diff --git a/.csharpierrc b/.csharpierrc new file mode 100644 index 00000000000..987d5fa55c5 --- /dev/null +++ b/.csharpierrc @@ -0,0 +1,6 @@ +{ + "printWidth": 180, + "useTabs": false, + "tabWidth": 4, + "endOfLine": "auto" +} diff --git a/.vscode/settings.json b/.vscode/settings.json index 944e8ed31f8..d1c5c186c91 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,8 @@ // Place your settings in this file to overwrite default and user settings. { - "omnisharp.projectLoadTimeout": 600 + "omnisharp.projectLoadTimeout": 600, + "[csharp]": { + "editor.defaultFormatter": "csharpier.csharpier-vscode", + "editor.formatOnSave": true + } } diff --git a/src/OrchardCore.Cms.Web/Program.cs b/src/OrchardCore.Cms.Web/Program.cs index f5e06716d21..bab06133767 100644 --- a/src/OrchardCore.Cms.Web/Program.cs +++ b/src/OrchardCore.Cms.Web/Program.cs @@ -4,9 +4,7 @@ builder.Host.UseNLogHost(); -builder.Services - .AddOrchardCms() - .AddSetupFeatures("OrchardCore.AutoSetup"); +builder.Services.AddOrchardCms().AddSetupFeatures("OrchardCore.AutoSetup"); var app = builder.Build(); diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/AdminAreaControllerRouteMapper.cs b/src/OrchardCore.Modules/OrchardCore.Admin/AdminAreaControllerRouteMapper.cs index edb28f9d77b..98eeb832af0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/AdminAreaControllerRouteMapper.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/AdminAreaControllerRouteMapper.cs @@ -48,10 +48,7 @@ public bool TryMapAreaControllerRoute(IEndpointRouteBuilder routes, ControllerAc var action = descriptor.ActionName; routes.MapAreaControllerRoute( - name: name? - .Replace("{area}", area) - .Replace("{controller}", controller) - .Replace("{action}", action) ?? descriptor.DisplayName, + name: name?.Replace("{area}", area).Replace("{controller}", controller).Replace("{action}", action) ?? descriptor.DisplayName, areaName: area, pattern: $"{_adminUrlPrefix}/{pattern.TrimStart('/').Replace("{action}", action)}", defaults: new { controller, action } diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Admin/AdminMenu.cs index dea3065f327..a31f486f4bf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/AdminMenu.cs @@ -8,11 +8,7 @@ namespace OrchardCore.Admin { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", AdminSiteSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", AdminSiteSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -28,17 +24,20 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Admin"], S["Admin"].PrefixPosition(), admin => admin - .AddClass("admin").Id("admin") - .Action("Index", "Admin", _routeValues) - .Permission(PermissionsAdminSettings.ManageAdminSettings) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Admin"], + S["Admin"].PrefixPosition(), + admin => + admin.AddClass("admin").Id("admin").Action("Index", "Admin", _routeValues).Permission(PermissionsAdminSettings.ManageAdminSettings).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/AdminMenuFilter.cs b/src/OrchardCore.Modules/OrchardCore.Admin/AdminMenuFilter.cs index 462f2338179..505a47e56bd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/AdminMenuFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/AdminMenuFilter.cs @@ -16,8 +16,7 @@ public class AdminMenuFilter : IAsyncResultFilter private readonly ILayoutAccessor _layoutAccessor; private readonly IShapeFactory _shapeFactory; - public AdminMenuFilter(ILayoutAccessor layoutAccessor, - IShapeFactory shapeFactory) + public AdminMenuFilter(ILayoutAccessor layoutAccessor, IShapeFactory shapeFactory) { _layoutAccessor = layoutAccessor; _shapeFactory = shapeFactory; @@ -55,12 +54,7 @@ public async Task OnResultExecutionAsync(ResultExecutingContext filterContext, R } // Populate main nav - var menuShape = await _shapeFactory.CreateAsync("Navigation", - Arguments.From(new - { - MenuName = NavigationConstants.AdminId, - filterContext.RouteData, - })); + var menuShape = await _shapeFactory.CreateAsync("Navigation", Arguments.From(new { MenuName = NavigationConstants.AdminId, filterContext.RouteData, })); var layout = await _layoutAccessor.GetLayoutAsync(); diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/AdminPageRouteModelProvider.cs b/src/OrchardCore.Modules/OrchardCore.Admin/AdminPageRouteModelProvider.cs index 3dec3ac2d46..e9a435dbc51 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/AdminPageRouteModelProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/AdminPageRouteModelProvider.cs @@ -67,9 +67,7 @@ public void OnProvidersExecuting(PageRouteModelProviderContext context) } } - public void OnProvidersExecuted(PageRouteModelProviderContext context) - { - } + public void OnProvidersExecuted(PageRouteModelProviderContext context) { } private static IEnumerable GetPageDescriptors(ApplicationPartManager applicationManager) where T : ViewsFeature, new() @@ -94,10 +92,10 @@ private static IEnumerable GetPageDescriptors(Applica } } - private static bool IsRazorPage(CompiledViewDescriptor viewDescriptor) => - viewDescriptor.Item?.Kind == RazorPageDocumentClassifierPass.RazorPageDocumentKind; + private static bool IsRazorPage(CompiledViewDescriptor viewDescriptor) => viewDescriptor.Item?.Kind == RazorPageDocumentClassifierPass.RazorPageDocumentKind; - private static T GetViewFeature(ApplicationPartManager applicationManager) where T : ViewsFeature, new() + private static T GetViewFeature(ApplicationPartManager applicationManager) + where T : ViewsFeature, new() { var viewsFeature = new T(); applicationManager.PopulateFeature(viewsFeature); diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/AdminThemeSelector.cs b/src/OrchardCore.Modules/OrchardCore.Admin/AdminThemeSelector.cs index a5c3659139b..bc984edd872 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/AdminThemeSelector.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/AdminThemeSelector.cs @@ -14,10 +14,7 @@ public class AdminThemeSelector : IThemeSelector private readonly IAdminThemeService _adminThemeService; private readonly IHttpContextAccessor _httpContextAccessor; - public AdminThemeSelector( - IAdminThemeService adminThemeService, - IHttpContextAccessor httpContextAccessor - ) + public AdminThemeSelector(IAdminThemeService adminThemeService, IHttpContextAccessor httpContextAccessor) { _adminThemeService = adminThemeService; _httpContextAccessor = httpContextAccessor; @@ -33,11 +30,7 @@ public async Task GetThemeAsync() return null; } - return new ThemeSelectorResult - { - Priority = 100, - ThemeName = adminThemeName - }; + return new ThemeSelectorResult { Priority = 100, ThemeName = adminThemeName }; } return null; diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/AdminThemeService.cs b/src/OrchardCore.Modules/OrchardCore.Admin/AdminThemeService.cs index 08a0f538e8e..6d702a16b12 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/AdminThemeService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/AdminThemeService.cs @@ -9,9 +9,7 @@ public class AdminThemeService : IAdminThemeService private readonly ISiteService _siteService; private readonly IExtensionManager _extensionManager; - public AdminThemeService( - ISiteService siteService, - IExtensionManager extensionManager) + public AdminThemeService(ISiteService siteService, IExtensionManager extensionManager) { _siteService = siteService; _extensionManager = extensionManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/Drivers/AdminSiteSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Admin/Drivers/AdminSiteSettingsDisplayDriver.cs index 81b9665bf23..8a093d51050 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/Drivers/AdminSiteSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/Drivers/AdminSiteSettingsDisplayDriver.cs @@ -17,9 +17,7 @@ public class AdminSiteSettingsDisplayDriver : SectionDisplayDriver EditAsync(AdminSettings settings, Bui return null; } - return Initialize("AdminSettings_Edit", model => - { - model.DisplayThemeToggler = settings.DisplayThemeToggler; - model.DisplayMenuFilter = settings.DisplayMenuFilter; - model.DisplayNewMenu = settings.DisplayNewMenu; - model.DisplayTitlesInTopbar = settings.DisplayTitlesInTopbar; - }).Location("Content:3").OnGroup(GroupId); + return Initialize( + "AdminSettings_Edit", + model => + { + model.DisplayThemeToggler = settings.DisplayThemeToggler; + model.DisplayMenuFilter = settings.DisplayMenuFilter; + model.DisplayNewMenu = settings.DisplayNewMenu; + model.DisplayTitlesInTopbar = settings.DisplayTitlesInTopbar; + } + ) + .Location("Content:3") + .OnGroup(GroupId); } public override async Task UpdateAsync(AdminSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/Drivers/VisitSiteNavbarDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Admin/Drivers/VisitSiteNavbarDisplayDriver.cs index 8a330c67d4e..46a93f7707d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/Drivers/VisitSiteNavbarDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/Drivers/VisitSiteNavbarDisplayDriver.cs @@ -8,7 +8,6 @@ public class VisitSiteNavbarDisplayDriver : DisplayDriver { public override IDisplayResult Display(Navbar model) { - return View("VisitSiteNavbarItem", model) - .Location("DetailAdmin", "Content:20"); + return View("VisitSiteNavbarItem", model).Location("DetailAdmin", "Content:20"); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Admin/Manifest.cs index d97764dd742..00cd77b25c3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/Manifest.cs @@ -7,8 +7,5 @@ Version = ManifestConstants.OrchardCoreVersion, Description = "Creates an admin section for the site.", Category = "Infrastructure", - Dependencies = - [ - "OrchardCore.Settings" - ] + Dependencies = ["OrchardCore.Settings"] )] diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Admin/Permissions.cs index fac741d8475..3796fd5b47a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/Permissions.cs @@ -8,40 +8,16 @@ public class Permissions : IPermissionProvider { public static readonly Permission AccessAdminPanel = new("AccessAdminPanel", "Access admin panel"); - private readonly IEnumerable _allPermissions = - [ - AccessAdminPanel, - ]; + private readonly IEnumerable _allPermissions = [AccessAdminPanel,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Moderator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Author", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Contributor", - Permissions = _allPermissions, - }, - ]; + [ + new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Editor", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Moderator", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Author", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Contributor", Permissions = _allPermissions, }, + ]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/PermissionsAdminSettings.cs b/src/OrchardCore.Modules/OrchardCore.Admin/PermissionsAdminSettings.cs index 85189fb4d2a..b9a19f90d6d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/PermissionsAdminSettings.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/PermissionsAdminSettings.cs @@ -8,20 +8,9 @@ public class PermissionsAdminSettings : IPermissionProvider { public static readonly Permission ManageAdminSettings = new("ManageAdminSettings", "Manage Admin Settings"); - private readonly IEnumerable _allPermissions = - [ - ManageAdminSettings, - ]; + private readonly IEnumerable _allPermissions = [ManageAdminSettings,]; - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); } diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Admin/Startup.cs index 7d08f46eabb..fd5d4d80be4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/Startup.cs @@ -38,14 +38,16 @@ public override void ConfigureServices(IServiceCollection services) { services.AddNavigation(); - services.Configure((options) => - { - options.Filters.Add(typeof(AdminFilter)); - options.Filters.Add(typeof(AdminMenuFilter)); + services.Configure( + (options) => + { + options.Filters.Add(typeof(AdminFilter)); + options.Filters.Add(typeof(AdminMenuFilter)); - // Ordered to be called before any global filter. - options.Filters.Add(typeof(AdminZoneFilter), -1000); - }); + // Ordered to be called before any global filter. + options.Filters.Add(typeof(AdminZoneFilter), -1000); + } + ); services.AddTransient(); services.AddScoped(); @@ -77,11 +79,13 @@ public class AdminPagesStartup : StartupBase public override void ConfigureServices(IServiceCollection services) { - services.Configure((options) => - { - var adminOptions = ShellScope.Services.GetRequiredService>().Value; - options.Conventions.Add(new AdminPageRouteModelConvention(adminOptions.AdminUrlPrefix)); - }); + services.Configure( + (options) => + { + var adminOptions = ShellScope.Services.GetRequiredService>().Value; + options.Conventions.Add(new AdminPageRouteModelConvention(adminOptions.AdminUrlPrefix)); + } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Controllers/DashboardController.cs b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Controllers/DashboardController.cs index 3abf427168d..fdcf0fc967e 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Controllers/DashboardController.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Controllers/DashboardController.cs @@ -36,7 +36,8 @@ public DashboardController( IContentItemDisplayManager contentItemDisplayManager, IContentDefinitionManager contentDefinitionManager, IUpdateModelAccessor updateModelAccessor, - YesSql.ISession session) + YesSql.ISession session + ) { _authorizationService = authorizationService; _adminDashboardService = adminDashboardService; @@ -49,10 +50,7 @@ public DashboardController( public async Task Index() { - var model = new AdminDashboardViewModel() - { - CanManageDashboard = await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminDashboard), - }; + var model = new AdminDashboardViewModel() { CanManageDashboard = await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminDashboard), }; if (model.CanManageDashboard || await _authorizationService.AuthorizeAsync(User, Permissions.AccessAdminDashboard)) { @@ -72,11 +70,13 @@ public async Task Index() continue; } - wrappers.Add(new DashboardWrapper - { - Dashboard = widget, - Content = await _contentItemDisplayManager.BuildDisplayAsync(widget, _updateModelAccessor.ModelUpdater, "DetailAdmin") - }); + wrappers.Add( + new DashboardWrapper + { + Dashboard = widget, + Content = await _contentItemDisplayManager.BuildDisplayAsync(widget, _updateModelAccessor.ModelUpdater, "DetailAdmin") + } + ); } model.Dashboards = wrappers.ToArray(); @@ -94,10 +94,7 @@ public async Task Manage() } // Set Manage Dashboard Feature. - Request.HttpContext.Features.Set(new DashboardFeature() - { - IsManageRequest = true - }); + Request.HttpContext.Features.Set(new DashboardFeature() { IsManageRequest = true }); var dashboardCreatable = new List(); var widgetContentTypes = await GetDashboardWidgetsAsync(); @@ -118,8 +115,10 @@ public async Task Manage() var wrappers = new List(); foreach (var widget in widgets) { - if (!widgetContentTypes.ContainsKey(widget.ContentType) - || !await _authorizationService.AuthorizeContentTypeAsync(User, CommonPermissions.EditContent, widget.ContentType, userId)) + if ( + !widgetContentTypes.ContainsKey(widget.ContentType) + || !await _authorizationService.AuthorizeContentTypeAsync(User, CommonPermissions.EditContent, widget.ContentType, userId) + ) { continue; } @@ -133,11 +132,7 @@ public async Task Manage() wrappers.Add(wrapper); } - var model = new AdminDashboardViewModel - { - Dashboards = wrappers.ToArray(), - Creatable = dashboardCreatable - }; + var model = new AdminDashboardViewModel { Dashboards = wrappers.ToArray(), Creatable = dashboardCreatable }; return View(model); } @@ -203,9 +198,7 @@ public async Task Update([FromForm] DashboardPartViewModel[] part return RedirectToAction(nameof(Manage)); } - private async Task> GetDashboardWidgetsAsync() - => (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(t => t.StereotypeEquals("DashboardWidget")) - .ToDictionary(ctd => ctd.Name, ctd => ctd); + private async Task> GetDashboardWidgetsAsync() => + (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(t => t.StereotypeEquals("DashboardWidget")).ToDictionary(ctd => ctd.Name, ctd => ctd); } } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Drivers/DashboardContentDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Drivers/DashboardContentDisplayDriver.cs index 8af3f6a082d..78d8aff560e 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Drivers/DashboardContentDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Drivers/DashboardContentDisplayDriver.cs @@ -9,7 +9,6 @@ using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.Views; - namespace OrchardCore.AdminDashboard.Drivers { public class DashboardContentDisplayDriver : ContentDisplayDriver @@ -18,15 +17,11 @@ public class DashboardContentDisplayDriver : ContentDisplayDriver private readonly IAuthorizationService _authorizationService; private readonly IContentManager _contentManager; - - public DashboardContentDisplayDriver(IHttpContextAccessor httpContextAccessor, - IAuthorizationService authorizationService, - IContentManager contentManager) + public DashboardContentDisplayDriver(IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService, IContentManager contentManager) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; _contentManager = contentManager; - } public override async Task DisplayAsync(ContentItem model, BuildDisplayContext context) @@ -34,7 +29,7 @@ public override async Task DisplayAsync(ContentItem model, Build var httpContext = _httpContextAccessor.HttpContext; var dashboardFeature = httpContext.Features.Get(); - // Return if it's not Manage dashboard request + // Return if it's not Manage dashboard request if (dashboardFeature == null || !dashboardFeature.IsManageRequest) { return null; @@ -47,61 +42,89 @@ public override async Task DisplayAsync(ContentItem model, Build var hasDeletePermission = await _authorizationService.AuthorizeAsync(httpContext.User, CommonPermissions.DeleteContent, model); var hasPublishPermission = await _authorizationService.AuthorizeAsync(httpContext.User, CommonPermissions.PublishContent, model); - var dragHandle = Initialize("Dashboard_DragHandle", m => - { - m.ContentItem = model; - }).Location("Leading:before"); + var dragHandle = Initialize( + "Dashboard_DragHandle", + m => + { + m.ContentItem = model; + } + ) + .Location("Leading:before"); results.Add(dragHandle); if (hasEditPermission) { - var editButton = Initialize("Dashboard_EditButton", m => - { - m.ContentItem = model; - }).Location("ActionsMenu:after"); + var editButton = Initialize( + "Dashboard_EditButton", + m => + { + m.ContentItem = model; + } + ) + .Location("ActionsMenu:after"); results.Add(editButton); } if (hasDeletePermission) { - var deleteButton = Initialize("Dashboard_DeleteButton", m => - { - m.ContentItem = model; - }).Location("ActionsMenu:after"); + var deleteButton = Initialize( + "Dashboard_DeleteButton", + m => + { + m.ContentItem = model; + } + ) + .Location("ActionsMenu:after"); results.Add(deleteButton); } if (hasPublished && hasPublishPermission) { - var unpublishButton = Initialize("Dashboard_UnpublishButton", m => - { - m.ContentItem = model; - }).Location("ActionsMenu:after"); + var unpublishButton = Initialize( + "Dashboard_UnpublishButton", + m => + { + m.ContentItem = model; + } + ) + .Location("ActionsMenu:after"); results.Add(unpublishButton); } if (hasDraft && hasPublishPermission) { - var publishButton = Initialize("Dashboard_PublishButton", m => - { - m.ContentItem = model; - }).Location("ActionsMenu:after"); + var publishButton = Initialize( + "Dashboard_PublishButton", + m => + { + m.ContentItem = model; + } + ) + .Location("ActionsMenu:after"); results.Add(publishButton); } if (hasDraft && hasEditPermission) { - var discardDraftButton = Initialize("Dashboard_DiscardDraftButton", m => - { - m.ContentItem = model; - }).Location("ActionsMenu:after"); + var discardDraftButton = Initialize( + "Dashboard_DiscardDraftButton", + m => + { + m.ContentItem = model; + } + ) + .Location("ActionsMenu:after"); results.Add(discardDraftButton); } - var shapeTag = Initialize("DashboardWidget_DetailAdmin__ContentsTags", m => - { - m.ContentItem = model; - }).Location("DetailAdmin", "Tags:10"); + var shapeTag = Initialize( + "DashboardWidget_DetailAdmin__ContentsTags", + m => + { + m.ContentItem = model; + } + ) + .Location("DetailAdmin", "Tags:10"); results.Add(shapeTag); return Combine(results.ToArray()); diff --git a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Indexes/DashboardPartIndex.cs b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Indexes/DashboardPartIndex.cs index 4e70965687d..076bfce5ed5 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Indexes/DashboardPartIndex.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Indexes/DashboardPartIndex.cs @@ -13,7 +13,8 @@ public class DashboardPartIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(contentItem => { var dashboardPart = contentItem.As(); @@ -26,10 +27,7 @@ public override void Describe(DescribeContext context) if (dashboardPart != null) { - return new DashboardPartIndex - { - Position = dashboardPart.Position, - }; + return new DashboardPartIndex { Position = dashboardPart.Position, }; } return null; diff --git a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Manifest.cs index 09f0474515c..122ff332ff2 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Manifest.cs @@ -6,12 +6,6 @@ Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion, Description = "Allows to organize widgets in an Admin Dashboard.", - Dependencies = - [ - "OrchardCore.Admin", - "OrchardCore.Html", - "OrchardCore.Title", - "OrchardCore.Recipes.Core", - ], + Dependencies = ["OrchardCore.Admin", "OrchardCore.Html", "OrchardCore.Title", "OrchardCore.Recipes.Core",], Category = "Content Management" )] diff --git a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Migrations.cs index 2074fd88558..c04eab26a4f 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Migrations.cs @@ -22,20 +22,14 @@ public Migrations(IContentDefinitionManager contentDefinitionManager, IRecipeMig public async Task CreateAsync() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("Position") - ); + await SchemaBuilder.CreateMapIndexTableAsync(table => table.Column("Position")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DashboardPart_DocumentId", - "DocumentId", - "Position") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_DashboardPart_DocumentId", "DocumentId", "Position")); - await _contentDefinitionManager.AlterPartDefinitionAsync("DashboardPart", builder => builder - .Attachable() - .WithDescription("Provides a way to add widgets to a dashboard.") - ); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "DashboardPart", + builder => builder.Attachable().WithDescription("Provides a way to add widgets to a dashboard.") + ); await _recipeMigrator.ExecuteAsync($"dashboard-widgets{RecipesConstants.RecipeExtension}", this); @@ -53,11 +47,7 @@ public async Task UpdateFrom1Async() // This code can be removed in a later version. public async Task UpdateFrom2Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DashboardPart_DocumentId", - "DocumentId", - "Position") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_DashboardPart_DocumentId", "DocumentId", "Position")); return 3; } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Permissions.cs index e59d0afd210..2a6fc08dbb4 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Permissions.cs @@ -9,46 +9,18 @@ public class Permissions : IPermissionProvider public static readonly Permission ManageAdminDashboard = new("ManageAdminDashboard", "Manage the Admin Dashboard"); public static readonly Permission AccessAdminDashboard = new("AccessAdminDashboard", "Access the Admin Dashboard", new[] { ManageAdminDashboard }); - private readonly IEnumerable _allPermissions = - [ - AccessAdminDashboard, - ManageAdminDashboard, - ]; + private readonly IEnumerable _allPermissions = [AccessAdminDashboard, ManageAdminDashboard,]; - private readonly IEnumerable _generalPermissions = - [ - AccessAdminDashboard, - ]; + private readonly IEnumerable _generalPermissions = [AccessAdminDashboard,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Moderator", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Author", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Contributor", - Permissions = _generalPermissions, - }, - ]; + [ + new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Editor", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Moderator", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Author", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Contributor", Permissions = _generalPermissions, }, + ]; } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Services/AdminDashboardService.cs b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Services/AdminDashboardService.cs index f9d03c02c90..5fb0fc4efb0 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Services/AdminDashboardService.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Services/AdminDashboardService.cs @@ -20,11 +20,7 @@ public AdminDashboardService(ISession session) public async Task> GetWidgetsAsync(Expression> predicate) { - var widgets = await _session - .Query() - .OrderBy(w => w.Position) - .With(predicate) - .ListAsync(); + var widgets = await _session.Query().OrderBy(w => w.Position).With(predicate).ListAsync(); return widgets; } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Startup.cs b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Startup.cs index 948fa32d074..a1faea72ef4 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/Startup.cs @@ -37,8 +37,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddIndexProvider(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/ViewModels/DashboardWrapper.cs b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/ViewModels/DashboardWrapper.cs index cf293deeb7b..af0fd82c1b6 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminDashboard/ViewModels/DashboardWrapper.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminDashboard/ViewModels/DashboardWrapper.cs @@ -6,12 +6,10 @@ namespace OrchardCore.AdminDashboard.ViewModels { public class DashboardWrapper : ShapeViewModel { - public DashboardWrapper() : base("Dashboard_Wrapper") - { - } + public DashboardWrapper() + : base("Dashboard_Wrapper") { } public ContentItem Dashboard { get; set; } public IShape Content { get; set; } } - } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminMenu.cs index 84e2721d894..52d8370851e 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminMenu.cs @@ -10,8 +10,7 @@ public class AdminMenu : INavigationProvider private readonly AdminMenuNavigationProvidersCoordinator _adminMenuNavigationProvider; private protected IStringLocalizer S; - public AdminMenu(AdminMenuNavigationProvidersCoordinator adminMenuNavigationProvider, - IStringLocalizer localizer) + public AdminMenu(AdminMenuNavigationProvidersCoordinator adminMenuNavigationProvider, IStringLocalizer localizer) { _adminMenuNavigationProvider = adminMenuNavigationProvider; S = localizer; @@ -25,14 +24,15 @@ public async Task BuildNavigationAsync(string name, NavigationBuilder builder) } // Configuration and settings menus for the AdminMenu module - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Admin Menus"], S["Admin Menus"].PrefixPosition(), adminMenu => adminMenu - .Permission(Permissions.ManageAdminMenu) - .Action("List", "Menu", "OrchardCore.AdminMenu") - .LocalNav() + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Admin Menus"], + S["Admin Menus"].PrefixPosition(), + adminMenu => adminMenu.Permission(Permissions.ManageAdminMenu).Action("List", "Menu", "OrchardCore.AdminMenu").LocalNav() ) - ); + ); // This is the entry point for the adminMenu: dynamically generated custom admin menus await _adminMenuNavigationProvider.BuildNavigationAsync(NavigationConstants.AdminMenuId, builder); diff --git a/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/LinkAdminNodeDriver.cs b/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/LinkAdminNodeDriver.cs index 8b46ca2bf06..0d329c1ae54 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/LinkAdminNodeDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/LinkAdminNodeDriver.cs @@ -28,29 +28,23 @@ public override IDisplayResult Display(LinkAdminNode treeNode) public override IDisplayResult Edit(LinkAdminNode treeNode) { - return Initialize("LinkAdminNode_Fields_TreeEdit", async model => - { - model.LinkText = treeNode.LinkText; - model.LinkUrl = treeNode.LinkUrl; - model.IconClass = treeNode.IconClass; + return Initialize( + "LinkAdminNode_Fields_TreeEdit", + async model => + { + model.LinkText = treeNode.LinkText; + model.LinkUrl = treeNode.LinkUrl; + model.IconClass = treeNode.IconClass; - var permissions = await _adminMenuPermissionService.GetPermissionsAsync(); + var permissions = await _adminMenuPermissionService.GetPermissionsAsync(); - var selectedPermissions = permissions.Where(p => treeNode.PermissionNames.Contains(p.Name)); + var selectedPermissions = permissions.Where(p => treeNode.PermissionNames.Contains(p.Name)); - model.SelectedItems = selectedPermissions - .Select(p => new PermissionViewModel - { - Name = p.Name, - DisplayText = p.Description - }).ToList(); - model.AllItems = permissions - .Select(p => new PermissionViewModel - { - Name = p.Name, - DisplayText = p.Description - }).ToList(); - }).Location("Content"); + model.SelectedItems = selectedPermissions.Select(p => new PermissionViewModel { Name = p.Name, DisplayText = p.Description }).ToList(); + model.AllItems = permissions.Select(p => new PermissionViewModel { Name = p.Name, DisplayText = p.Description }).ToList(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(LinkAdminNode treeNode, IUpdateModel updater) @@ -65,9 +59,7 @@ public override async Task UpdateAsync(LinkAdminNode treeNode, I var selectedPermissions = (model.SelectedPermissionNames == null ? [] : model.SelectedPermissionNames.Split(',', StringSplitOptions.RemoveEmptyEntries)); var permissions = await _adminMenuPermissionService.GetPermissionsAsync(); - treeNode.PermissionNames = permissions - .Where(p => selectedPermissions.Contains(p.Name)) - .Select(p => p.Name).ToArray(); + treeNode.PermissionNames = permissions.Where(p => selectedPermissions.Contains(p.Name)).Select(p => p.Name).ToArray(); } return Edit(treeNode); diff --git a/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/LinkAdminNodeNavigationBuilder.cs b/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/LinkAdminNodeNavigationBuilder.cs index 8bd05d0460f..f6a16a6ec0a 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/LinkAdminNodeNavigationBuilder.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/LinkAdminNodeNavigationBuilder.cs @@ -17,11 +17,11 @@ public class LinkAdminNodeNavigationBuilder : IAdminNodeNavigationBuilder private readonly IAdminMenuPermissionService _adminMenuPermissionService; private readonly AdminOptions _adminOptions; - public LinkAdminNodeNavigationBuilder( IAdminMenuPermissionService adminMenuPermissionService, IOptions adminOptions, - ILogger logger) + ILogger logger + ) { _adminMenuPermissionService = adminMenuPermissionService; _adminOptions = adminOptions.Value; @@ -38,58 +38,62 @@ public Task BuildNavigationAsync(MenuItem menuItem, NavigationBuilder builder, I return Task.CompletedTask; } - return builder.AddAsync(new LocalizedString(node.LinkText, node.LinkText), async itemBuilder => - { - var nodeLinkUrl = node.LinkUrl; - if (!string.IsNullOrEmpty(nodeLinkUrl) && nodeLinkUrl[0] != '/' && !nodeLinkUrl.Contains("://")) + return builder.AddAsync( + new LocalizedString(node.LinkText, node.LinkText), + async itemBuilder => { - if (nodeLinkUrl.StartsWith("~/", StringComparison.Ordinal)) + var nodeLinkUrl = node.LinkUrl; + if (!string.IsNullOrEmpty(nodeLinkUrl) && nodeLinkUrl[0] != '/' && !nodeLinkUrl.Contains("://")) { - nodeLinkUrl = nodeLinkUrl[2..]; - } + if (nodeLinkUrl.StartsWith("~/", StringComparison.Ordinal)) + { + nodeLinkUrl = nodeLinkUrl[2..]; + } - // Check if the first segment of 'nodeLinkUrl' is not equal to the admin prefix. - if (!nodeLinkUrl.StartsWith($"{_adminOptions.AdminUrlPrefix}", StringComparison.OrdinalIgnoreCase) || - (nodeLinkUrl.Length != _adminOptions.AdminUrlPrefix.Length - && nodeLinkUrl[_adminOptions.AdminUrlPrefix.Length] != '/')) - { - nodeLinkUrl = $"{_adminOptions.AdminUrlPrefix}/{nodeLinkUrl}"; + // Check if the first segment of 'nodeLinkUrl' is not equal to the admin prefix. + if ( + !nodeLinkUrl.StartsWith($"{_adminOptions.AdminUrlPrefix}", StringComparison.OrdinalIgnoreCase) + || (nodeLinkUrl.Length != _adminOptions.AdminUrlPrefix.Length && nodeLinkUrl[_adminOptions.AdminUrlPrefix.Length] != '/') + ) + { + nodeLinkUrl = $"{_adminOptions.AdminUrlPrefix}/{nodeLinkUrl}"; + } } - } - // Add the actual link. - itemBuilder.Url(nodeLinkUrl); - itemBuilder.Priority(node.Priority); - itemBuilder.Position(node.Position); + // Add the actual link. + itemBuilder.Url(nodeLinkUrl); + itemBuilder.Priority(node.Priority); + itemBuilder.Position(node.Position); - if (node.PermissionNames.Length > 0) - { - var permissions = await _adminMenuPermissionService.GetPermissionsAsync(); + if (node.PermissionNames.Length > 0) + { + var permissions = await _adminMenuPermissionService.GetPermissionsAsync(); - // Find the actual permissions and apply them to the menu. - var selectedPermissions = permissions.Where(p => node.PermissionNames.Contains(p.Name)); - itemBuilder.Permissions(selectedPermissions); - } + // Find the actual permissions and apply them to the menu. + var selectedPermissions = permissions.Where(p => node.PermissionNames.Contains(p.Name)); + itemBuilder.Permissions(selectedPermissions); + } - // Add adminNode's IconClass property values to menuItem.Classes. - // Add them with a prefix so that later the shape template can extract them to use them on a tag. - node.IconClass?.Split(' ').ToList().ForEach(c => itemBuilder.AddClass("icon-class-" + c)); + // Add adminNode's IconClass property values to menuItem.Classes. + // Add them with a prefix so that later the shape template can extract them to use them on a tag. + node.IconClass?.Split(' ').ToList().ForEach(c => itemBuilder.AddClass("icon-class-" + c)); - // Let children build themselves inside this MenuItem. - // Todo: This logic can be shared by all TreeNodeNavigationBuilders. - foreach (var childTreeNode in menuItem.Items) - { - try - { - var treeBuilder = treeNodeBuilders.FirstOrDefault(x => x.Name == childTreeNode.GetType().Name); - await treeBuilder.BuildNavigationAsync(childTreeNode, itemBuilder, treeNodeBuilders); - } - catch (Exception e) + // Let children build themselves inside this MenuItem. + // Todo: This logic can be shared by all TreeNodeNavigationBuilders. + foreach (var childTreeNode in menuItem.Items) { - _logger.LogError(e, "An exception occurred while building the '{MenuItem}' child Menu Item.", childTreeNode.GetType().Name); + try + { + var treeBuilder = treeNodeBuilders.FirstOrDefault(x => x.Name == childTreeNode.GetType().Name); + await treeBuilder.BuildNavigationAsync(childTreeNode, itemBuilder, treeNodeBuilders); + } + catch (Exception e) + { + _logger.LogError(e, "An exception occurred while building the '{MenuItem}' child Menu Item.", childTreeNode.GetType().Name); + } } } - }); + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/PlaceholderAdminNodeDriver.cs b/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/PlaceholderAdminNodeDriver.cs index 9976d19a583..48a643dc791 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/PlaceholderAdminNodeDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/PlaceholderAdminNodeDriver.cs @@ -28,28 +28,22 @@ public override IDisplayResult Display(PlaceholderAdminNode treeNode) public override IDisplayResult Edit(PlaceholderAdminNode treeNode) { - return Initialize("PlaceholderAdminNode_Fields_TreeEdit", async model => - { - model.LinkText = treeNode.LinkText; - model.IconClass = treeNode.IconClass; + return Initialize( + "PlaceholderAdminNode_Fields_TreeEdit", + async model => + { + model.LinkText = treeNode.LinkText; + model.IconClass = treeNode.IconClass; - var permissions = await _adminMenuPermissionService.GetPermissionsAsync(); + var permissions = await _adminMenuPermissionService.GetPermissionsAsync(); - var selectedPermissions = permissions.Where(p => treeNode.PermissionNames.Contains(p.Name)); + var selectedPermissions = permissions.Where(p => treeNode.PermissionNames.Contains(p.Name)); - model.SelectedItems = selectedPermissions - .Select(p => new PermissionViewModel - { - Name = p.Name, - DisplayText = p.Description - }).ToList(); - model.AllItems = permissions - .Select(p => new PermissionViewModel - { - Name = p.Name, - DisplayText = p.Description - }).ToList(); - }).Location("Content"); + model.SelectedItems = selectedPermissions.Select(p => new PermissionViewModel { Name = p.Name, DisplayText = p.Description }).ToList(); + model.AllItems = permissions.Select(p => new PermissionViewModel { Name = p.Name, DisplayText = p.Description }).ToList(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(PlaceholderAdminNode treeNode, IUpdateModel updater) @@ -60,11 +54,11 @@ public override async Task UpdateAsync(PlaceholderAdminNode tree treeNode.LinkText = model.LinkText; treeNode.IconClass = model.IconClass; - var selectedPermissions = (model.SelectedPermissionNames == null ? Array.Empty() : model.SelectedPermissionNames.Split(',', StringSplitOptions.RemoveEmptyEntries)); + var selectedPermissions = ( + model.SelectedPermissionNames == null ? Array.Empty() : model.SelectedPermissionNames.Split(',', StringSplitOptions.RemoveEmptyEntries) + ); var permissions = await _adminMenuPermissionService.GetPermissionsAsync(); - treeNode.PermissionNames = permissions - .Where(p => selectedPermissions.Contains(p.Name)) - .Select(p => p.Name).ToArray(); + treeNode.PermissionNames = permissions.Where(p => selectedPermissions.Contains(p.Name)).Select(p => p.Name).ToArray(); } return Edit(treeNode); diff --git a/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/PlaceholderAdminNodeNavigationBuilder.cs b/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/PlaceholderAdminNodeNavigationBuilder.cs index d3128008e47..231ac276cd2 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/PlaceholderAdminNodeNavigationBuilder.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminMenu/AdminNodes/PlaceholderAdminNodeNavigationBuilder.cs @@ -31,38 +31,41 @@ public Task BuildNavigationAsync(MenuItem menuItem, NavigationBuilder builder, I return Task.CompletedTask; } - return builder.AddAsync(new LocalizedString(node.LinkText, node.LinkText), async itemBuilder => - { - itemBuilder.Priority(node.Priority); - itemBuilder.Position(node.Position); - - if (node.PermissionNames.Length > 0) + return builder.AddAsync( + new LocalizedString(node.LinkText, node.LinkText), + async itemBuilder => { - var permissions = await _adminMenuPermissionService.GetPermissionsAsync(); - // Find the actual permissions and apply them to the menu. - var selectedPermissions = permissions.Where(p => node.PermissionNames.Contains(p.Name)); - itemBuilder.Permissions(selectedPermissions); - } - - // Add adminNode's IconClass property values to menuItem.Classes. - // Add them with a prefix so that later the shape template can extract them to use them on a tag. - node.IconClass?.Split(' ').ToList().ForEach(c => itemBuilder.AddClass("icon-class-" + c)); + itemBuilder.Priority(node.Priority); + itemBuilder.Position(node.Position); - // Let children build themselves inside this MenuItem - // todo: this logic can be shared by all TreeNodeNavigationBuilders - foreach (var childTreeNode in menuItem.Items) - { - try + if (node.PermissionNames.Length > 0) { - var treeBuilder = treeNodeBuilders.FirstOrDefault(x => x.Name == childTreeNode.GetType().Name); - await treeBuilder.BuildNavigationAsync(childTreeNode, itemBuilder, treeNodeBuilders); + var permissions = await _adminMenuPermissionService.GetPermissionsAsync(); + // Find the actual permissions and apply them to the menu. + var selectedPermissions = permissions.Where(p => node.PermissionNames.Contains(p.Name)); + itemBuilder.Permissions(selectedPermissions); } - catch (Exception e) + + // Add adminNode's IconClass property values to menuItem.Classes. + // Add them with a prefix so that later the shape template can extract them to use them on a tag. + node.IconClass?.Split(' ').ToList().ForEach(c => itemBuilder.AddClass("icon-class-" + c)); + + // Let children build themselves inside this MenuItem + // todo: this logic can be shared by all TreeNodeNavigationBuilders + foreach (var childTreeNode in menuItem.Items) { - _logger.LogError(e, "An exception occurred while building the '{MenuItem}' child Menu Item.", childTreeNode.GetType().Name); + try + { + var treeBuilder = treeNodeBuilders.FirstOrDefault(x => x.Name == childTreeNode.GetType().Name); + await treeBuilder.BuildNavigationAsync(childTreeNode, itemBuilder, treeNodeBuilders); + } + catch (Exception e) + { + _logger.LogError(e, "An exception occurred while building the '{MenuItem}' child Menu Item.", childTreeNode.GetType().Name); + } } } - }); + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminMenu/Controllers/MenuController.cs b/src/OrchardCore.Modules/OrchardCore.AdminMenu/Controllers/MenuController.cs index 639adf36476..a15d51356a3 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminMenu/Controllers/MenuController.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminMenu/Controllers/MenuController.cs @@ -43,7 +43,8 @@ public MenuController( INotifier notifier, IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer, - ILogger logger) + ILogger logger + ) { _authorizationService = authorizationService; _adminMenuService = adminMenuService; @@ -79,10 +80,7 @@ public async Task List(ContentOptions options, PagerParameters pa // load at least the ones without error. Provide a way to delete the ones on error. try { - results = adminMenuList - .Skip(startIndex) - .Take(pageSize) - .ToList(); + results = adminMenuList.Skip(startIndex).Take(pageSize).ToList(); } catch (Exception ex) { @@ -107,21 +105,14 @@ public async Task List(ContentOptions options, PagerParameters pa Pager = pagerShape, }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(List))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(AdminMenuListViewModel model) - => RedirectToAction(nameof(List), new RouteValueDictionary - { - {_optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(AdminMenuListViewModel model) => RedirectToAction(nameof(List), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Create() { @@ -170,11 +161,7 @@ public async Task Edit(string id) return NotFound(); } - var model = new AdminMenuEditViewModel - { - Id = adminMenu.Id, - Name = adminMenu.Name - }; + var model = new AdminMenuEditViewModel { Id = adminMenu.Id, Name = adminMenu.Name }; return View(model); } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminMenu/Controllers/NodeController.cs b/src/OrchardCore.Modules/OrchardCore.AdminMenu/Controllers/NodeController.cs index dd3c9010614..5d1a6c64d88 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminMenu/Controllers/NodeController.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminMenu/Controllers/NodeController.cs @@ -25,7 +25,6 @@ public class NodeController : Controller protected readonly IHtmlLocalizer H; private readonly IUpdateModelAccessor _updateModelAccessor; - public NodeController( IAuthorizationService authorizationService, IDisplayManager displayManager, @@ -33,7 +32,8 @@ public NodeController( IAdminMenuService adminMenuService, IHtmlLocalizer htmlLocalizer, INotifier notifier, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _displayManager = displayManager; _factories = factories; @@ -73,11 +73,7 @@ private async Task BuildDisplayViewModel(Models.AdminMen thumbnails.Add(factory.Name, thumbnail); } - var model = new AdminNodeListViewModel - { - AdminMenu = tree, - Thumbnails = thumbnails, - }; + var model = new AdminNodeListViewModel { AdminMenu = tree, Thumbnails = thumbnails, }; return model; } @@ -306,8 +302,7 @@ public async Task Toggle(string id, string treeNodeId) } [HttpPost] - public async Task MoveNode(string treeId, string nodeToMoveId, - string destinationNodeId, int position) + public async Task MoveNode(string treeId, string nodeToMoveId, string destinationNodeId, int position) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu)) { diff --git a/src/OrchardCore.Modules/OrchardCore.AdminMenu/Deployment/AdminMenuDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.AdminMenu/Deployment/AdminMenuDeploymentSource.cs index e07ba5551ef..ebc5c0cfec0 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminMenu/Deployment/AdminMenuDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminMenu/Deployment/AdminMenuDeploymentSource.cs @@ -19,10 +19,7 @@ public AdminMenuDeploymentSource(IAdminMenuService adminMenuService, IOptions _generalPermissions = - [ - ManageAdminMenu, - ]; + private readonly IEnumerable _generalPermissions = [ManageAdminMenu,]; private readonly IAdminMenuService _adminMenuService; @@ -28,11 +25,7 @@ public async Task> GetPermissionsAsync() { var adminMenuItems = (await _adminMenuService.GetAdminMenuListAsync()).AdminMenu; - var permissions = new List(adminMenuItems.Count + 2) - { - ViewAdminMenuAll, - ManageAdminMenu, - }; + var permissions = new List(adminMenuItems.Count + 2) { ViewAdminMenuAll, ManageAdminMenu, }; foreach (var adminMenu in adminMenuItems) { @@ -43,23 +36,11 @@ public async Task> GetPermissionsAsync() } public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _generalPermissions, - }, - ]; + [ + new PermissionStereotype { Name = "Administrator", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Editor", Permissions = _generalPermissions, }, + ]; - public static Permission CreatePermissionForAdminMenu(string name) - => new( - string.Format(_viewAdminMenu.Name, name), - string.Format(_viewAdminMenu.Description, name), - _viewAdminMenu.ImpliedBy - ); + public static Permission CreatePermissionForAdminMenu(string name) => + new(string.Format(_viewAdminMenu.Name, name), string.Format(_viewAdminMenu.Description, name), _viewAdminMenu.ImpliedBy); } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminMenu/Recipes/AdminMenuStep.cs b/src/OrchardCore.Modules/OrchardCore.AdminMenu/Recipes/AdminMenuStep.cs index 1e578340f61..e9c300d3487 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminMenu/Recipes/AdminMenuStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminMenu/Recipes/AdminMenuStep.cs @@ -25,10 +25,7 @@ public AdminMenuStep(IAdminMenuService adminMenuService, IOptions nodeBuilders, - ILogger logger) + ILogger logger + ) { _adminMenuService = adminMenuService; _authorizationService = authorizationService; @@ -42,14 +43,11 @@ public async Task BuildNavigationAsync(string name, NavigationBuilder builder) return; } - var trees = (await _adminMenuService.GetAdminMenuListAsync()) - .AdminMenu.Where(m => m.Enabled && m.MenuItems.Count > 0); + var trees = (await _adminMenuService.GetAdminMenuListAsync()).AdminMenu.Where(m => m.Enabled && m.MenuItems.Count > 0); foreach (var tree in trees) { - if (await _authorizationService.AuthorizeAsync( - _httpContextAccessor.HttpContext?.User, - Permissions.CreatePermissionForAdminMenu(tree.Name))) + if (await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, Permissions.CreatePermissionForAdminMenu(tree.Name))) { await BuildTreeAsync(tree, builder); } diff --git a/src/OrchardCore.Modules/OrchardCore.AdminMenu/Services/AdminMenuPermissionService.cs b/src/OrchardCore.Modules/OrchardCore.AdminMenu/Services/AdminMenuPermissionService.cs index ada48b1c910..daada1fb372 100644 --- a/src/OrchardCore.Modules/OrchardCore.AdminMenu/Services/AdminMenuPermissionService.cs +++ b/src/OrchardCore.Modules/OrchardCore.AdminMenu/Services/AdminMenuPermissionService.cs @@ -35,4 +35,3 @@ public async Task> GetPermissionsAsync() return _permissions; } } - diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Drivers/AliasPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Drivers/AliasPartDisplayDriver.cs index 9cbcac7a0d0..2affde51051 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Drivers/AliasPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Drivers/AliasPartDisplayDriver.cs @@ -14,14 +14,10 @@ namespace OrchardCore.Alias.Drivers { public class AliasPartDisplayDriver : ContentPartDisplayDriver { - private readonly ISession _session; protected readonly IStringLocalizer S; - public AliasPartDisplayDriver( - ISession session, - IStringLocalizer localizer - ) + public AliasPartDisplayDriver(ISession session, IStringLocalizer localizer) { _session = session; S = localizer; @@ -51,6 +47,5 @@ private static void BuildViewModel(AliasPartViewModel model, AliasPart part, Ali model.ContentItem = part.ContentItem; model.Settings = settings; } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Handlers/AliasPartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Handlers/AliasPartHandler.cs index 49fa883d1ff..916a1e329c0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Handlers/AliasPartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Handlers/AliasPartHandler.cs @@ -29,7 +29,8 @@ public AliasPartHandler( ITagCache tagCache, ILiquidTemplateManager liquidTemplateManager, ISession session, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _contentDefinitionManager = contentDefinitionManager; _tagCache = tagCache; @@ -52,7 +53,7 @@ public override async Task ValidatingAsync(ValidateContentContext context, Alias } } - public async override Task UpdatedAsync(UpdateContentContext context, AliasPart part) + public override async Task UpdatedAsync(UpdateContentContext context, AliasPart part) { // Compute the Alias only if it's empty. if (!string.IsNullOrEmpty(part.Alias)) @@ -71,8 +72,12 @@ public async override Task UpdatedAsync(UpdateContentContext context, AliasPart ContentItem = part.ContentItem }; - part.Alias = await _liquidTemplateManager.RenderStringAsync(pattern, NullEncoder.Default, model, - new Dictionary() { [nameof(ContentItem)] = new ObjectValue(model.ContentItem) }); + part.Alias = await _liquidTemplateManager.RenderStringAsync( + pattern, + NullEncoder.Default, + model, + new Dictionary() { [nameof(ContentItem)] = new ObjectValue(model.ContentItem) } + ); part.Alias = part.Alias.Replace("\r", string.Empty).Replace("\n", string.Empty); diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Indexes/AliasPartIndex.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Indexes/AliasPartIndex.cs index d93a5d1553c..07f98accb80 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Indexes/AliasPartIndex.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Indexes/AliasPartIndex.cs @@ -36,7 +36,7 @@ public override async Task UpdatedAsync(UpdateContentContext context) var part = context.ContentItem.As(); // Validate that the content definition contains this part, this prevents indexing parts - // that have been removed from the type definition, but are still present in the elements. + // that have been removed from the type definition, but are still present in the elements. if (part != null) { // Lazy initialization because of ISession cyclic dependency. @@ -60,7 +60,8 @@ public override async Task UpdatedAsync(UpdateContentContext context) public void Describe(DescribeContext context) { - context.For() + context + .For() .When(contentItem => contentItem.Has() || _partRemoved.Contains(contentItem.ContentItemId)) .Map(contentItem => { diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Migrations.cs index c6848fbacce..d63641996d8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Migrations.cs @@ -19,24 +19,21 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync(nameof(AliasPart), builder => builder - .Attachable() - .WithDescription("Provides a way to define custom aliases for content items.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + nameof(AliasPart), + builder => builder.Attachable().WithDescription("Provides a way to define custom aliases for content items.") + ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("Alias", col => col.WithLength(AliasPart.MaxAliasLength)) - .Column("ContentItemId", c => c.WithLength(26)) - .Column("Latest", c => c.WithDefault(false)) - .Column("Published", c => c.WithDefault(true)) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("Alias", col => col.WithLength(AliasPart.MaxAliasLength)) + .Column("ContentItemId", c => c.WithLength(26)) + .Column("Latest", c => c.WithDefault(false)) + .Column("Published", c => c.WithDefault(true)) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_AliasPartIndex_DocumentId", - "DocumentId", - "Alias", - "ContentItemId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_AliasPartIndex_DocumentId", "DocumentId", "Alias", "ContentItemId", "Published", "Latest") ); // Shortcut other migration steps on new content definition schemas. @@ -46,13 +43,9 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version as Latest and Published are alterations. public async Task UpdateFrom1Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Latest", c => c.WithDefault(false)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Latest", c => c.WithDefault(false))); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Published", c => c.WithDefault(true)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Published", c => c.WithDefault(true))); return 2; } @@ -61,7 +54,8 @@ await SchemaBuilder.AlterIndexTableAsync(table => table public async Task UpdateFrom2Async() { // Can't be fully created on existing databases where the 'Alias' may be of 767 chars. - await SchemaBuilder.AlterIndexTableAsync(table => table + await SchemaBuilder.AlterIndexTableAsync(table => + table // .CreateIndex("IDX_AliasPartIndex_DocumentId", // "DocumentId", // "Alias", @@ -69,9 +63,7 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // "Latest", // "Published") - .CreateIndex("IDX_AliasPartIndex_DocumentId", - "DocumentId", - "Alias") + .CreateIndex("IDX_AliasPartIndex_DocumentId", "DocumentId", "Alias") ); return 3; @@ -82,12 +74,8 @@ public async Task UpdateFrom3Async() { // In the previous migration step, an index was not fully created, // but here, we can create a separate one for the missing columns. - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_AliasPartIndex_DocumentId_ContentItemId", - "DocumentId", - "ContentItemId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_AliasPartIndex_DocumentId_ContentItemId", "DocumentId", "ContentItemId", "Published", "Latest") ); return 4; diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Models/AliasPartExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Models/AliasPartExtensions.cs index 2d780605935..d387ef6b9cf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Models/AliasPartExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Models/AliasPartExtensions.cs @@ -15,7 +15,10 @@ public static async IAsyncEnumerable ValidateAsync(this AliasP { if (part.Alias.Length > AliasPart.MaxAliasLength) { - yield return new ValidationResult(S["Your alias is too long. The alias can only be up to {0} characters. \"{1}\"", AliasPart.MaxAliasLength, part.Alias], new string[] { nameof(part.Alias) }); + yield return new ValidationResult( + S["Your alias is too long. The alias can only be up to {0} characters. \"{1}\"", AliasPart.MaxAliasLength, part.Alias], + new string[] { nameof(part.Alias) } + ); } if (!await IsAliasUniqueAsync(part, session, part.Alias)) @@ -29,6 +32,5 @@ public static async Task IsAliasUniqueAsync(this AliasPart context, ISessi { return (await session.QueryIndex(o => o.Alias == alias && o.ContentItemId != context.ContentItem.ContentItemId).CountAsync()) == 0; } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Settings/AliasPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Settings/AliasPartSettingsDisplayDriver.cs index 1215a4b31c9..75d8422bd4d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Settings/AliasPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Settings/AliasPartSettingsDisplayDriver.cs @@ -22,14 +22,18 @@ public AliasPartSettingsDisplayDriver(ILiquidTemplateManager templateManager, IS public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("AliasPartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + "AliasPartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); - model.Pattern = settings.Pattern; - model.Options = settings.Options; - model.AliasPartSettings = settings; - }).Location("Content"); + model.Pattern = settings.Pattern; + model.Options = settings.Options; + model.AliasPartSettings = settings; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Settings/AliasPartSettingsViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Settings/AliasPartSettingsViewModel.cs index 55e8dfb5868..2adba18501c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Settings/AliasPartSettingsViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Settings/AliasPartSettingsViewModel.cs @@ -6,6 +6,7 @@ public class AliasPartSettingsViewModel { public string Pattern { get; set; } public AliasPartOptions Options { get; set; } + [BindNever] public AliasPartSettings AliasPartSettings { get; set; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Startup.cs index 0768f063ed0..797a91aa6de 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Startup.cs @@ -30,30 +30,35 @@ public override void ConfigureServices(IServiceCollection services) { o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register("Alias", (obj, context) => - { - var liquidTemplateContext = (LiquidTemplateContext)context; - - return new LiquidPropertyAccessor(liquidTemplateContext, async (alias, context) => + o.MemberAccessStrategy.Register( + "Alias", + (obj, context) => { - var session = context.Services.GetRequiredService(); + var liquidTemplateContext = (LiquidTemplateContext)context; + + return new LiquidPropertyAccessor( + liquidTemplateContext, + async (alias, context) => + { + var session = context.Services.GetRequiredService(); #pragma warning disable CA1862 // Use the 'StringComparison' method overloads to perform case-insensitive string comparisons - var contentItem = await session.Query(x => - x.Published && x.Alias == alias.ToLowerInvariant()).FirstOrDefaultAsync(); + var contentItem = await session.Query(x => x.Published && x.Alias == alias.ToLowerInvariant()).FirstOrDefaultAsync(); #pragma warning restore CA1862 // Use the 'StringComparison' method overloads to perform case-insensitive string comparisons - if (contentItem == null) - { - return NilValue.Instance; - } + if (contentItem == null) + { + return NilValue.Instance; + } - var contentManager = context.Services.GetRequiredService(); - contentItem = await contentManager.LoadAsync(contentItem); + var contentManager = context.Services.GetRequiredService(); + contentItem = await contentManager.LoadAsync(contentItem); - return new ObjectValue(contentItem); - }); - }); + return new ObjectValue(contentItem); + } + ); + } + ); }); services.AddScoped(); @@ -64,9 +69,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); // Identity Part - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/AdminMenu.cs index bb84d4f87e4..b3561b55899 100644 --- a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/AdminMenu.cs @@ -20,14 +20,15 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["GraphiQL"], S["GraphiQL"].PrefixPosition(), graphiQL => graphiQL - .Action("Index", "Admin", "OrchardCore.Apis.GraphQL") - .Permission(Permissions.ExecuteGraphQL) - .LocalNav() + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["GraphiQL"], + S["GraphiQL"].PrefixPosition(), + graphiQL => graphiQL.Action("Index", "Admin", "OrchardCore.Apis.GraphQL").Permission(Permissions.ExecuteGraphQL).LocalNav() ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Extensions/DocumentWriterExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Extensions/DocumentWriterExtensions.cs index 1163977934a..f2d23cf7e27 100644 --- a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Extensions/DocumentWriterExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Extensions/DocumentWriterExtensions.cs @@ -13,10 +13,7 @@ public static async Task WriteErrorAsync(this IGraphQLSerializer graphQLSerializ { ArgumentNullException.ThrowIfNull(message); - var errorResult = new ExecutionResult - { - Errors = [] - }; + var errorResult = new ExecutionResult { Errors = [] }; if (e == null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/GraphQLMiddleware.cs b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/GraphQLMiddleware.cs index 44281d94b6d..962f1eaa60d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/GraphQLMiddleware.cs +++ b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/GraphQLMiddleware.cs @@ -34,15 +34,13 @@ public class GraphQLMiddleware : IMiddleware private static readonly MediaType _jsonMediaType = new("application/json"); private static readonly MediaType _graphQlMediaType = new("application/graphql"); - public GraphQLMiddleware( - IOptions settingsOption, - IDocumentExecuter executer, - IGraphQLSerializer serializer) + public GraphQLMiddleware(IOptions settingsOption, IDocumentExecuter executer, IGraphQLSerializer serializer) { _settings = settingsOption.Value; _executer = executer; _serializer = serializer; } + public async Task InvokeAsync(HttpContext context, RequestDelegate next) { if (!IsGraphQLRequest(context)) @@ -70,6 +68,7 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next) } } } + private bool IsGraphQLRequest(HttpContext context) { return context.Request.Path.StartsWithNormalizedSegments(_settings.Path, StringComparison.OrdinalIgnoreCase); @@ -89,15 +88,11 @@ private async Task ExecuteAsync(HttpContext context) if (mediaType.IsSubsetOf(_jsonMediaType) || mediaType.IsSubsetOf(_graphQlMediaType)) { - if (mediaType.IsSubsetOf(_graphQlMediaType)) { using var sr = new StreamReader(context.Request.Body); - request = new GraphQLNamedQueryRequest - { - Query = await sr.ReadToEndAsync() - }; + request = new GraphQLNamedQueryRequest { Query = await sr.ReadToEndAsync() }; } else { @@ -131,9 +126,7 @@ private async Task ExecuteAsync(HttpContext context) { var namedQueries = context.RequestServices.GetServices(); - var queries = namedQueries - .SelectMany(dict => dict.Resolve()) - .ToDictionary(pair => pair.Key, pair => pair.Value); + var queries = namedQueries.SelectMany(dict => dict.Resolve()).ToDictionary(pair => pair.Key, pair => pair.Value); queryToExecute = queries[request.NamedQuery]; } @@ -148,23 +141,29 @@ private async Task ExecuteAsync(HttpContext context) options.OperationName = request.OperationName; options.Variables = request.Variables; options.UserContext = _settings.BuildUserContext?.Invoke(context); - options.ValidationRules = DocumentValidator.CoreRules - .Concat(context.RequestServices.GetServices()) - .Append(new ComplexityValidationRule(new ComplexityConfiguration - { - MaxDepth = _settings.MaxDepth, - MaxComplexity = _settings.MaxComplexity, - FieldImpact = _settings.FieldImpact - })); + options.ValidationRules = DocumentValidator + .CoreRules.Concat(context.RequestServices.GetServices()) + .Append( + new ComplexityValidationRule( + new ComplexityConfiguration + { + MaxDepth = _settings.MaxDepth, + MaxComplexity = _settings.MaxComplexity, + FieldImpact = _settings.FieldImpact + } + ) + ); options.Listeners.Add(dataLoaderDocumentListener); options.RequestServices = context.RequestServices; }); - context.Response.StatusCode = (int)(result.Errors == null || result.Errors.Count == 0 - ? HttpStatusCode.OK - : result.Errors.Any(x => x is ValidationError ve && ve.Number == RequiresPermissionValidationRule.ErrorCode) - ? HttpStatusCode.Unauthorized - : HttpStatusCode.BadRequest); + context.Response.StatusCode = (int)( + result.Errors == null || result.Errors.Count == 0 + ? HttpStatusCode.OK + : result.Errors.Any(x => x is ValidationError ve && ve.Number == RequiresPermissionValidationRule.ErrorCode) + ? HttpStatusCode.Unauthorized + : HttpStatusCode.BadRequest + ); context.Response.ContentType = MediaTypeNames.Application.Json; @@ -183,10 +182,7 @@ private static GraphQLNamedQueryRequest CreateRequestFromQueryString(HttpContext return null; } - var request = new GraphQLNamedQueryRequest - { - Query = context.Request.Query["query"] - }; + var request = new GraphQLNamedQueryRequest { Query = context.Request.Query["query"] }; if (context.Request.Query.ContainsKey("variables")) { diff --git a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/GraphQLNamedQueryRequest.cs b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/GraphQLNamedQueryRequest.cs index d27e7564088..ede4034aecd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/GraphQLNamedQueryRequest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/GraphQLNamedQueryRequest.cs @@ -1,4 +1,3 @@ - using GraphQL.Transport; namespace OrchardCore.Apis.GraphQL diff --git a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Permissions.cs index d890058f209..db0c72f204c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Permissions.cs @@ -9,24 +9,9 @@ public class Permissions : IPermissionProvider public static readonly Permission ExecuteGraphQLMutations = CommonPermissions.ExecuteGraphQLMutations; public static readonly Permission ExecuteGraphQL = CommonPermissions.ExecuteGraphQL; - private readonly IEnumerable _allPermissions = - [ - ExecuteGraphQL, - ExecuteGraphQLMutations, - ]; + private readonly IEnumerable _allPermissions = [ExecuteGraphQL, ExecuteGraphQLMutations,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = - [ - ExecuteGraphQLMutations, - ], - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = [ExecuteGraphQLMutations,], },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Services/SchemaService.cs b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Services/SchemaService.cs index b0be8eb9661..546cd2898de 100644 --- a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Services/SchemaService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Services/SchemaService.cs @@ -94,7 +94,6 @@ public async Task GetSchemaAsync() await builder.BuildAsync(schema); } - // Clean Query, Mutation and Subscription if they have no fields // to prevent GraphQL configuration errors. diff --git a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Startup.cs index 963237964a4..20af62605f4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/Startup.cs @@ -1,3 +1,4 @@ +using System; using GraphQL; using GraphQL.DataLoader; using GraphQL.Execution; @@ -14,7 +15,6 @@ using OrchardCore.Modules; using OrchardCore.Navigation; using OrchardCore.Security.Permissions; -using System; namespace OrchardCore.Apis.GraphQL { @@ -48,32 +48,34 @@ public override void ConfigureServices(IServiceCollection services) services.AddSingleton(); services.AddGraphQL(builder => builder.AddSystemTextJson()); - services.AddOptions().Configure((c, configuration) => - { - var exposeExceptions = configuration.GetValue( - $"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.ExposeExceptions)}", - _hostingEnvironment.IsDevelopment()); + services + .AddOptions() + .Configure( + (c, configuration) => + { + var exposeExceptions = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.ExposeExceptions)}", _hostingEnvironment.IsDevelopment()); - var maxNumberOfResultsValidationMode = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.MaxNumberOfResultsValidationMode)}") - ?? MaxNumberOfResultsValidationMode.Default; + var maxNumberOfResultsValidationMode = + configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.MaxNumberOfResultsValidationMode)}") + ?? MaxNumberOfResultsValidationMode.Default; - if (maxNumberOfResultsValidationMode == MaxNumberOfResultsValidationMode.Default) - { - maxNumberOfResultsValidationMode = _hostingEnvironment.IsDevelopment() ? MaxNumberOfResultsValidationMode.Enabled : MaxNumberOfResultsValidationMode.Disabled; - } + if (maxNumberOfResultsValidationMode == MaxNumberOfResultsValidationMode.Default) + { + maxNumberOfResultsValidationMode = _hostingEnvironment.IsDevelopment() + ? MaxNumberOfResultsValidationMode.Enabled + : MaxNumberOfResultsValidationMode.Disabled; + } - c.BuildUserContext = ctx => new GraphQLUserContext - { - User = ctx.User, - }; - c.ExposeExceptions = exposeExceptions; - c.MaxDepth = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.MaxDepth)}") ?? 100; - c.MaxComplexity = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.MaxComplexity)}"); - c.FieldImpact = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.FieldImpact)}"); - c.MaxNumberOfResults = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.MaxNumberOfResults)}") ?? 1000; - c.MaxNumberOfResultsValidationMode = maxNumberOfResultsValidationMode; - c.DefaultNumberOfResults = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.DefaultNumberOfResults)}") ?? 100; - }); + c.BuildUserContext = ctx => new GraphQLUserContext { User = ctx.User, }; + c.ExposeExceptions = exposeExceptions; + c.MaxDepth = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.MaxDepth)}") ?? 100; + c.MaxComplexity = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.MaxComplexity)}"); + c.FieldImpact = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.FieldImpact)}"); + c.MaxNumberOfResults = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.MaxNumberOfResults)}") ?? 1000; + c.MaxNumberOfResultsValidationMode = maxNumberOfResultsValidationMode; + c.DefaultNumberOfResults = configuration.GetValue($"OrchardCore_Apis_GraphQL:{nameof(GraphQLSettings.DefaultNumberOfResults)}") ?? 100; + } + ); } public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) diff --git a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/ValidationRules/MaxNumberOfResultsValidationRule.cs b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/ValidationRules/MaxNumberOfResultsValidationRule.cs index 8f3ce387f3d..5775bddbafb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/ValidationRules/MaxNumberOfResultsValidationRule.cs +++ b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/ValidationRules/MaxNumberOfResultsValidationRule.cs @@ -17,7 +17,8 @@ public class MaxNumberOfResultsValidationRule : IValidationRule public MaxNumberOfResultsValidationRule( IOptions options, IStringLocalizer localizer, - ILogger logger) + ILogger logger + ) { var settings = options.Value; _maxNumberOfResults = settings.MaxNumberOfResults; @@ -28,46 +29,60 @@ public MaxNumberOfResultsValidationRule( public ValueTask ValidateAsync(ValidationContext validationContext) { - return ValueTask.FromResult((INodeVisitor)new NodeVisitors( - new MatchingNodeVisitor((arg, visitorContext) => - { - if ((arg.Name == "first" || arg.Name == "last") && arg.Value != null) - { - var context = (GraphQLUserContext)validationContext.UserContext; + return ValueTask.FromResult( + (INodeVisitor) + new NodeVisitors( + new MatchingNodeVisitor( + (arg, visitorContext) => + { + if ((arg.Name == "first" || arg.Name == "last") && arg.Value != null) + { + var context = (GraphQLUserContext)validationContext.UserContext; - int? value = null; + int? value = null; - if (arg.Value is GraphQLIntValue) - { - value = int.Parse((arg.Value as GraphQLIntValue).Value); - } - else - { - if (validationContext.Variables.TryGetValue(arg.Value.ToString(), out var input)) - { - value = (int?)input; - } - } + if (arg.Value is GraphQLIntValue) + { + value = int.Parse((arg.Value as GraphQLIntValue).Value); + } + else + { + if (validationContext.Variables.TryGetValue(arg.Value.ToString(), out var input)) + { + value = (int?)input; + } + } - if (value.HasValue && value > _maxNumberOfResults) - { - if (_maxNumberOfResultsValidationMode == MaxNumberOfResultsValidationMode.Enabled) - { - validationContext.ReportError(new ValidationError( - validationContext.Document.Source, - "ArgumentInputError", - S["'{0}' exceeds the maximum number of results for '{1}' ({2})", value.Value, arg.Name, _maxNumberOfResults], - arg)); - } - else - { - _logger.LogInformation("'{value}' exceeds the maximum number of results for '{name}' ({total})", value.Value, arg.Name, _maxNumberOfResults); + if (value.HasValue && value > _maxNumberOfResults) + { + if (_maxNumberOfResultsValidationMode == MaxNumberOfResultsValidationMode.Enabled) + { + validationContext.ReportError( + new ValidationError( + validationContext.Document.Source, + "ArgumentInputError", + S["'{0}' exceeds the maximum number of results for '{1}' ({2})", value.Value, arg.Name, _maxNumberOfResults], + arg + ) + ); + } + else + { + _logger.LogInformation( + "'{value}' exceeds the maximum number of results for '{name}' ({total})", + value.Value, + arg.Name, + _maxNumberOfResults + ); - arg = new GraphQLArgument(arg.Name, new GraphQLIntValue(_maxNumberOfResults)); // if disabled mode we just log info and override the arg to be maxvalue - } - } - } - }))); + arg = new GraphQLArgument(arg.Name, new GraphQLIntValue(_maxNumberOfResults)); // if disabled mode we just log info and override the arg to be maxvalue + } + } + } + } + ) + ) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/ValidationRules/RequiresPermissionValidationRule.cs b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/ValidationRules/RequiresPermissionValidationRule.cs index a0aae7945d8..3c82a931d5a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/ValidationRules/RequiresPermissionValidationRule.cs +++ b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/ValidationRules/RequiresPermissionValidationRule.cs @@ -16,9 +16,7 @@ public class RequiresPermissionValidationRule : IValidationRule private readonly IAuthorizationService _authorizationService; protected readonly IStringLocalizer S; - public RequiresPermissionValidationRule( - IAuthorizationService authorizationService, - IStringLocalizer localizer) + public RequiresPermissionValidationRule(IAuthorizationService authorizationService, IStringLocalizer localizer) { _authorizationService = authorizationService; S = localizer; @@ -29,43 +27,61 @@ public async ValueTask ValidateAsync(ValidationContext validationC // shouldn't we access UserContext from validationcontext inside MatchingNodeVisitor actions? var userContext = (GraphQLUserContext)validationContext.UserContext; - return await Task.FromResult(new NodeVisitors( - new MatchingNodeVisitor(async (operationDefinition, validationContext) => - { - await AuthorizeOperationAsync(operationDefinition, validationContext, userContext, operationDefinition.Operation, operationDefinition?.Name?.StringValue); - }), - new MatchingNodeVisitor(async (objectFieldAst, validationContext) => - { - if (validationContext.TypeInfo.GetArgument()?.ResolvedType.GetNamedType() is IComplexGraphType argumentType) - { - var fieldType = argumentType.GetField(objectFieldAst.Name); - await AuthorizeNodePermissionAsync(objectFieldAst, fieldType, validationContext, userContext); - } - }), - new MatchingNodeVisitor(async (fieldAst, validationContext) => - { - var fieldDef = validationContext.TypeInfo.GetFieldDef(); - - if (fieldDef == null) - return; - - // check target field - await AuthorizeNodePermissionAsync(fieldAst, fieldDef, validationContext, userContext); - // check returned graph type - // AuthorizeNodePermissionAsync(fieldAst, fieldDef.ResolvedType.GetNamedType(), validationContext, userContext).GetAwaiter().GetResult(); // TODO: need to think of something to avoid this - }) - )); + return await Task.FromResult( + new NodeVisitors( + new MatchingNodeVisitor( + async (operationDefinition, validationContext) => + { + await AuthorizeOperationAsync( + operationDefinition, + validationContext, + userContext, + operationDefinition.Operation, + operationDefinition?.Name?.StringValue + ); + } + ), + new MatchingNodeVisitor( + async (objectFieldAst, validationContext) => + { + if (validationContext.TypeInfo.GetArgument()?.ResolvedType.GetNamedType() is IComplexGraphType argumentType) + { + var fieldType = argumentType.GetField(objectFieldAst.Name); + await AuthorizeNodePermissionAsync(objectFieldAst, fieldType, validationContext, userContext); + } + } + ), + new MatchingNodeVisitor( + async (fieldAst, validationContext) => + { + var fieldDef = validationContext.TypeInfo.GetFieldDef(); + + if (fieldDef == null) + return; + + // check target field + await AuthorizeNodePermissionAsync(fieldAst, fieldDef, validationContext, userContext); + // check returned graph type + // AuthorizeNodePermissionAsync(fieldAst, fieldDef.ResolvedType.GetNamedType(), validationContext, userContext).GetAwaiter().GetResult(); // TODO: need to think of something to avoid this + } + ) + ) + ); } - private async Task AuthorizeOperationAsync(ASTNode node, ValidationContext validationContext, GraphQLUserContext userContext, OperationType? operationType, string operationName) + private async Task AuthorizeOperationAsync( + ASTNode node, + ValidationContext validationContext, + GraphQLUserContext userContext, + OperationType? operationType, + string operationName + ) { if (operationType == OperationType.Mutation && !(await _authorizationService.AuthorizeAsync(userContext.User, Permissions.ExecuteGraphQLMutations))) { - validationContext.ReportError(new ValidationError( - validationContext.Document.Source, - ErrorCode, - S["Authorization is required to access {0}.", operationName], - node)); + validationContext.ReportError( + new ValidationError(validationContext.Document.Source, ErrorCode, S["Authorization is required to access {0}.", operationName], node) + ); } } @@ -114,11 +130,9 @@ private async Task AuthorizeNodePermissionAsync(ASTNode node, IFieldType fieldTy private void AddPermissionValidationError(ValidationContext validationContext, ASTNode node, string nodeName) { - validationContext.ReportError(new ValidationError( - validationContext.Document.Source, - ErrorCode, - S["Authorization is required to access the node. {0}", nodeName], - node)); + validationContext.ReportError( + new ValidationError(validationContext.Document.Source, ErrorCode, S["Authorization is required to access the node. {0}", nodeName], node) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Drivers/ArchiveLaterPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Drivers/ArchiveLaterPartDisplayDriver.cs index e80b571142a..0f1fcf35502 100644 --- a/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Drivers/ArchiveLaterPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Drivers/ArchiveLaterPartDisplayDriver.cs @@ -18,25 +18,18 @@ public class ArchiveLaterPartDisplayDriver : ContentPartDisplayDriver Initialize( - $"{nameof(ArchiveLaterPart)}_SummaryAdmin", - model => PopulateViewModel(part, model)).Location("SummaryAdmin", "Meta:25"); + public override IDisplayResult Display(ArchiveLaterPart part, BuildPartDisplayContext context) => + Initialize($"{nameof(ArchiveLaterPart)}_SummaryAdmin", model => PopulateViewModel(part, model)).Location("SummaryAdmin", "Meta:25"); - public override IDisplayResult Edit(ArchiveLaterPart part, BuildPartEditorContext context) - => Initialize( - GetEditorShapeType(context), - model => PopulateViewModel(part, model)).Location("Actions:10.5"); + public override IDisplayResult Edit(ArchiveLaterPart part, BuildPartEditorContext context) => + Initialize(GetEditorShapeType(context), model => PopulateViewModel(part, model)).Location("Actions:10.5"); public override async Task UpdateAsync(ArchiveLaterPart part, IUpdateModel updater, UpdatePartEditorContext context) { @@ -65,8 +58,6 @@ private async ValueTask PopulateViewModel(ArchiveLaterPart part, ArchiveLaterPar { viewModel.ContentItem = part.ContentItem; viewModel.ScheduledArchiveUtc = part.ScheduledArchiveUtc; - viewModel.ScheduledArchiveLocalDateTime = part.ScheduledArchiveUtc.HasValue - ? (await _localClock.ConvertToLocalAsync(part.ScheduledArchiveUtc.Value)).DateTime - : null; + viewModel.ScheduledArchiveLocalDateTime = part.ScheduledArchiveUtc.HasValue ? (await _localClock.ConvertToLocalAsync(part.ScheduledArchiveUtc.Value)).DateTime : null; } } diff --git a/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Migrations.cs index f62335d3a4c..bacb72166ca 100644 --- a/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Migrations.cs @@ -20,25 +20,17 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync(nameof(ArchiveLaterPart), builder => builder - .Attachable() - .WithDescription("Adds the ability to schedule content items to be archived at a given future date and time.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + nameof(ArchiveLaterPart), + builder => builder.Attachable().WithDescription("Adds the ability to schedule content items to be archived at a given future date and time.") + ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId") - .Column("ScheduledArchiveDateTimeUtc") - .Column("Published") - .Column("Latest") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table.Column("ContentItemId").Column("ScheduledArchiveDateTimeUtc").Column("Published").Column("Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ArchiveLaterPartIndex_DocumentId", - "Id", - "DocumentId", - "ContentItemId", - "ScheduledArchiveDateTimeUtc", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ArchiveLaterPartIndex_DocumentId", "Id", "DocumentId", "ContentItemId", "ScheduledArchiveDateTimeUtc", "Published", "Latest") ); return 1; diff --git a/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Services/ScheduledArchivingBackgroundTask.cs b/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Services/ScheduledArchivingBackgroundTask.cs index b645d7cdac9..99acf8448d2 100644 --- a/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Services/ScheduledArchivingBackgroundTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Services/ScheduledArchivingBackgroundTask.cs @@ -14,10 +14,7 @@ namespace OrchardCore.ArchiveLater.Services; -[BackgroundTask( - Title = "Content Items Archiver", - Schedule = "* * * * *", - Description = "Archives content items when their scheduled archive date time arrives.")] +[BackgroundTask(Title = "Content Items Archiver", Schedule = "* * * * *", Description = "Archives content items when their scheduled archive date time arrives.")] public class ScheduledArchivingBackgroundTask : IBackgroundTask { private readonly ILogger _logger; diff --git a/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Startup.cs b/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Startup.cs index dd1999e5366..95d52bffae9 100644 --- a/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.ArchiveLater/Startup.cs @@ -17,7 +17,6 @@ namespace OrchardCore.ArchiveLater; public class Startup : StartupBase { - public override void ConfigureServices(IServiceCollection services) { services.Configure(o => @@ -25,9 +24,7 @@ public override void ConfigureServices(IServiceCollection services) o.MemberAccessStrategy.Register(); }); - services - .AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddDataMigration(); diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Controllers/AdminController.cs index 257ea9ed920..6134e954a7b 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Controllers/AdminController.cs @@ -39,7 +39,8 @@ public AdminController( IAuditTrailAdminListQueryService auditTrailAdminListQueryService, IDisplayManager displayManager, IDisplayManager auditTrailOptionsDisplayManager, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _pagerOptions = pagerOptions.Value; _shapeFactory = shapeFactory; @@ -53,17 +54,18 @@ public AdminController( } [Admin("AuditTrail/{correlationId?}", "AuditTrailIndex")] - public async Task Index([ModelBinder(BinderType = typeof(AuditTrailFilterEngineModelBinder), Name = "q")] QueryFilterResult queryFilterResult, PagerParameters pagerParameters, string correlationId = "") + public async Task Index( + [ModelBinder(BinderType = typeof(AuditTrailFilterEngineModelBinder), Name = "q")] QueryFilterResult queryFilterResult, + PagerParameters pagerParameters, + string correlationId = "" + ) { if (!await _authorizationService.AuthorizeAsync(User, AuditTrailPermissions.ViewAuditTrail)) { return Forbid(); } - var options = new AuditTrailIndexOptions - { - FilterResult = queryFilterResult - }; + var options = new AuditTrailIndexOptions { FilterResult = queryFilterResult }; // This is used by Contents feature for routing so needs to be passed into the options. if (!string.IsNullOrEmpty(correlationId)) @@ -95,9 +97,7 @@ public async Task Index([ModelBinder(BinderType = typeof(AuditTrai foreach (var auditTrailEvent in result.Events) { - items.Add( - await _displayManager.BuildDisplayAsync(auditTrailEvent, updater: _updateModelAccessor.ModelUpdater, displayType: "SummaryAdmin") - ); + items.Add(await _displayManager.BuildDisplayAsync(auditTrailEvent, updater: _updateModelAccessor.ModelUpdater, displayType: "SummaryAdmin")); } var startIndex = (pager.Page - 1) * pager.PageSize + 1; @@ -108,13 +108,16 @@ await _displayManager.BuildDisplayAsync(auditTrailEvent, updater: _updateModelAc var header = await _auditTrailOptionsDisplayManager.BuildEditorAsync(options, _updateModelAccessor.ModelUpdater, false, string.Empty, string.Empty); - var shapeViewModel = await _shapeFactory.CreateAsync("AuditTrailAdminList", viewModel => - { - viewModel.Events = items; - viewModel.Pager = pagerShape; - viewModel.Options = options; - viewModel.Header = header; - }); + var shapeViewModel = await _shapeFactory.CreateAsync( + "AuditTrailAdminList", + viewModel => + { + viewModel.Events = items; + viewModel.Pager = pagerShape; + viewModel.Options = options; + viewModel.Header = header; + } + ); return View(shapeViewModel); } @@ -153,7 +156,6 @@ public async Task Display(string auditTrailEventId) return NotFound(); } - var shape = await _displayManager.BuildDisplayAsync(auditTrailEvent, updater: _updateModelAccessor.ModelUpdater, displayType: "DetailAdmin"); return View(new AuditTrailItemViewModel { Shape = shape }); diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Drivers/AuditTrailSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Drivers/AuditTrailSettingsDisplayDriver.cs index b419eaf2be3..05ee17be77d 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Drivers/AuditTrailSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Drivers/AuditTrailSettingsDisplayDriver.cs @@ -24,7 +24,8 @@ public AuditTrailSettingsDisplayDriver( IAuditTrailManager auditTrailManager, IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService, - IServiceProvider serviceProvider) + IServiceProvider serviceProvider + ) { _auditTrailManager = auditTrailManager; _httpContextAccessor = httpContextAccessor; @@ -39,43 +40,46 @@ public override async Task EditAsync(AuditTrailSettings settings return null; } - return Initialize("AuditTrailSettings_Edit", model => - { - var categories = _auditTrailManager.DescribeCategories(); + return Initialize( + "AuditTrailSettings_Edit", + model => + { + var categories = _auditTrailManager.DescribeCategories(); - var settingsGroups = settings.Categories - .ToLookup(category => category.Events - .FirstOrDefault()?.Category ?? ""); + var settingsGroups = settings.Categories.ToLookup(category => category.Events.FirstOrDefault()?.Category ?? ""); - var categoriesViewModel = categories - .Select(category => new AuditTrailCategorySettingsViewModel() - { - Name = category.Name, - LocalizedName = category.LocalizedName(_serviceProvider), - Events = category.Events.Values - .Select(auditTrailEvent => + var categoriesViewModel = categories + .Select(category => new AuditTrailCategorySettingsViewModel() { - var settings = settingsGroups[auditTrailEvent.Category] - .FirstOrDefault()?.Events - .FirstOrDefault(settings => settings.Name == auditTrailEvent.Name); + Name = category.Name, + LocalizedName = category.LocalizedName(_serviceProvider), + Events = category + .Events.Values.Select(auditTrailEvent => + { + var settings = settingsGroups[auditTrailEvent.Category] + .FirstOrDefault() + ?.Events.FirstOrDefault(settings => settings.Name == auditTrailEvent.Name); - return new AuditTrailEventSettingsViewModel() - { - Name = auditTrailEvent.Name, - Category = auditTrailEvent.Category, - LocalizedName = auditTrailEvent.LocalizedName(_serviceProvider), - Description = auditTrailEvent.Description(_serviceProvider), - IsEnabled = auditTrailEvent.IsMandatory || (settings?.IsEnabled ?? auditTrailEvent.IsEnabledByDefault), - IsMandatory = auditTrailEvent.IsMandatory - }; + return new AuditTrailEventSettingsViewModel() + { + Name = auditTrailEvent.Name, + Category = auditTrailEvent.Category, + LocalizedName = auditTrailEvent.LocalizedName(_serviceProvider), + Description = auditTrailEvent.Description(_serviceProvider), + IsEnabled = auditTrailEvent.IsMandatory || (settings?.IsEnabled ?? auditTrailEvent.IsEnabledByDefault), + IsMandatory = auditTrailEvent.IsMandatory + }; + }) + .ToArray() }) - .ToArray() - }) - .ToArray(); + .ToArray(); - model.Categories = categoriesViewModel; - model.ClientIpAddressAllowed = settings.ClientIpAddressAllowed; - }).Location("Content:1#Events").OnGroup(AuditTrailSettingsGroup.Id); + model.Categories = categoriesViewModel; + model.ClientIpAddressAllowed = settings.ClientIpAddressAllowed; + } + ) + .Location("Content:1#Events") + .OnGroup(AuditTrailSettingsGroup.Id); } public override async Task UpdateAsync(AuditTrailSettings settings, BuildEditorContext context) @@ -90,12 +94,12 @@ public override async Task UpdateAsync(AuditTrailSettings settin var model = new AuditTrailSettingsViewModel(); await context.Updater.TryUpdateModelAsync(model, Prefix); - settings.Categories = model.Categories - .Select(categorySettings => new AuditTrailCategorySettings() + settings.Categories = model + .Categories.Select(categorySettings => new AuditTrailCategorySettings() { Name = categorySettings.Name, - Events = categorySettings.Events - .Select(settings => new AuditTrailEventSettings() + Events = categorySettings + .Events.Select(settings => new AuditTrailEventSettings() { Name = settings.Name, Category = settings.Category, diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Drivers/AuditTrailTrimmingSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Drivers/AuditTrailTrimmingSettingsDisplayDriver.cs index 855814ecc13..c8cd139351d 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Drivers/AuditTrailTrimmingSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Drivers/AuditTrailTrimmingSettingsDisplayDriver.cs @@ -29,12 +29,17 @@ public override async Task EditAsync(AuditTrailTrimmingSettings return null; } - return Initialize("AuditTrailTrimmingSettings_Edit", model => - { - model.RetentionDays = section.RetentionDays; - model.LastRunUtc = section.LastRunUtc; - model.Disabled = section.Disabled; - }).Location("Content:10#Trimming;0").OnGroup(AuditTrailSettingsGroup.Id); + return Initialize( + "AuditTrailTrimmingSettings_Edit", + model => + { + model.RetentionDays = section.RetentionDays; + model.LastRunUtc = section.LastRunUtc; + model.Disabled = section.Disabled; + } + ) + .Location("Content:10#Trimming;0") + .OnGroup(AuditTrailSettingsGroup.Id); } public override async Task UpdateAsync(AuditTrailTrimmingSettings section, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Indexes/AuditTrailEventIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Indexes/AuditTrailEventIndexProvider.cs index 2234cdbfa2f..febcedd7d41 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Indexes/AuditTrailEventIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Indexes/AuditTrailEventIndexProvider.cs @@ -8,7 +8,8 @@ public class AuditTrailEventIndexProvider : IndexProvider public AuditTrailEventIndexProvider() => CollectionName = AuditTrailEvent.Collection; public override void Describe(DescribeContext context) => - context.For() + context + .For() .Map(auditTrailEvent => { return new AuditTrailEventIndex diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Manifest.cs index 45b789b8466..d6afd560314 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Manifest.cs @@ -8,9 +8,4 @@ Category = "Security" )] -[assembly: Feature( - Id = "OrchardCore.AuditTrail", - Name = "Audit Trail", - Description = "Provides a log for recording and viewing back-end changes.", - Category = "Security" -)] +[assembly: Feature(Id = "OrchardCore.AuditTrail", Name = "Audit Trail", Description = "Provides a log for recording and viewing back-end changes.", Category = "Security")] diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Migrations.cs index ab5423ac5fb..f4a84d78ad3 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Migrations.cs @@ -11,26 +11,31 @@ public class Migrations : DataMigration { public async Task CreateAsync() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column(nameof(AuditTrailEventIndex.EventId), column => column.WithLength(26)) - .Column(nameof(AuditTrailEventIndex.Category), column => column.WithLength(64)) - .Column(nameof(AuditTrailEventIndex.Name), column => column.WithLength(64)) - .Column(nameof(AuditTrailEventIndex.CorrelationId), column => column.WithLength(26)) - .Column(nameof(AuditTrailEventIndex.UserId), column => column.WithLength(26)) - .Column(nameof(AuditTrailEventIndex.NormalizedUserName), column => column.Nullable().WithLength(255)) - .Column(nameof(AuditTrailEventIndex.CreatedUtc), column => column.Nullable()), - collection: AuditTrailEvent.Collection); + await SchemaBuilder.CreateMapIndexTableAsync( + table => + table + .Column(nameof(AuditTrailEventIndex.EventId), column => column.WithLength(26)) + .Column(nameof(AuditTrailEventIndex.Category), column => column.WithLength(64)) + .Column(nameof(AuditTrailEventIndex.Name), column => column.WithLength(64)) + .Column(nameof(AuditTrailEventIndex.CorrelationId), column => column.WithLength(26)) + .Column(nameof(AuditTrailEventIndex.UserId), column => column.WithLength(26)) + .Column(nameof(AuditTrailEventIndex.NormalizedUserName), column => column.Nullable().WithLength(255)) + .Column(nameof(AuditTrailEventIndex.CreatedUtc), column => column.Nullable()), + collection: AuditTrailEvent.Collection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_AuditTrailEventIndex_DocumentId", - "DocumentId", - "EventId", - "Category", - "Name", - "CorrelationId", - "UserId", - "NormalizedUserName", - "CreatedUtc" + await SchemaBuilder.AlterIndexTableAsync( + table => + table.CreateIndex( + "IDX_AuditTrailEventIndex_DocumentId", + "DocumentId", + "EventId", + "Category", + "Name", + "CorrelationId", + "UserId", + "NormalizedUserName", + "CreatedUtc" ), collection: AuditTrailEvent.Collection ); diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Navigation/AuditTrailAdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Navigation/AuditTrailAdminMenu.cs index b56cd76f432..5e0e89d24fa 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Navigation/AuditTrailAdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Navigation/AuditTrailAdminMenu.cs @@ -8,11 +8,7 @@ namespace OrchardCore.AuditTrail.Navigation { public class AuditTrailAdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.AuditTrail" }, - { "correlationId", string.Empty }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.AuditTrail" }, { "correlationId", string.Empty }, }; protected readonly IStringLocalizer S; @@ -28,14 +24,17 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Audit Trail"], NavigationConstants.AdminMenuAuditTrailPosition, configuration => configuration - .AddClass("audittrail") - .Id("audittrail") - .Action(nameof(AdminController.Index), "Admin", _routeValues) - .Permission(AuditTrailPermissions.ViewAuditTrail) - .LocalNav() - ); + builder.Add( + S["Audit Trail"], + NavigationConstants.AdminMenuAuditTrailPosition, + configuration => + configuration + .AddClass("audittrail") + .Id("audittrail") + .Action(nameof(AdminController.Index), "Admin", _routeValues) + .Permission(AuditTrailPermissions.ViewAuditTrail) + .LocalNav() + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Navigation/AuditTrailSettingsAdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Navigation/AuditTrailSettingsAdminMenu.cs index 570e337e0f9..73918ecf976 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Navigation/AuditTrailSettingsAdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Navigation/AuditTrailSettingsAdminMenu.cs @@ -8,11 +8,7 @@ namespace OrchardCore.AuditTrail.Navigation { public class AuditTrailSettingsAdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", AuditTrailSettingsGroup.Id }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", AuditTrailSettingsGroup.Id }, }; protected readonly IStringLocalizer S; @@ -28,18 +24,25 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Audit Trail"], S["Audit Trail"].PrefixPosition(), auditTrail => auditTrail - .AddClass("audittrail") - .Id("audittrailSettings") - .Action("Index", "Admin", _routeValues) - .Permission(AuditTrailPermissions.ManageAuditTrailSettings) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Audit Trail"], + S["Audit Trail"].PrefixPosition(), + auditTrail => + auditTrail + .AddClass("audittrail") + .Id("audittrailSettings") + .Action("Index", "Admin", _routeValues) + .Permission(AuditTrailPermissions.ManageAuditTrailSettings) + .LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Permissions.cs index 2a9398f4dc7..fb1beaf0c2c 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Permissions.cs @@ -9,21 +9,9 @@ public class Permissions : IPermissionProvider public static readonly Permission ViewAuditTrail = AuditTrailPermissions.ViewAuditTrail; public static readonly Permission ManageAuditTrailSettings = AuditTrailPermissions.ManageAuditTrailSettings; - private readonly IEnumerable _allPermissions = - [ - ViewAuditTrail, - ManageAuditTrailSettings, - ]; + private readonly IEnumerable _allPermissions = [ViewAuditTrail, ManageAuditTrailSettings,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/AuditTrailBackgroundTask.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/AuditTrailBackgroundTask.cs index f9a40a7bb1b..1406045072c 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/AuditTrailBackgroundTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/AuditTrailBackgroundTask.cs @@ -15,8 +15,9 @@ namespace OrchardCore.AuditTrail.Services Title = "Audit Trail Events Purger", Schedule = "0 0 * * *", Description = "Regularly purges old Audit Trail events.", - LockTimeout = 3_000, LockExpiration = 30_000)] - + LockTimeout = 3_000, + LockExpiration = 30_000 + )] public class AuditTrailBackgroundTask : IBackgroundTask { public async Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken) @@ -43,10 +44,13 @@ public async Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToke settings.LastRunUtc = clock.UtcNow; var container = await siteService.LoadSiteSettingsAsync(); - container.Alter(nameof(AuditTrailTrimmingSettings), settings => - { - settings.LastRunUtc = clock.UtcNow; - }); + container.Alter( + nameof(AuditTrailTrimmingSettings), + settings => + { + settings.LastRunUtc = clock.UtcNow; + } + ); await siteService.UpdateSiteSettingsAsync(container); } diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/AuditTrailManager.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/AuditTrailManager.cs index bc8e8b14369..d992ecb854b 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/AuditTrailManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/AuditTrailManager.cs @@ -45,7 +45,8 @@ public AuditTrailManager( IClientIPAddressAccessor clientIPAddressAccessor, IAuditTrailIdGenerator auditTrailIdGenerator, ShellSettings shellSettings, - ILogger logger) + ILogger logger + ) { _clock = clock; _session = session; @@ -60,7 +61,8 @@ public AuditTrailManager( _logger = logger; } - public async Task RecordEventAsync(AuditTrailContext context) where TEvent : class, new() + public async Task RecordEventAsync(AuditTrailContext context) + where TEvent : class, new() { if (_shellSettings.IsInitializing() && string.IsNullOrEmpty(context.UserName)) { @@ -97,28 +99,31 @@ public AuditTrailManager( UserId = createContext.UserId, UserName = createContext.UserName ?? "", NormalizedUserName = string.IsNullOrEmpty(createContext.UserName) ? "" : _keyNormalizer.NormalizeName(createContext.UserName), - ClientIpAddress = string.IsNullOrEmpty(createContext.ClientIpAddress) - ? await GetClientIpAddressAsync() - : createContext.ClientIpAddress, + ClientIpAddress = string.IsNullOrEmpty(createContext.ClientIpAddress) ? await GetClientIpAddressAsync() : createContext.ClientIpAddress, CreatedUtc = createContext.CreatedUtc ?? _clock.UtcNow }; auditTrailEvent.Put(createContext.AuditTrailEventItem); - await _auditTrailEventHandlers.InvokeAsync((handler, context, auditTrailEvent) => handler.AlterAsync(context, auditTrailEvent), createContext, auditTrailEvent, _logger); + await _auditTrailEventHandlers.InvokeAsync( + (handler, context, auditTrailEvent) => handler.AlterAsync(context, auditTrailEvent), + createContext, + auditTrailEvent, + _logger + ); await _session.SaveAsync(auditTrailEvent, AuditTrailEvent.Collection); } + public Task GetEventAsync(string eventId) => - _session.Query(collection: AuditTrailEvent.Collection) - .Where(index => index.EventId == eventId) - .FirstOrDefaultAsync(); + _session.Query(collection: AuditTrailEvent.Collection).Where(index => index.EventId == eventId).FirstOrDefaultAsync(); public async Task TrimEventsAsync(TimeSpan retentionPeriod) { var dateThreshold = _clock.UtcNow.AddDays(1) - retentionPeriod; - var events = await _session.Query(collection: AuditTrailEvent.Collection) + var events = await _session + .Query(collection: AuditTrailEvent.Collection) .Where(index => index.CreatedUtc <= dateThreshold) .ListAsync(); @@ -133,11 +138,9 @@ public async Task TrimEventsAsync(TimeSpan retentionPeriod) } public AuditTrailEventDescriptor DescribeEvent(AuditTrailEvent auditTrailEvent) => - DescribeEvent(auditTrailEvent.Name, auditTrailEvent.Category) - ?? AuditTrailEventDescriptor.Default(auditTrailEvent); + DescribeEvent(auditTrailEvent.Name, auditTrailEvent.Category) ?? AuditTrailEventDescriptor.Default(auditTrailEvent); - public IEnumerable DescribeCategories() - => _auditTrailOptions.CategoryDescriptors.Values; + public IEnumerable DescribeCategories() => _auditTrailOptions.CategoryDescriptors.Values; public AuditTrailCategoryDescriptor DescribeCategory(string name) { @@ -168,8 +171,7 @@ private async Task GetClientIpAddressAsync() return (await _clientIPAddressAccessor.GetIPAddressAsync())?.ToString(); } - private async Task GetAuditTrailSettingsAsync() => - (await _siteService.GetSiteSettingsAsync()).As(); + private async Task GetAuditTrailSettingsAsync() => (await _siteService.GetSiteSettingsAsync()).As(); private async Task IsEventEnabledAsync(AuditTrailEventDescriptor descriptor) { @@ -180,9 +182,9 @@ private async Task IsEventEnabledAsync(AuditTrailEventDescriptor descripto var settings = await GetAuditTrailSettingsAsync(); - var eventSettings = settings.Categories - .FirstOrDefault(category => category.Name == descriptor.Category)?.Events - .FirstOrDefault(settings => settings.Name == descriptor.Name); + var eventSettings = settings + .Categories.FirstOrDefault(category => category.Name == descriptor.Category) + ?.Events.FirstOrDefault(settings => settings.Name == descriptor.Name); return eventSettings?.IsEnabled ?? descriptor.IsEnabledByDefault; } diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/CorrelationIdFilterNode.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/CorrelationIdFilterNode.cs index a53f685efad..19d2629ed32 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/CorrelationIdFilterNode.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/CorrelationIdFilterNode.cs @@ -7,14 +7,11 @@ namespace OrchardCore.AuditTrail.Services /// public class CorrelationIdFilterNode : TermOperationNode { - public CorrelationIdFilterNode(string correlationId) : base("id", new UnaryNode(correlationId, OperateNodeQuotes.None)) - { - } + public CorrelationIdFilterNode(string correlationId) + : base("id", new UnaryNode(correlationId, OperateNodeQuotes.None)) { } - public override string ToNormalizedString() - => string.Empty; + public override string ToNormalizedString() => string.Empty; - public override string ToString() - => string.Empty; + public override string ToString() => string.Empty; } } diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DateTimeParser.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DateTimeParser.cs index ae0557f8d74..b6bf5743d28 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DateTimeParser.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DateTimeParser.cs @@ -60,11 +60,9 @@ public DateNode(DateTimeOffset dateTime) public DateTimeOffset DateTime { get; } - public override Expression BuildExpression(in BuildExpressionContext context) - => BuildOperation(context, Expression.Constant(DateTime.UtcDateTime, typeof(DateTime))); + public override Expression BuildExpression(in BuildExpressionContext context) => BuildOperation(context, Expression.Constant(DateTime.UtcDateTime, typeof(DateTime))); - public override string ToString() - => $"{(string.IsNullOrEmpty(Operator) ? string.Empty : Operator)}{DateTime:o}"; + public override string ToString() => $"{(string.IsNullOrEmpty(Operator) ? string.Empty : Operator)}{DateTime:o}"; } public class DateNode2 : OperatorNode @@ -76,18 +74,15 @@ public DateNode2(DateTime dateTime) public DateTime DateTime { get; } - public override Expression BuildExpression(in BuildExpressionContext context) - => BuildOperation(context, Expression.Constant(DateTime, typeof(DateTime))); + public override Expression BuildExpression(in BuildExpressionContext context) => BuildOperation(context, Expression.Constant(DateTime, typeof(DateTime))); - public override string ToString() - => $"{(string.IsNullOrEmpty(Operator) ? string.Empty : Operator)}{DateTime:o}"; + public override string ToString() => $"{(string.IsNullOrEmpty(Operator) ? string.Empty : Operator)}{DateTime:o}"; } public class NowNode : OperatorNode { - public NowNode() - { - } + public NowNode() { } + public NowNode(long arithmetic) { Arithmetic = arithmetic; @@ -95,30 +90,25 @@ public NowNode(long arithmetic) public long? Arithmetic { get; } - public override Expression BuildExpression(in BuildExpressionContext context) - => BuildOperation(context, Expression.Constant(context.UtcNow.AddDays(Arithmetic.GetValueOrDefault()), typeof(DateTime))); + public override Expression BuildExpression(in BuildExpressionContext context) => + BuildOperation(context, Expression.Constant(context.UtcNow.AddDays(Arithmetic.GetValueOrDefault()), typeof(DateTime))); - public override string ToString() - => $"{(string.IsNullOrEmpty(Operator) ? string.Empty : Operator)}@now{(Arithmetic.HasValue ? Arithmetic.Value.ToString() : string.Empty)}"; + public override string ToString() => + $"{(string.IsNullOrEmpty(Operator) ? string.Empty : Operator)}@now{(Arithmetic.HasValue ? Arithmetic.Value.ToString() : string.Empty)}"; } public class TodayNode : NowNode { - public TodayNode() - { - } + public TodayNode() { } - public TodayNode(long arithmetic) : base(arithmetic) - { - } - - public override string ToString() - => $"{(string.IsNullOrEmpty(Operator) ? string.Empty : Operator)}@today{(Arithmetic.HasValue ? Arithmetic.Value.ToString() : string.Empty)}"; + public TodayNode(long arithmetic) + : base(arithmetic) { } + public override string ToString() => + $"{(string.IsNullOrEmpty(Operator) ? string.Empty : Operator)}@today{(Arithmetic.HasValue ? Arithmetic.Value.ToString() : string.Empty)}"; } - public abstract class ExpressionNode : Node - { } + public abstract class ExpressionNode : Node { } public class UnaryExpressionNode : ExpressionNode { @@ -127,12 +117,11 @@ public UnaryExpressionNode(OperatorNode node) Node = node; } - public override Expression BuildExpression(in BuildExpressionContext context) - => Expression.Lambda(context.Type, Node.BuildExpression(context), context.Parameter); + public override Expression BuildExpression(in BuildExpressionContext context) => Expression.Lambda(context.Type, Node.BuildExpression(context), context.Parameter); public OperatorNode Node { get; } - public override string ToString() - => Node.ToString(); + + public override string ToString() => Node.ToString(); } public class BinaryExpressionNode : ExpressionNode @@ -168,18 +157,22 @@ static DateTimeParser() var arithmetic = Terms.Integer(NumberOptions.AllowSign); var range = Literals.Text(".."); - var todayParser = Terms.Text("@today").And(ZeroOrOne(arithmetic)) - .Then(x => - { - if (x.Item2 != 0) - { - return new TodayNode(x.Item2); - } + var todayParser = Terms + .Text("@today") + .And(ZeroOrOne(arithmetic)) + .Then(x => + { + if (x.Item2 != 0) + { + return new TodayNode(x.Item2); + } - return new TodayNode(); - }); + return new TodayNode(); + }); - var nowParser = Terms.Text("@now").And(ZeroOrOne(arithmetic)) + var nowParser = Terms + .Text("@now") + .And(ZeroOrOne(arithmetic)) .Then(x => { if (x.Item2 != 0) @@ -191,37 +184,39 @@ static DateTimeParser() }); var dateParser = AnyCharBefore(range) - .Then((ctx, x) => - { - var context = (DateTimeParseContext)ctx; - var dateValue = x.ToString(); - - // Try o, primarily for times, and fall back to local timezone. - if (DateTimeOffset.TryParseExact(dateValue, "yyyy-MM-dd'T'HH:mm:ss.FFFK", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateTimeOffset)) - { - return new DateNode2(dateTimeOffset.UtcDateTime); - } - else + .Then( + (ctx, x) => { - var success = true; - if (!DateTime.TryParse(dateValue, context.CultureInfo, DateTimeStyles.None, out var dateTime)) + var context = (DateTimeParseContext)ctx; + var dateValue = x.ToString(); + + // Try o, primarily for times, and fall back to local timezone. + if (DateTimeOffset.TryParseExact(dateValue, "yyyy-MM-dd'T'HH:mm:ss.FFFK", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateTimeOffset)) + { + return new DateNode2(dateTimeOffset.UtcDateTime); + } + else { - if (!DateTime.TryParse(dateValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) + var success = true; + if (!DateTime.TryParse(dateValue, context.CultureInfo, DateTimeStyles.None, out var dateTime)) { - success = false; + if (!DateTime.TryParse(dateValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) + { + success = false; + } } - } - // If no timezone is specified, assume local using the configured timezone. - if (success) - { - var converted = context.Clock.ConvertToTimeZone(dateTime, context.UserTimeZone); - return new DateNode2(converted.UtcDateTime.Date); + // If no timezone is specified, assume local using the configured timezone. + if (success) + { + var converted = context.Clock.ConvertToTimeZone(dateTime, context.UserTimeZone); + return new DateNode2(converted.UtcDateTime.Date); + } } - } - throw new ParseException("Could not parse date", context.Scanner.Cursor.Position); - }); + throw new ParseException("Could not parse date", context.Scanner.Cursor.Position); + } + ); var currentParser = OneOf(nowParser, todayParser); @@ -235,26 +230,28 @@ static DateTimeParser() { return new UnaryExpressionNode(x.Item1); } - else { return new BinaryExpressionNode(x.Item1, x.Item2); } }); - Parser = operators.And(valueParser) - .Then(x => - { - x.Item2.Operator = x.Item1; - return new UnaryExpressionNode(x.Item2); - }) - .Or(rangeParser).Compile(); + Parser = operators + .And(valueParser) + .Then(x => + { + x.Item2.Operator = x.Item1; + return new UnaryExpressionNode(x.Item2); + }) + .Or(rangeParser) + .Compile(); } } public class DateTimeParseContext : ParseContext { - public DateTimeParseContext(CultureInfo cultureInfo, IClock clock, ITimeZone userTimeZone, Scanner scanner, bool useNewLines = false) : base(scanner, useNewLines) + public DateTimeParseContext(CultureInfo cultureInfo, IClock clock, ITimeZone userTimeZone, Scanner scanner, bool useNewLines = false) + : base(scanner, useNewLines) { CultureInfo = cultureInfo; Clock = clock; diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListFilterParser.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListFilterParser.cs index 4e51f811bc6..e92119a1655 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListFilterParser.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListFilterParser.cs @@ -12,7 +12,6 @@ public DefaultAuditTrailAdminListFilterParser(IQueryParser pars _parser = parser; } - public QueryFilterResult Parse(string text) - => _parser.Parse(text); + public QueryFilterResult Parse(string text) => _parser.Parse(text); } } diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListFilterProvider.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListFilterProvider.cs index 768c13e9969..11c844f104b 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListFilterProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListFilterProvider.cs @@ -29,185 +29,234 @@ public DefaultAuditTrailAdminListFilterProvider(IOptions builder) { builder - .WithNamedTerm("id", builder => builder - .OneCondition((val, query) => - { - if (!string.IsNullOrEmpty(val)) - { - query.With(x => x.CorrelationId == val); - } - - return query; - }) - .MapTo((val, model) => - { - model.CorrelationId = val; - }) - .MapFrom((model) => - { - if (!string.IsNullOrEmpty(model.CorrelationId)) - { - return (true, model.CorrelationId); - } - return (false, string.Empty); - }) + .WithNamedTerm( + "id", + builder => + builder + .OneCondition( + (val, query) => + { + if (!string.IsNullOrEmpty(val)) + { + query.With(x => x.CorrelationId == val); + } + + return query; + } + ) + .MapTo( + (val, model) => + { + model.CorrelationId = val; + } + ) + .MapFrom( + (model) => + { + if (!string.IsNullOrEmpty(model.CorrelationId)) + { + return (true, model.CorrelationId); + } + return (false, string.Empty); + } + ) ) - .WithNamedTerm("category", builder => builder - .OneCondition((val, query) => - { - if (!string.IsNullOrEmpty(val)) - { - query.With(x => x.Category == val); - } - - return query; - }) - .MapTo((val, model) => - { - model.Category = val; - }) - .MapFrom((model) => - { - if (!string.IsNullOrEmpty(model.Category)) - { - return (true, model.Category); - } - return (false, string.Empty); - }) + .WithNamedTerm( + "category", + builder => + builder + .OneCondition( + (val, query) => + { + if (!string.IsNullOrEmpty(val)) + { + query.With(x => x.Category == val); + } + + return query; + } + ) + .MapTo( + (val, model) => + { + model.Category = val; + } + ) + .MapFrom( + (model) => + { + if (!string.IsNullOrEmpty(model.Category)) + { + return (true, model.Category); + } + return (false, string.Empty); + } + ) ) - .WithNamedTerm("event", builder => builder - .OneCondition((val, query) => - { - if (!string.IsNullOrEmpty(val)) - { - query.With(x => x.Name == val); - } - - return query; - }) - .MapTo((val, model) => - { - model.Event = val; - }) - .MapFrom((model) => - { - if (!string.IsNullOrEmpty(model.Event)) - { - return (true, model.Event); - } - return (false, string.Empty); - }) + .WithNamedTerm( + "event", + builder => + builder + .OneCondition( + (val, query) => + { + if (!string.IsNullOrEmpty(val)) + { + query.With(x => x.Name == val); + } + + return query; + } + ) + .MapTo( + (val, model) => + { + model.Event = val; + } + ) + .MapFrom( + (model) => + { + if (!string.IsNullOrEmpty(model.Event)) + { + return (true, model.Event); + } + return (false, string.Empty); + } + ) ) - .WithNamedTerm("date", builder => builder - .OneCondition(async (val, query, ctx) => - { - if (string.IsNullOrEmpty(val)) - { - return query; - } - - var context = (AuditTrailQueryContext)ctx; - var clock = context.ServiceProvider.GetRequiredService(); - var localClock = context.ServiceProvider.GetRequiredService(); - var userTimeZone = await localClock.GetLocalTimeZoneAsync(); - var parseContext = new DateTimeParseContext(CultureInfo.CurrentUICulture, clock, userTimeZone, new Scanner(val)); - - if (DateTimeParser.Parser.TryParse(parseContext, out var expression, out var parseError)) - { - var utcNow = clock.UtcNow; - - var param = Expression.Parameter(typeof(AuditTrailEventIndex)); - var field = Expression.Property(param, nameof(AuditTrailEventIndex.CreatedUtc)); - var expressionContext = new BuildExpressionContext(utcNow, param, field, typeof(Func)); - - query.With((Expression>)expression.BuildExpression(expressionContext)); - } - - return query; - }) - .MapTo((val, model) => - { - model.Date = val; - }) - .MapFrom((model) => - { - if (!string.IsNullOrEmpty(model.Date)) - { - return (true, model.Date); - } - return (false, string.Empty); - }) + .WithNamedTerm( + "date", + builder => + builder + .OneCondition( + async (val, query, ctx) => + { + if (string.IsNullOrEmpty(val)) + { + return query; + } + + var context = (AuditTrailQueryContext)ctx; + var clock = context.ServiceProvider.GetRequiredService(); + var localClock = context.ServiceProvider.GetRequiredService(); + var userTimeZone = await localClock.GetLocalTimeZoneAsync(); + var parseContext = new DateTimeParseContext(CultureInfo.CurrentUICulture, clock, userTimeZone, new Scanner(val)); + + if (DateTimeParser.Parser.TryParse(parseContext, out var expression, out var parseError)) + { + var utcNow = clock.UtcNow; + + var param = Expression.Parameter(typeof(AuditTrailEventIndex)); + var field = Expression.Property(param, nameof(AuditTrailEventIndex.CreatedUtc)); + var expressionContext = new BuildExpressionContext(utcNow, param, field, typeof(Func)); + + query.With((Expression>)expression.BuildExpression(expressionContext)); + } + + return query; + } + ) + .MapTo( + (val, model) => + { + model.Date = val; + } + ) + .MapFrom( + (model) => + { + if (!string.IsNullOrEmpty(model.Date)) + { + return (true, model.Date); + } + return (false, string.Empty); + } + ) ) - .WithNamedTerm("sort", builder => builder - .OneCondition((val, query, ctx) => - { - var context = (AuditTrailQueryContext)ctx; - var options = context.ServiceProvider.GetRequiredService>().Value; - - if (options.SortOptions.TryGetValue(val, out var sortOption)) - { - return sortOption.Query(val, query, ctx); - } - - return options.DefaultSortOption.Query(val, query, ctx); - }) - .MapTo((val, model) => - { - // TODO add a context property to the mapping func. - if (!string.IsNullOrEmpty(val) && _options.Value.SortOptions.TryGetValue(val, out var sortOption)) - { - model.Sort = sortOption.Value; - } - }) - .MapFrom((model) => - { - // TODO add a context property to the mapping func. - if (model.Sort != _options.Value.DefaultSortOption.Value) - { - return (true, model.Sort); - } - - return (false, string.Empty); - }) - .AlwaysRun() + .WithNamedTerm( + "sort", + builder => + builder + .OneCondition( + (val, query, ctx) => + { + var context = (AuditTrailQueryContext)ctx; + var options = context.ServiceProvider.GetRequiredService>().Value; + + if (options.SortOptions.TryGetValue(val, out var sortOption)) + { + return sortOption.Query(val, query, ctx); + } + + return options.DefaultSortOption.Query(val, query, ctx); + } + ) + .MapTo( + (val, model) => + { + // TODO add a context property to the mapping func. + if (!string.IsNullOrEmpty(val) && _options.Value.SortOptions.TryGetValue(val, out var sortOption)) + { + model.Sort = sortOption.Value; + } + } + ) + .MapFrom( + (model) => + { + // TODO add a context property to the mapping func. + if (model.Sort != _options.Value.DefaultSortOption.Value) + { + return (true, model.Sort); + } + + return (false, string.Empty); + } + ) + .AlwaysRun() ) - .WithDefaultTerm("username", builder => builder - .ManyCondition( - (val, query, ctx) => - { - var context = (AuditTrailQueryContext)ctx; - var lookupNormalizer = context.ServiceProvider.GetRequiredService(); - var normalizedUserName = lookupNormalizer.NormalizeName(val); - query.With(x => x.NormalizedUserName.Contains(normalizedUserName)); - - return new ValueTask>(query); - }, - (val, query, ctx) => - { - var context = (AuditTrailQueryContext)ctx; - var lookupNormalizer = context.ServiceProvider.GetRequiredService(); - var normalizedUserName = lookupNormalizer.NormalizeName(val); - query.With(x => x.NormalizedUserName.NotContains(normalizedUserName)); - - return new ValueTask>(query); - } - ) + .WithDefaultTerm( + "username", + builder => + builder.ManyCondition( + (val, query, ctx) => + { + var context = (AuditTrailQueryContext)ctx; + var lookupNormalizer = context.ServiceProvider.GetRequiredService(); + var normalizedUserName = lookupNormalizer.NormalizeName(val); + query.With(x => x.NormalizedUserName.Contains(normalizedUserName)); + + return new ValueTask>(query); + }, + (val, query, ctx) => + { + var context = (AuditTrailQueryContext)ctx; + var lookupNormalizer = context.ServiceProvider.GetRequiredService(); + var normalizedUserName = lookupNormalizer.NormalizeName(val); + query.With(x => x.NormalizedUserName.NotContains(normalizedUserName)); + + return new ValueTask>(query); + } + ) ) - .WithNamedTerm("userid", builder => builder - .ManyCondition( - (val, query) => - { - query.With(x => x.UserId.Contains(val)); - - return query; - }, - (val, query) => - { - query.With(x => x.UserId.NotContains(val)); - - return query; - } - ) + .WithNamedTerm( + "userid", + builder => + builder.ManyCondition( + (val, query) => + { + query.With(x => x.UserId.Contains(val)); + + return query; + }, + (val, query) => + { + query.With(x => x.UserId.NotContains(val)); + + return query; + } + ) ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListQueryService.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListQueryService.cs index 63db00d7ef4..1e09d95d6d5 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListQueryService.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Services/DefaultAuditTrailAdminListQueryService.cs @@ -29,7 +29,8 @@ public DefaultAuditTrailAdminListQueryService( IOptions adminListOptions, ISession session, IServiceProvider serviceProvider, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _auditTrailManager = auditTrailManager; _localClock = localClock; @@ -60,13 +61,12 @@ public async Task QueryAsync(int page, int pageSize, var events = await query.ListAsync(); - var result = new AuditTrailEventQueryResult - { - Events = events, - TotalCount = totalCount - }; + var result = new AuditTrailEventQueryResult { Events = events, TotalCount = totalCount }; - options.AuditTrailSorts = _adminListOptions.SortOptions.Values.Where(x => x.SelectListItem != null).Select(opt => opt.SelectListItem(_serviceProvider, opt, options)).ToList(); + options.AuditTrailSorts = _adminListOptions + .SortOptions.Values.Where(x => x.SelectListItem != null) + .Select(opt => opt.SelectListItem(_serviceProvider, opt, options)) + .ToList(); var categories = _auditTrailManager.DescribeCategories(); @@ -84,8 +84,9 @@ public async Task QueryAsync(int page, int pageSize, var currentCategory = categories.FirstOrDefault(x => x.Name == firstEvent.Category); if (currentCategory != null) { - options.Events = currentCategory.Events.Values.Select(category => - new SelectListItem(category.LocalizedName(_serviceProvider), category.Name, category.Name == options.Category)).ToList(); + options.Events = currentCategory + .Events.Values.Select(category => new SelectListItem(category.LocalizedName(_serviceProvider), category.Name, category.Name == options.Category)) + .ToList(); } } } @@ -93,10 +94,7 @@ public async Task QueryAsync(int page, int pageSize, var localNow = await _localClock.LocalNowAsync; var startOfWeek = CultureInfo.CurrentUICulture.DateTimeFormat.FirstDayOfWeek; - options.AuditTrailDates = - [ - new(S["Any date"], string.Empty, options.Date == string.Empty), - ]; + options.AuditTrailDates = [new(S["Any date"], string.Empty, options.Date == string.Empty),]; var dateTimeValue = ">@now-1"; options.AuditTrailDates.Add(new SelectListItem(S["Last 24 hours"], dateTimeValue, options.Date == dateTimeValue)); diff --git a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Startup.cs b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Startup.cs index 6095ebb667c..356917ae9b7 100644 --- a/src/OrchardCore.Modules/OrchardCore.AuditTrail/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.AuditTrail/Startup.cs @@ -32,8 +32,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); - services - .AddScoped, AuditTrailEventDisplayDriver>(); + services.AddScoped, AuditTrailEventDisplayDriver>(); services.AddSingleton(); @@ -75,50 +74,60 @@ public override void ConfigureServices(IServiceCollection services) services.Configure(options => { options - .ForSort("time-desc", b => b - .WithQuery((val, query) => query.With().OrderByDescending(i => i.CreatedUtc)) - .WithSelectListItem((S, opt, model) => new SelectListItem(S["Newest"], opt.Value, model.Sort == string.Empty)) - .AsDefault()) - - .ForSort("time-asc", b => b - .WithQuery((val, query) => query.With().OrderBy(i => i.CreatedUtc)) - .WithSelectListItem((S, opt, model) => new SelectListItem(S["Oldest"], opt.Value, model.Sort == opt.Value))) - - .ForSort("category-asc-time-desc", b => b - .WithQuery((val, query) => query.With().OrderBy(i => i.Category).ThenByDescending(i => i.CreatedUtc)) - .WithSelectListItem((S, opt, model) => new SelectListItem(S["Category"], opt.Value, model.Sort == opt.Value))) - - .ForSort("category-asc-time-asc", b => b - .WithQuery((val, query) => query.With().OrderBy(i => i.Category).ThenBy(i => i.CreatedUtc))) - - .ForSort("category-desc-time-desc", b => b - .WithQuery((val, query) => query.With().OrderByDescending(i => i.Category).ThenByDescending(i => i.CreatedUtc))) - - .ForSort("category-desc-time-asc", b => b - .WithQuery((val, query) => query.With().OrderByDescending(i => i.Category).ThenBy(i => i.CreatedUtc))) - - .ForSort("event-asc-time-desc", b => b - .WithQuery((val, query) => query.With().OrderBy(i => i.Name).ThenByDescending(i => i.CreatedUtc)) - .WithSelectListItem((S, opt, model) => new SelectListItem(S["Event"], opt.Value, model.Sort == opt.Value))) - - .ForSort("event-asc-time-asc", b => b - .WithQuery((val, query) => query.With().OrderBy(i => i.Name).ThenBy(i => i.CreatedUtc))) - - .ForSort("event-desc-time-desc", b => b - .WithQuery((val, query) => query.With().OrderByDescending(i => i.Name).ThenByDescending(i => i.CreatedUtc))) - - .ForSort("event-desc-time-asc", b => b - .WithQuery((val, query) => query.With().OrderByDescending(i => i.Name).ThenBy(i => i.CreatedUtc))) - - .ForSort("user-asc-time-asc", b => b - .WithQuery((val, query) => query.With().OrderBy(i => i.NormalizedUserName).ThenBy(i => i.CreatedUtc)) - .WithSelectListItem((S, opt, model) => new SelectListItem(S["User"], opt.Value, model.Sort == opt.Value))) - - .ForSort("user-desc-time-desc", b => b - .WithQuery((val, query) => query.With().OrderByDescending(i => i.NormalizedUserName).ThenByDescending(i => i.CreatedUtc))) - - .ForSort("user-desc-time-asc", b => b - .WithQuery((val, query) => query.With().OrderByDescending(i => i.NormalizedUserName).ThenBy(i => i.CreatedUtc))); + .ForSort( + "time-desc", + b => + b.WithQuery((val, query) => query.With().OrderByDescending(i => i.CreatedUtc)) + .WithSelectListItem((S, opt, model) => new SelectListItem(S["Newest"], opt.Value, model.Sort == string.Empty)) + .AsDefault() + ) + .ForSort( + "time-asc", + b => + b.WithQuery((val, query) => query.With().OrderBy(i => i.CreatedUtc)) + .WithSelectListItem((S, opt, model) => new SelectListItem(S["Oldest"], opt.Value, model.Sort == opt.Value)) + ) + .ForSort( + "category-asc-time-desc", + b => + b.WithQuery((val, query) => query.With().OrderBy(i => i.Category).ThenByDescending(i => i.CreatedUtc)) + .WithSelectListItem((S, opt, model) => new SelectListItem(S["Category"], opt.Value, model.Sort == opt.Value)) + ) + .ForSort("category-asc-time-asc", b => b.WithQuery((val, query) => query.With().OrderBy(i => i.Category).ThenBy(i => i.CreatedUtc))) + .ForSort( + "category-desc-time-desc", + b => b.WithQuery((val, query) => query.With().OrderByDescending(i => i.Category).ThenByDescending(i => i.CreatedUtc)) + ) + .ForSort( + "category-desc-time-asc", + b => b.WithQuery((val, query) => query.With().OrderByDescending(i => i.Category).ThenBy(i => i.CreatedUtc)) + ) + .ForSort( + "event-asc-time-desc", + b => + b.WithQuery((val, query) => query.With().OrderBy(i => i.Name).ThenByDescending(i => i.CreatedUtc)) + .WithSelectListItem((S, opt, model) => new SelectListItem(S["Event"], opt.Value, model.Sort == opt.Value)) + ) + .ForSort("event-asc-time-asc", b => b.WithQuery((val, query) => query.With().OrderBy(i => i.Name).ThenBy(i => i.CreatedUtc))) + .ForSort( + "event-desc-time-desc", + b => b.WithQuery((val, query) => query.With().OrderByDescending(i => i.Name).ThenByDescending(i => i.CreatedUtc)) + ) + .ForSort("event-desc-time-asc", b => b.WithQuery((val, query) => query.With().OrderByDescending(i => i.Name).ThenBy(i => i.CreatedUtc))) + .ForSort( + "user-asc-time-asc", + b => + b.WithQuery((val, query) => query.With().OrderBy(i => i.NormalizedUserName).ThenBy(i => i.CreatedUtc)) + .WithSelectListItem((S, opt, model) => new SelectListItem(S["User"], opt.Value, model.Sort == opt.Value)) + ) + .ForSort( + "user-desc-time-desc", + b => b.WithQuery((val, query) => query.With().OrderByDescending(i => i.NormalizedUserName).ThenByDescending(i => i.CreatedUtc)) + ) + .ForSort( + "user-desc-time-asc", + b => b.WithQuery((val, query) => query.With().OrderByDescending(i => i.NormalizedUserName).ThenBy(i => i.CreatedUtc)) + ); }); } } @@ -129,7 +138,10 @@ public class DeploymentStartup : StartupBase public override void ConfigureServices(IServiceCollection services) { services.AddSiteSettingsPropertyDeploymentStep(S => S["Audit Trail settings"], S => S["Exports the audit trail settings."]); - services.AddSiteSettingsPropertyDeploymentStep(S => S["Audit Trail Trimming settings"], S => S["Exports the audit trail trimming settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Audit Trail Trimming settings"], + S => S["Exports the audit trail trimming settings."] + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.AutoSetup/AutoSetupMiddleware.cs b/src/OrchardCore.Modules/OrchardCore.AutoSetup/AutoSetupMiddleware.cs index fc639cba1f6..f274b5ae8af 100644 --- a/src/OrchardCore.Modules/OrchardCore.AutoSetup/AutoSetupMiddleware.cs +++ b/src/OrchardCore.Modules/OrchardCore.AutoSetup/AutoSetupMiddleware.cs @@ -83,7 +83,8 @@ public AutoSetupMiddleware( IShellSettingsManager shellSettingsManager, IDistributedLock distributedLock, IOptions options, - ILogger logger) + ILogger logger + ) { _next = next; _shellHost = shellHost; @@ -128,9 +129,7 @@ public async Task InvokeAsync(HttpContext httpContext) } // Check if the tenant was installed by another instance. - using var settings = (await _shellSettingsManager - .LoadSettingsAsync(_shellSettings.Name)) - .AsDisposable(); + using var settings = (await _shellSettingsManager.LoadSettingsAsync(_shellSettings.Name)).AsDisposable(); if (!settings.IsUninitialized()) { @@ -207,10 +206,7 @@ public async Task SetupTenantAsync(ISetupService setupService, TenantSetup /// The . public async Task CreateTenantSettingsAsync(TenantSetupOptions setupOptions) { - using var shellSettings = _shellSettingsManager - .CreateDefaultSettings() - .AsUninitialized() - .AsDisposable(); + using var shellSettings = _shellSettingsManager.CreateDefaultSettings().AsUninitialized().AsDisposable(); shellSettings.Name = setupOptions.ShellName; shellSettings.RequestUrlHost = setupOptions.RequestUrlHost; diff --git a/src/OrchardCore.Modules/OrchardCore.AutoSetup/Extensions/DistributedLockExtensions.cs b/src/OrchardCore.Modules/OrchardCore.AutoSetup/Extensions/DistributedLockExtensions.cs index e54f268ddc6..a35a1b88ba5 100644 --- a/src/OrchardCore.Modules/OrchardCore.AutoSetup/Extensions/DistributedLockExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.AutoSetup/Extensions/DistributedLockExtensions.cs @@ -25,7 +25,8 @@ public static class DistributedLockExtensions /// public static Task<(ILocker locker, bool locked)> TryAcquireAutoSetupLockAsync(this IDistributedLock distributedLock, LockOptions lockOptions) { - TimeSpan timeout, expiration; + TimeSpan timeout, + expiration; if (distributedLock is ILocalLock) { // If it is a local lock, don't use any timeout and expiration. diff --git a/src/OrchardCore.Modules/OrchardCore.AutoSetup/Startup.cs b/src/OrchardCore.Modules/OrchardCore.AutoSetup/Startup.cs index 5ab8fd246ae..2003cdc085d 100644 --- a/src/OrchardCore.Modules/OrchardCore.AutoSetup/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.AutoSetup/Startup.cs @@ -112,8 +112,7 @@ public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder ro } else { - app.MapWhen(ctx => ctx.Request.Path.StartsWithNormalizedSegments(options.AutoSetupPath), - appBuilder => appBuilder.UseMiddleware()); + app.MapWhen(ctx => ctx.Request.Path.StartsWithNormalizedSegments(options.AutoSetupPath), appBuilder => appBuilder.UseMiddleware()); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Drivers/AutoroutePartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Drivers/AutoroutePartDisplayDriver.cs index aa5c62d6a44..17b0191992b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Drivers/AutoroutePartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Drivers/AutoroutePartDisplayDriver.cs @@ -48,34 +48,37 @@ IStringLocalizer localizer public override IDisplayResult Edit(AutoroutePart autoroutePart, BuildPartEditorContext context) { - return Initialize("AutoroutePart_Edit", async model => - { - model.Path = autoroutePart.Path; - model.AutoroutePart = autoroutePart; - model.ContentItem = autoroutePart.ContentItem; - model.SetHomepage = false; + return Initialize( + "AutoroutePart_Edit", + async model => + { + model.Path = autoroutePart.Path; + model.AutoroutePart = autoroutePart; + model.ContentItem = autoroutePart.ContentItem; + model.SetHomepage = false; - var siteSettings = await _siteService.GetSiteSettingsAsync(); - var homeRoute = siteSettings.HomeRoute; + var siteSettings = await _siteService.GetSiteSettingsAsync(); + var homeRoute = siteSettings.HomeRoute; - if (homeRoute != null && homeRoute.TryGetValue(_options.ContainedContentItemIdKey, out var containedContentItemId)) - { - if (string.Equals(autoroutePart.ContentItem.ContentItemId, containedContentItemId.ToString(), StringComparison.OrdinalIgnoreCase)) + if (homeRoute != null && homeRoute.TryGetValue(_options.ContainedContentItemIdKey, out var containedContentItemId)) + { + if (string.Equals(autoroutePart.ContentItem.ContentItemId, containedContentItemId.ToString(), StringComparison.OrdinalIgnoreCase)) + { + model.IsHomepage = true; + } + } + else if (string.Equals(autoroutePart.ContentItem.ContentItemId, homeRoute?[_options.ContentItemIdKey]?.ToString(), StringComparison.OrdinalIgnoreCase)) { model.IsHomepage = true; } - } - else if (string.Equals(autoroutePart.ContentItem.ContentItemId, homeRoute?[_options.ContentItemIdKey]?.ToString(), StringComparison.OrdinalIgnoreCase)) - { - model.IsHomepage = true; - } - model.Disabled = autoroutePart.Disabled; - model.Absolute = autoroutePart.Absolute; - model.RouteContainedItems = autoroutePart.RouteContainedItems; + model.Disabled = autoroutePart.Disabled; + model.Absolute = autoroutePart.Absolute; + model.RouteContainedItems = autoroutePart.RouteContainedItems; - model.Settings = context.TypePartDefinition.GetSettings(); - }); + model.Settings = context.TypePartDefinition.GetSettings(); + } + ); } public override async Task UpdateAsync(AutoroutePart model, IUpdateModel updater, UpdatePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/AutorouteContentHandler.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/AutorouteContentHandler.cs index 73285044ae0..3787c64ec12 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/AutorouteContentHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/AutorouteContentHandler.cs @@ -24,11 +24,12 @@ public override Task GetContentItemAspectAsync(ContentItemAspectContext context) if (found && !string.IsNullOrEmpty(entry.ContainedContentItemId)) { - metadata.DisplayRouteValues = new RouteValueDictionary { + metadata.DisplayRouteValues = new RouteValueDictionary + { { "Area", "OrchardCore.Contents" }, { "Controller", "Item" }, { "Action", "Display" }, - { "ContentItemId", entry.ContentItemId}, + { "ContentItemId", entry.ContentItemId }, { "ContainedContentItemId", entry.ContainedContentItemId } }; } diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/AutoroutePartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/AutoroutePartHandler.cs index 833546fdd66..2a1676645bb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/AutoroutePartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/AutoroutePartHandler.cs @@ -50,7 +50,8 @@ public AutoroutePartHandler( ITagCache tagCache, ISession session, IServiceProvider serviceProvider, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _entries = entries; _options = options.Value; @@ -80,11 +81,14 @@ public override async Task PublishedAsync(PublishContentContext context, Autorou if (!string.IsNullOrWhiteSpace(part.Path) && !part.Disabled && part.SetHomepage) { - await SetHomeRouteAsync(part, homeRoute => - { - homeRoute[_options.ContentItemIdKey] = context.ContentItem.ContentItemId; - homeRoute.Remove(_options.JsonPathKey); - }); + await SetHomeRouteAsync( + part, + homeRoute => + { + homeRoute[_options.ContentItemIdKey] = context.ContentItem.ContentItemId; + homeRoute.Remove(_options.JsonPathKey); + } + ); } // Evict any dependent item from cache. @@ -132,7 +136,6 @@ public override async Task ValidatingAsync(ValidateContentContext context, Autor { context.Fail(S["Your permalink is already in use."], nameof(part.Path)); } - } public override async Task UpdatedAsync(UpdateContentContext context, AutoroutePart part) @@ -141,7 +144,7 @@ public override async Task UpdatedAsync(UpdateContentContext context, AutorouteP await GenerateContainedPathsFromPatternAsync(context.UpdatingItem, part); } - public async override Task CloningAsync(CloneContentContext context, AutoroutePart part) + public override async Task CloningAsync(CloneContentContext context, AutoroutePart part) { var clonedPart = context.CloneContentItem.As(); clonedPart.Path = await GenerateUniqueAbsolutePathAsync(part.Path, context.CloneContentItem.ContentItemId); @@ -211,11 +214,14 @@ private async Task CheckContainedHomeRouteAsync(string containerContentItemId, C var autoroutePart = contentItem.As(); if (autoroutePart != null && autoroutePart.SetHomepage) { - await SetHomeRouteAsync(autoroutePart, homeRoute => - { - homeRoute[_options.ContentItemIdKey] = containerContentItemId; - homeRoute[_options.JsonPathKey] = jItem.GetNormalizedPath(); - }); + await SetHomeRouteAsync( + autoroutePart, + homeRoute => + { + homeRoute[_options.ContentItemIdKey] = containerContentItemId; + homeRoute[_options.JsonPathKey] = jItem.GetNormalizedPath(); + } + ); break; } @@ -242,7 +248,13 @@ private async Task GenerateContainedPathsFromPatternAsync(ContentItem contentIte await ValidateContainedContentItemRoutesAsync(entries, part.ContentItem.ContentItemId, containedAspect, (JsonObject)contentItem.Content, part.Path); } - private async Task PopulateContainedContentItemRoutesAsync(List entries, string containerContentItemId, ContainedContentItemsAspect containedContentItemsAspect, JsonObject content, string basePath) + private async Task PopulateContainedContentItemRoutesAsync( + List entries, + string containerContentItemId, + ContainedContentItemsAspect containedContentItemsAspect, + JsonObject content, + string basePath + ) { foreach (var accessor in containedContentItemsAspect.Accessors) { @@ -261,10 +273,7 @@ private async Task PopulateContainedContentItemRoutesAsync(List path = (basePath.EndsWith('/') ? basePath : basePath + '/') + handlerAspect.Path.TrimStart('/'); } - entries.Add(new AutorouteEntry(containerContentItemId, path, contentItem.ContentItemId, jItem.GetNormalizedPath()) - { - DocumentId = contentItem.Id - }); + entries.Add(new AutorouteEntry(containerContentItemId, path, contentItem.ContentItemId, jItem.GetNormalizedPath()) { DocumentId = contentItem.Id }); } var itemBasePath = (basePath.EndsWith('/') ? basePath : basePath + '/') + handlerAspect.Path.TrimStart('/'); @@ -274,7 +283,13 @@ private async Task PopulateContainedContentItemRoutesAsync(List } } - private async Task ValidateContainedContentItemRoutesAsync(List entries, string containerContentItemId, ContainedContentItemsAspect containedContentItemsAspect, JsonObject content, string basePath) + private async Task ValidateContainedContentItemRoutesAsync( + List entries, + string containerContentItemId, + ContainedContentItemsAspect containedContentItemsAspect, + JsonObject content, + string basePath + ) { foreach (var accessor in containedContentItemsAspect.Accessors) { @@ -298,11 +313,10 @@ private async Task ValidateContainedContentItemRoutesAsync(List containedAutoroutePart.Apply(); // Merge because we have disconnected the content item from it's json owner. - jItem.Merge((JsonObject)contentItem.Content, new JsonMergeSettings - { - MergeArrayHandling = MergeArrayHandling.Replace, - MergeNullValueHandling = MergeNullValueHandling.Merge - }); + jItem.Merge( + (JsonObject)contentItem.Content, + new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge } + ); } else { @@ -316,11 +330,10 @@ private async Task ValidateContainedContentItemRoutesAsync(List containedAutoroutePart.Apply(); // Merge because we have disconnected the content item from it's json owner. - jItem.Merge((JsonObject)contentItem.Content, new JsonMergeSettings - { - MergeArrayHandling = MergeArrayHandling.Replace, - MergeNullValueHandling = MergeNullValueHandling.Merge - }); + jItem.Merge( + (JsonObject)contentItem.Content, + new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge } + ); } path = path[currentItemBasePath.Length..]; @@ -336,7 +349,9 @@ private async Task ValidateContainedContentItemRoutesAsync(List private static bool IsRelativePathUnique(List entries, string path, AutoroutePart context) { - var result = !entries.Any(e => context.ContentItem.ContentItemId != e.ContainedContentItemId && string.Equals(e.Path.Trim('/'), path.Trim('/'), StringComparison.OrdinalIgnoreCase)); + var result = !entries.Any(e => + context.ContentItem.ContentItemId != e.ContainedContentItemId && string.Equals(e.Path.Trim('/'), path.Trim('/'), StringComparison.OrdinalIgnoreCase) + ); return result; } @@ -398,8 +413,12 @@ private async Task GenerateContainerPathFromPatternAsync(AutoroutePart part) using (CultureScope.Create(cultureAspect.Culture, ignoreSystemSettings: cultureOptions.IgnoreSystemSettings)) { - part.Path = await _liquidTemplateManager.RenderStringAsync(pattern, NullEncoder.Default, model, - new Dictionary() { [nameof(ContentItem)] = new ObjectValue(model.ContentItem) }); + part.Path = await _liquidTemplateManager.RenderStringAsync( + pattern, + NullEncoder.Default, + model, + new Dictionary() { [nameof(ContentItem)] = new ObjectValue(model.ContentItem) } + ); } part.Path = part.Path.Replace("\r", string.Empty).Replace("\n", string.Empty); diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Indexing/AutoroutePartIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Indexing/AutoroutePartIndexHandler.cs index 60a089e0490..8a66bbc768f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Indexing/AutoroutePartIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Indexing/AutoroutePartIndexHandler.cs @@ -8,9 +8,7 @@ public class AutoroutePartIndexHandler : ContentPartIndexHandler { public override Task BuildIndexAsync(AutoroutePart part, BuildPartIndexContext context) { - var options = context.Settings.ToOptions() - & ~DocumentIndexOptions.Sanitize - ; + var options = context.Settings.ToOptions() & ~DocumentIndexOptions.Sanitize; foreach (var key in context.Keys) { diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Migrations.cs index 7db23059adf..bcde9322f5d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Migrations.cs @@ -19,17 +19,19 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("AutoroutePart", builder => builder - .Attachable() - .WithDescription("Provides a custom url for your content item.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "AutoroutePart", + builder => builder.Attachable().WithDescription("Provides a custom url for your content item.") + ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", c => c.WithLength(26)) - .Column("ContainedContentItemId", c => c.WithLength(26)) - .Column("JsonPath", c => c.Unlimited()) - .Column("Path", col => col.WithLength(AutoroutePart.MaxPathLength)) - .Column("Published") - .Column("Latest") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", c => c.WithLength(26)) + .Column("ContainedContentItemId", c => c.WithLength(26)) + .Column("JsonPath", c => c.Unlimited()) + .Column("Path", col => col.WithLength(AutoroutePart.MaxPathLength)) + .Column("Published") + .Column("Latest") ); // Shortcut other migration steps on new content definition schemas. @@ -56,17 +58,11 @@ public int UpdateFrom2() // This code can be removed in a later version. public async Task UpdateFrom3Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("ContainedContentItemId", c => c.WithLength(26)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("ContainedContentItemId", c => c.WithLength(26))); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("JsonPath", c => c.Unlimited()) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("JsonPath", c => c.Unlimited())); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Latest", c => c.WithDefault(false)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Latest", c => c.WithDefault(false))); return 4; } diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Models/AutoroutePartExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Models/AutoroutePartExtensions.cs index ffb16a5a37d..0126399082e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Models/AutoroutePartExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Models/AutoroutePartExtensions.cs @@ -18,12 +18,21 @@ public static IEnumerable ValidatePathFieldValue(this Autorout if (HasInvalidCharacters(autoroute.Path)) { var invalidCharactersForMessage = string.Join(", ", AutoroutePart.InvalidCharactersForPath.Select(c => $"\"{c}\"")); - yield return new ValidationResult(S["Please do not use any of the following characters in your permalink: {0}. No spaces, or consecutive slashes, are allowed (please use dashes or underscores instead).", invalidCharactersForMessage], new[] { nameof(autoroute.Path) }); + yield return new ValidationResult( + S[ + "Please do not use any of the following characters in your permalink: {0}. No spaces, or consecutive slashes, are allowed (please use dashes or underscores instead).", + invalidCharactersForMessage + ], + new[] { nameof(autoroute.Path) } + ); } if (autoroute.Path?.Length > AutoroutePart.MaxPathLength) { - yield return new ValidationResult(S["Your permalink is too long. The permalink can only be up to {0} characters.", AutoroutePart.MaxPathLength], new[] { nameof(autoroute.Path) }); + yield return new ValidationResult( + S["Your permalink is too long. The permalink can only be up to {0} characters.", AutoroutePart.MaxPathLength], + new[] { nameof(autoroute.Path) } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Permissions.cs index 924380c8769..a36ce776b6e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission SetHomepage = new("SetHomepage", "Set homepage."); - private readonly IEnumerable _allPermissions = - [ - SetHomepage, - ]; + private readonly IEnumerable _allPermissions = [SetHomepage,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Routing/AutorouteTransformer.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Routing/AutorouteTransformer.cs index 00366911063..9ffed62454f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Routing/AutorouteTransformer.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Routing/AutorouteTransformer.cs @@ -24,10 +24,7 @@ public override async ValueTask TransformAsync(HttpContext if (found) { - var routeValues = new RouteValueDictionary(_options.GlobalRouteValues) - { - [_options.ContentItemIdKey] = entry.ContentItemId - }; + var routeValues = new RouteValueDictionary(_options.GlobalRouteValues) { [_options.ContentItemIdKey] = entry.ContentItemId }; if (!string.IsNullOrEmpty(entry.JsonPath)) { @@ -38,7 +35,6 @@ public override async ValueTask TransformAsync(HttpContext values.Clear(); return routeValues; - } return null; diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Routing/AutorouteValuesAddressScheme.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Routing/AutorouteValuesAddressScheme.cs index 5a21d7d56c5..ce023ae45b5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Routing/AutorouteValuesAddressScheme.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Routing/AutorouteValuesAddressScheme.cs @@ -69,14 +69,7 @@ public IEnumerable FindEndpoints(RouteValuesAddress address) } } - var endpoint = new RouteEndpoint - ( - c => null, - RoutePatternFactory.Parse(autorouteEntry.Path, routeValues, null), - 0, - null, - null - ); + var endpoint = new RouteEndpoint(c => null, RoutePatternFactory.Parse(autorouteEntry.Path, routeValues, null), 0, null, null); return new[] { endpoint }; } diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Settings/AutoroutePartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Settings/AutoroutePartSettingsDisplayDriver.cs index 0f5c30fdd66..59ca3cd47c5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Settings/AutoroutePartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Settings/AutoroutePartSettingsDisplayDriver.cs @@ -23,27 +23,33 @@ public AutoroutePartSettingsDisplayDriver(ILiquidTemplateManager templateManager public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("AutoroutePartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + "AutoroutePartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); - model.AllowCustomPath = settings.AllowCustomPath; - model.AllowUpdatePath = settings.AllowUpdatePath; - model.Pattern = settings.Pattern; - model.ShowHomepageOption = settings.ShowHomepageOption; - model.AllowDisabled = settings.AllowDisabled; - model.AllowRouteContainedItems = settings.AllowRouteContainedItems; - model.ManageContainedItemRoutes = settings.ManageContainedItemRoutes; - model.AllowAbsolutePath = settings.AllowAbsolutePath; - model.AutoroutePartSettings = settings; - }).Location("Content"); + model.AllowCustomPath = settings.AllowCustomPath; + model.AllowUpdatePath = settings.AllowUpdatePath; + model.Pattern = settings.Pattern; + model.ShowHomepageOption = settings.ShowHomepageOption; + model.AllowDisabled = settings.AllowDisabled; + model.AllowRouteContainedItems = settings.AllowRouteContainedItems; + model.ManageContainedItemRoutes = settings.ManageContainedItemRoutes; + model.AllowAbsolutePath = settings.AllowAbsolutePath; + model.AutoroutePartSettings = settings; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) { var model = new AutoroutePartSettingsViewModel(); - await context.Updater.TryUpdateModelAsync(model, Prefix, + await context.Updater.TryUpdateModelAsync( + model, + Prefix, m => m.Pattern, m => m.AllowCustomPath, m => m.AllowUpdatePath, @@ -51,7 +57,8 @@ await context.Updater.TryUpdateModelAsync(model, Prefix, m => m.AllowDisabled, m => m.AllowRouteContainedItems, m => m.ManageContainedItemRoutes, - m => m.AllowAbsolutePath); + m => m.AllowAbsolutePath + ); if (!string.IsNullOrEmpty(model.Pattern) && !_templateManager.Validate(model.Pattern, out var errors)) { @@ -59,17 +66,19 @@ await context.Updater.TryUpdateModelAsync(model, Prefix, } else { - context.Builder.WithSettings(new AutoroutePartSettings - { - Pattern = model.Pattern, - AllowCustomPath = model.AllowCustomPath, - AllowUpdatePath = model.AllowUpdatePath, - ShowHomepageOption = model.ShowHomepageOption, - AllowDisabled = model.AllowDisabled, - AllowRouteContainedItems = model.AllowRouteContainedItems, - ManageContainedItemRoutes = model.ManageContainedItemRoutes, - AllowAbsolutePath = model.AllowAbsolutePath - }); + context.Builder.WithSettings( + new AutoroutePartSettings + { + Pattern = model.Pattern, + AllowCustomPath = model.AllowCustomPath, + AllowUpdatePath = model.AllowUpdatePath, + ShowHomepageOption = model.ShowHomepageOption, + AllowDisabled = model.AllowDisabled, + AllowRouteContainedItems = model.AllowRouteContainedItems, + ManageContainedItemRoutes = model.ManageContainedItemRoutes, + AllowAbsolutePath = model.AllowAbsolutePath + } + ); } return Edit(contentTypePartDefinition, context.Updater); diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Sitemaps/AutorouteContentTypeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Sitemaps/AutorouteContentTypeProvider.cs index 2d256e7a71d..974c503bc47 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Sitemaps/AutorouteContentTypeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Sitemaps/AutorouteContentTypeProvider.cs @@ -16,10 +16,7 @@ public class AutorouteContentTypeProvider : IRouteableContentTypeProvider private readonly IContentDefinitionManager _contentDefinitionManager; private readonly IContentManager _contentManager; - public AutorouteContentTypeProvider( - IContentDefinitionManager contentDefinitionManager, - IContentManager contentManager - ) + public AutorouteContentTypeProvider(IContentDefinitionManager contentDefinitionManager, IContentManager contentManager) { _contentDefinitionManager = contentDefinitionManager; _contentManager = contentManager; @@ -44,8 +41,7 @@ public async Task GetRouteAsync(SitemapBuilderContext context, ContentIt public async Task> ListRoutableTypeDefinitionsAsync() { - return (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(ctd => ctd.Parts.Any(p => p.Name == nameof(AutoroutePart))); + return (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(ctd => ctd.Parts.Any(p => p.Name == nameof(AutoroutePart))); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Startup.cs index 13573cc11ef..48cec4fb108 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Startup.cs @@ -41,36 +41,40 @@ public override void ConfigureServices(IServiceCollection services) { o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register("Slug", (obj, context) => - { - var liquidTemplateContext = (LiquidTemplateContext)context; - - return new LiquidPropertyAccessor(liquidTemplateContext, async (slug, context) => + o.MemberAccessStrategy.Register( + "Slug", + (obj, context) => { - var autorouteEntries = context.Services.GetRequiredService(); - var contentManager = context.Services.GetRequiredService(); - - if (!slug.StartsWith('/')) - { - slug = "/" + slug; - } - - (var found, var entry) = await autorouteEntries.TryGetEntryByPathAsync(slug); - - if (found) - { - return FluidValue.Create(await contentManager.GetAsync(entry.ContentItemId, entry.JsonPath), context.Options); - } - - return NilValue.Instance; - }); - }); + var liquidTemplateContext = (LiquidTemplateContext)context; + + return new LiquidPropertyAccessor( + liquidTemplateContext, + async (slug, context) => + { + var autorouteEntries = context.Services.GetRequiredService(); + var contentManager = context.Services.GetRequiredService(); + + if (!slug.StartsWith('/')) + { + slug = "/" + slug; + } + + (var found, var entry) = await autorouteEntries.TryGetEntryByPathAsync(slug); + + if (found) + { + return FluidValue.Create(await contentManager.GetAsync(entry.ContentItemId, entry.JsonPath), context.Options); + } + + return NilValue.Instance; + } + ); + } + ); }); // Autoroute Part - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/AdminMenu.cs index d2b4569ef92..cb469f3dc22 100644 --- a/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/AdminMenu.cs @@ -17,16 +17,21 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Tasks"], S["Tasks"].PrefixPosition(), tasks => tasks - .Add(S["Background Tasks"], S["Background Tasks"].PrefixPosition(), backgroundTasks => backgroundTasks - .Action("Index", "BackgroundTask", "OrchardCore.BackgroundTasks") - .Permission(Permissions.ManageBackgroundTasks) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Tasks"], + S["Tasks"].PrefixPosition(), + tasks => + tasks.Add( + S["Background Tasks"], + S["Background Tasks"].PrefixPosition(), + backgroundTasks => + backgroundTasks.Action("Index", "BackgroundTask", "OrchardCore.BackgroundTasks").Permission(Permissions.ManageBackgroundTasks).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Controllers/BackgroundTaskController.cs b/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Controllers/BackgroundTaskController.cs index 68bf3b80fd2..28999feae1c 100644 --- a/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Controllers/BackgroundTaskController.cs +++ b/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Controllers/BackgroundTaskController.cs @@ -44,7 +44,8 @@ public BackgroundTaskController( IShapeFactory shapeFactory, IHtmlLocalizer htmlLocalizer, IStringLocalizer stringLocalizer, - INotifier notifier) + INotifier notifier + ) { _authorizationService = authorizationService; _backgroundTasks = backgroundTasks; @@ -92,7 +93,8 @@ public async Task Index(AdminIndexOptions options, PagerParameter if (!string.IsNullOrWhiteSpace(options.Search)) { - items = items.Where(entry => entry.Title != null && entry.Title.Contains(options.Search, StringComparison.OrdinalIgnoreCase) + items = items.Where(entry => + entry.Title != null && entry.Title.Contains(options.Search, StringComparison.OrdinalIgnoreCase) || (entry.Description != null && entry.Description.Contains(options.Search, StringComparison.OrdinalIgnoreCase)) ); } @@ -106,11 +108,7 @@ public async Task Index(AdminIndexOptions options, PagerParameter items = items.Where(entry => !entry.Enable); } - options.Statuses = - [ - new SelectListItem(S["Enabled"], "enabled"), - new SelectListItem(S["Disabled"], "disabled") - ]; + options.Statuses = [new SelectListItem(S["Enabled"], "enabled"), new SelectListItem(S["Disabled"], "disabled")]; var taskItems = items.ToList(); var routeData = new RouteData(); @@ -140,12 +138,8 @@ public async Task Index(AdminIndexOptions options, PagerParameter [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(BackgroundTaskIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search }, - { _optionsStatus, model.Options.Status }, - }); + public ActionResult IndexFilterPOST(BackgroundTaskIndexViewModel model) => + RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search }, { _optionsStatus, model.Options.Status }, }); public async Task Edit(string name) { diff --git a/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Permissions.cs index 6f8a7a532aa..887544849e3 100644 --- a/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageBackgroundTasks = new("ManageBackgroundTasks", "Manage background tasks"); - private readonly IEnumerable _allPermissions = - [ - ManageBackgroundTasks, - ]; + private readonly IEnumerable _allPermissions = [ManageBackgroundTasks,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Services/AlwaysHasChangedToken.cs b/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Services/AlwaysHasChangedToken.cs index 04c540f5eff..63e7ed51448 100644 --- a/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Services/AlwaysHasChangedToken.cs +++ b/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Services/AlwaysHasChangedToken.cs @@ -10,9 +10,7 @@ internal class AlwaysHasChangedToken : IChangeToken { public static AlwaysHasChangedToken Singleton { get; } = new AlwaysHasChangedToken(); - private AlwaysHasChangedToken() - { - } + private AlwaysHasChangedToken() { } public bool HasChanged => true; @@ -28,12 +26,8 @@ internal class EmptyDisposable : IDisposable { public static EmptyDisposable Instance { get; } = new EmptyDisposable(); - private EmptyDisposable() - { - } + private EmptyDisposable() { } - public void Dispose() - { - } + public void Dispose() { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/ContentPickerAdminController.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/ContentPickerAdminController.cs index 6b83767828a..2d93df63d29 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/ContentPickerAdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/ContentPickerAdminController.cs @@ -18,10 +18,7 @@ public class ContentPickerAdminController : Controller private readonly IContentDefinitionManager _contentDefinitionManager; private readonly IEnumerable _resultProviders; - public ContentPickerAdminController( - IContentDefinitionManager contentDefinitionManager, - IEnumerable resultProviders - ) + public ContentPickerAdminController(IContentDefinitionManager contentDefinitionManager, IEnumerable resultProviders) { _contentDefinitionManager = contentDefinitionManager; _resultProviders = resultProviders; @@ -35,8 +32,7 @@ public async Task SearchContentItems(string part, string field, s return BadRequest("Part and field are required parameters"); } - var partFieldDefinition = (await _contentDefinitionManager.GetPartDefinitionAsync(part))?.Fields - .FirstOrDefault(f => f.Name == field); + var partFieldDefinition = (await _contentDefinitionManager.GetPartDefinitionAsync(part))?.Fields.FirstOrDefault(f => f.Name == field); var fieldSettings = partFieldDefinition?.GetSettings(); if (fieldSettings == null) @@ -46,8 +42,7 @@ public async Task SearchContentItems(string part, string field, s var editor = partFieldDefinition.Editor() ?? "Default"; - var resultProvider = _resultProviders.FirstOrDefault(p => p.Name == editor) - ?? _resultProviders.FirstOrDefault(p => p.Name == "Default"); + var resultProvider = _resultProviders.FirstOrDefault(p => p.Name == editor) ?? _resultProviders.FirstOrDefault(p => p.Name == "Default"); if (resultProvider == null) { @@ -64,19 +59,29 @@ public async Task SearchContentItems(string part, string field, s var hasStereotype = contentType.TryGetStereotype(out var stereotype); return hasStereotype && fieldSettings.DisplayedStereotypes.Contains(stereotype); - }).Select(contentType => contentType.Name) + }) + .Select(contentType => contentType.Name) .ToArray(); } - var results = await resultProvider.Search(new ContentPickerSearchContext - { - Query = query, - DisplayAllContentTypes = fieldSettings.DisplayAllContentTypes, - ContentTypes = contentTypes, - PartFieldDefinition = partFieldDefinition, - }); + var results = await resultProvider.Search( + new ContentPickerSearchContext + { + Query = query, + DisplayAllContentTypes = fieldSettings.DisplayAllContentTypes, + ContentTypes = contentTypes, + PartFieldDefinition = partFieldDefinition, + } + ); - return new ObjectResult(results.Select(r => new VueMultiselectItemViewModel() { Id = r.ContentItemId, DisplayText = r.DisplayText, HasPublished = r.HasPublished })); + return new ObjectResult( + results.Select(r => new VueMultiselectItemViewModel() + { + Id = r.ContentItemId, + DisplayText = r.DisplayText, + HasPublished = r.HasPublished + }) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/LocalizationSetContentPickerAdminController.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/LocalizationSetContentPickerAdminController.cs index 8e0f2101a2b..951e82c5866 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/LocalizationSetContentPickerAdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/LocalizationSetContentPickerAdminController.cs @@ -35,7 +35,8 @@ public LocalizationSetContentPickerAdminController( IContentManager contentManager, ISession session, IAuthorizationService authorizationService, - IHttpContextAccessor httpContextAccessor) + IHttpContextAccessor httpContextAccessor + ) { _contentDefinitionManager = contentDefinitionManager; _contentLocalizationManager = contentLocalizationManager; @@ -54,8 +55,7 @@ public async Task SearchLocalizationSets(string part, string fiel return BadRequest("Part and field are required parameters"); } - var partFieldDefinition = (await _contentDefinitionManager.GetPartDefinitionAsync(part))?.Fields - .FirstOrDefault(f => f.Name == field); + var partFieldDefinition = (await _contentDefinitionManager.GetPartDefinitionAsync(part))?.Fields.FirstOrDefault(f => f.Name == field); var fieldSettings = partFieldDefinition?.GetSettings(); if (fieldSettings == null) @@ -63,8 +63,7 @@ public async Task SearchLocalizationSets(string part, string fiel return BadRequest("Unable to find field definition"); } - var dbQuery = _session.Query() - .With(x => x.ContentType.IsIn(fieldSettings.DisplayedContentTypes) && x.Latest); + var dbQuery = _session.Query().With(x => x.ContentType.IsIn(fieldSettings.DisplayedContentTypes) && x.Latest); if (!string.IsNullOrEmpty(query)) { @@ -82,12 +81,14 @@ public async Task SearchLocalizationSets(string part, string fiel { if (await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, CommonPermissions.ViewContent, contentItem)) { - results.Add(new VueMultiselectItemViewModel - { - Id = contentItem.Key, // localization set - DisplayText = contentItem.Value.ToString(), - HasPublished = await _contentManager.HasPublishedVersionAsync(contentItem.Value) - }); + results.Add( + new VueMultiselectItemViewModel + { + Id = contentItem.Key, // localization set + DisplayText = contentItem.Value.ToString(), + HasPublished = await _contentManager.HasPublishedVersionAsync(contentItem.Value) + } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/UserPickerAdminController.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/UserPickerAdminController.cs index 855fb3ec6a4..0928a05cabe 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/UserPickerAdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/UserPickerAdminController.cs @@ -29,7 +29,7 @@ public UserPickerAdminController( IContentManager contentManager, IAuthorizationService authorizationService, IEnumerable resultProviders - ) + ) { _contentDefinitionManager = contentDefinitionManager; _contentManager = contentManager; @@ -53,8 +53,7 @@ public async Task SearchUsers(string part, string field, string c return Forbid(); } - var partFieldDefinition = (await _contentDefinitionManager.GetPartDefinitionAsync(part))?.Fields - .FirstOrDefault(f => f.Name == field); + var partFieldDefinition = (await _contentDefinitionManager.GetPartDefinitionAsync(part))?.Fields.FirstOrDefault(f => f.Name == field); var fieldSettings = partFieldDefinition?.GetSettings(); if (fieldSettings == null) @@ -64,23 +63,31 @@ public async Task SearchUsers(string part, string field, string c var editor = partFieldDefinition.Editor() ?? "Default"; - var resultProvider = _resultProviders.FirstOrDefault(p => p.Name == editor) - ?? _resultProviders.FirstOrDefault(p => p.Name == "Default"); + var resultProvider = _resultProviders.FirstOrDefault(p => p.Name == editor) ?? _resultProviders.FirstOrDefault(p => p.Name == "Default"); if (resultProvider == null) { return new ObjectResult(new List()); } - var results = await resultProvider.Search(new UserPickerSearchContext - { - Query = query, - DisplayAllUsers = fieldSettings.DisplayAllUsers, - Roles = fieldSettings.DisplayedRoles, - PartFieldDefinition = partFieldDefinition - }); + var results = await resultProvider.Search( + new UserPickerSearchContext + { + Query = query, + DisplayAllUsers = fieldSettings.DisplayAllUsers, + Roles = fieldSettings.DisplayedRoles, + PartFieldDefinition = partFieldDefinition + } + ); - return new ObjectResult(results.Select(r => new VueMultiselectUserViewModel() { Id = r.UserId, DisplayText = r.DisplayText, IsEnabled = r.IsEnabled })); + return new ObjectResult( + results.Select(r => new VueMultiselectUserViewModel() + { + Id = r.UserId, + DisplayText = r.DisplayText, + IsEnabled = r.IsEnabled + }) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/BooleanFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/BooleanFieldDisplayDriver.cs index 5cc81394153..caa837cf755 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/BooleanFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/BooleanFieldDisplayDriver.cs @@ -13,27 +13,32 @@ public class BooleanFieldDisplayDriver : ContentFieldDisplayDriver { public override IDisplayResult Display(BooleanField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(BooleanField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.Value = (context.IsNew == false) ? - field.Value : context.PartFieldDefinition.GetSettings().DefaultValue; + return Initialize( + GetEditorShapeType(context), + model => + { + model.Value = (context.IsNew == false) ? field.Value : context.PartFieldDefinition.GetSettings().DefaultValue; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(BooleanField field, IUpdateModel updater, UpdateFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/ContentPickerFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/ContentPickerFieldDisplayDriver.cs index fa03ef66b58..2db3c6796c5 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/ContentPickerFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/ContentPickerFieldDisplayDriver.cs @@ -26,10 +26,7 @@ public class ContentPickerFieldDisplayDriver : ContentFieldDisplayDriver localizer, - ILiquidTemplateManager templateManager) + public ContentPickerFieldDisplayDriver(IContentManager contentManager, IStringLocalizer localizer, ILiquidTemplateManager templateManager) { _contentManager = contentManager; S = localizer; @@ -38,52 +35,64 @@ public ContentPickerFieldDisplayDriver( public override IDisplayResult Display(ContentPickerField field, BuildFieldDisplayContext fieldDisplayContext) { - return Initialize(GetDisplayShapeType(fieldDisplayContext), model => - { - model.Field = field; - model.Part = fieldDisplayContext.ContentPart; - model.PartFieldDefinition = fieldDisplayContext.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(fieldDisplayContext), + model => + { + model.Field = field; + model.Part = fieldDisplayContext.ContentPart; + model.PartFieldDefinition = fieldDisplayContext.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(ContentPickerField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), async model => - { - model.ContentItemIds = string.Join(",", field.ContentItemIds); + return Initialize( + GetEditorShapeType(context), + async model => + { + model.ContentItemIds = string.Join(",", field.ContentItemIds); - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; - model.SelectedItems = []; - var settings = context.PartFieldDefinition.GetSettings(); + model.SelectedItems = []; + var settings = context.PartFieldDefinition.GetSettings(); - foreach (var contentItemId in field.ContentItemIds) - { - var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest); - - if (contentItem == null) + foreach (var contentItemId in field.ContentItemIds) { - continue; - } + var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest); - var cultureAspect = await _contentManager.PopulateAspectAsync(contentItem, new CultureAspect()); + if (contentItem == null) + { + continue; + } - using (CultureScope.Create(cultureAspect.Culture)) - { - model.SelectedItems.Add(new VueMultiselectItemViewModel + var cultureAspect = await _contentManager.PopulateAspectAsync(contentItem, new CultureAspect()); + + using (CultureScope.Create(cultureAspect.Culture)) { - Id = contentItemId, - DisplayText = await _templateManager.RenderStringAsync(settings.TitlePattern, NullEncoder.Default, contentItem, - new Dictionary() { [nameof(ContentItem)] = new ObjectValue(contentItem) }), - HasPublished = await _contentManager.HasPublishedVersionAsync(contentItem) - }); + model.SelectedItems.Add( + new VueMultiselectItemViewModel + { + Id = contentItemId, + DisplayText = await _templateManager.RenderStringAsync( + settings.TitlePattern, + NullEncoder.Default, + contentItem, + new Dictionary() { [nameof(ContentItem)] = new ObjectValue(contentItem) } + ), + HasPublished = await _contentManager.HasPublishedVersionAsync(contentItem) + } + ); + } } } - }); + ); } public override async Task UpdateAsync(ContentPickerField field, IUpdateModel updater, UpdateFieldEditorContext context) @@ -97,8 +106,7 @@ public override async Task UpdateAsync(ContentPickerField field, return Edit(field, context); } - field.ContentItemIds = viewModel.ContentItemIds == null - ? [] : viewModel.ContentItemIds.Split(',', StringSplitOptions.RemoveEmptyEntries); + field.ContentItemIds = viewModel.ContentItemIds == null ? [] : viewModel.ContentItemIds.Split(',', StringSplitOptions.RemoveEmptyEntries); var settings = context.PartFieldDefinition.GetSettings(); @@ -109,7 +117,11 @@ public override async Task UpdateAsync(ContentPickerField field, if (!settings.Multiple && field.ContentItemIds.Length > 1) { - updater.ModelState.AddModelError(Prefix, nameof(field.ContentItemIds), S["The {0} field cannot contain multiple items.", context.PartFieldDefinition.DisplayName()]); + updater.ModelState.AddModelError( + Prefix, + nameof(field.ContentItemIds), + S["The {0} field cannot contain multiple items.", context.PartFieldDefinition.DisplayName()] + ); } return Edit(field, context); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/DateFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/DateFieldDisplayDriver.cs index 06a9096539b..e24fd3acd54 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/DateFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/DateFieldDisplayDriver.cs @@ -23,25 +23,31 @@ public DateFieldDisplayDriver(IStringLocalizer localizer public override IDisplayResult Display(DateField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(DateField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.Value = field.Value; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + return Initialize( + GetEditorShapeType(context), + model => + { + model.Value = field.Value; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(DateField field, IUpdateModel updater, UpdateFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/DateTimeFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/DateTimeFieldDisplayDriver.cs index a9cdaae1af3..9848142ef85 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/DateTimeFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/DateTimeFieldDisplayDriver.cs @@ -12,7 +12,6 @@ using OrchardCore.Modules; using OrchardCore.Mvc.ModelBinding; - namespace OrchardCore.ContentFields.Drivers { public class DateTimeFieldDisplayDriver : ContentFieldDisplayDriver @@ -20,8 +19,7 @@ public class DateTimeFieldDisplayDriver : ContentFieldDisplayDriver localizer) + public DateTimeFieldDisplayDriver(ILocalClock localClock, IStringLocalizer localizer) { _localClock = localClock; S = localizer; @@ -29,26 +27,32 @@ public DateTimeFieldDisplayDriver(ILocalClock localClock, public override IDisplayResult Display(DateTimeField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), async model => - { - model.LocalDateTime = field.Value == null ? (DateTime?)null : (await _localClock.ConvertToLocalAsync(field.Value.Value)).DateTime; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + async model => + { + model.LocalDateTime = field.Value == null ? (DateTime?)null : (await _localClock.ConvertToLocalAsync(field.Value.Value)).DateTime; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(DateTimeField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), async model => - { - model.LocalDateTime = field.Value == null ? (DateTime?)null : (await _localClock.ConvertToLocalAsync(field.Value.Value)).DateTime; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + return Initialize( + GetEditorShapeType(context), + async model => + { + model.LocalDateTime = field.Value == null ? (DateTime?)null : (await _localClock.ConvertToLocalAsync(field.Value.Value)).DateTime; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(DateTimeField field, IUpdateModel updater, UpdateFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/HtmlFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/HtmlFieldDisplayDriver.cs index aafb66f4652..afbcb75d924 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/HtmlFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/HtmlFieldDisplayDriver.cs @@ -27,11 +27,13 @@ public class HtmlFieldDisplayDriver : ContentFieldDisplayDriver private readonly IShortcodeService _shortcodeService; protected readonly IStringLocalizer S; - public HtmlFieldDisplayDriver(ILiquidTemplateManager liquidTemplateManager, + public HtmlFieldDisplayDriver( + ILiquidTemplateManager liquidTemplateManager, HtmlEncoder htmlEncoder, IHtmlSanitizerService htmlSanitizerService, IShortcodeService shortcodeService, - IStringLocalizer localizer) + IStringLocalizer localizer + ) { _liquidTemplateManager = liquidTemplateManager; _htmlEncoder = htmlEncoder; @@ -42,41 +44,48 @@ public HtmlFieldDisplayDriver(ILiquidTemplateManager liquidTemplateManager, public override IDisplayResult Display(HtmlField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), async model => - { - model.Html = field.Html; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - - var settings = context.PartFieldDefinition.GetSettings(); - if (!settings.SanitizeHtml) - { - model.Html = await _liquidTemplateManager.RenderStringAsync(field.Html, _htmlEncoder, model, - new Dictionary() { ["ContentItem"] = new ObjectValue(field.ContentItem) }); - } - - model.Html = await _shortcodeService.ProcessAsync(model.Html, - new Context + return Initialize( + GetDisplayShapeType(context), + async model => { - ["ContentItem"] = field.ContentItem, - ["PartFieldDefinition"] = context.PartFieldDefinition - }); + model.Html = field.Html; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + var settings = context.PartFieldDefinition.GetSettings(); + if (!settings.SanitizeHtml) + { + model.Html = await _liquidTemplateManager.RenderStringAsync( + field.Html, + _htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(field.ContentItem) } + ); + } + + model.Html = await _shortcodeService.ProcessAsync( + model.Html, + new Context { ["ContentItem"] = field.ContentItem, ["PartFieldDefinition"] = context.PartFieldDefinition } + ); + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(HtmlField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.Html = field.Html; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + return Initialize( + GetEditorShapeType(context), + model => + { + model.Html = field.Html; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(HtmlField field, IUpdateModel updater, UpdateFieldEditorContext context) @@ -92,9 +101,9 @@ public override async Task UpdateAsync(HtmlField field, IUpdateM var fieldName = context.PartFieldDefinition.DisplayName(); context.Updater.ModelState.AddModelError( Prefix, - nameof(viewModel.Html), S["{0} doesn't contain a valid Liquid expression. Details: {1}", - fieldName, - string.Join(' ', errors)]); + nameof(viewModel.Html), + S["{0} doesn't contain a valid Liquid expression. Details: {1}", fieldName, string.Join(' ', errors)] + ); } else { diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LinkFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LinkFieldDisplayDriver.cs index 37dc4529e8e..9eddff8d1f8 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LinkFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LinkFieldDisplayDriver.cs @@ -30,7 +30,8 @@ public LinkFieldDisplayDriver( IActionContextAccessor actionContextAccessor, IStringLocalizer localizer, IHtmlSanitizerService htmlSanitizerService, - HtmlEncoder htmlencoder) + HtmlEncoder htmlencoder + ) { _urlHelperFactory = urlHelperFactory; _actionContextAccessor = actionContextAccessor; @@ -41,28 +42,34 @@ public LinkFieldDisplayDriver( public override IDisplayResult Display(LinkField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(LinkField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - var settings = context.PartFieldDefinition.GetSettings(); - model.Url = context.IsNew && field.Url == null ? settings.DefaultUrl : field.Url; - model.Text = context.IsNew && field.Text == null ? settings.DefaultText : field.Text; + return Initialize( + GetEditorShapeType(context), + model => + { + var settings = context.PartFieldDefinition.GetSettings(); + model.Url = context.IsNew && field.Url == null ? settings.DefaultUrl : field.Url; + model.Text = context.IsNew && field.Text == null ? settings.DefaultText : field.Text; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(LinkField field, IUpdateModel updater, UpdateFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LocalizationSetContentPickerFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LocalizationSetContentPickerFieldDisplayDriver.cs index 0a05fb9770a..d3f850fe8d1 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LocalizationSetContentPickerFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LocalizationSetContentPickerFieldDisplayDriver.cs @@ -26,7 +26,8 @@ public class LocalizationSetContentPickerFieldDisplayDriver : ContentFieldDispla public LocalizationSetContentPickerFieldDisplayDriver( IContentManager contentManager, IStringLocalizer localizer, - IContentLocalizationManager contentLocalizationManager) + IContentLocalizationManager contentLocalizationManager + ) { _contentManager = contentManager; S = localizer; @@ -35,45 +36,53 @@ public LocalizationSetContentPickerFieldDisplayDriver( public override IDisplayResult Display(LocalizationSetContentPickerField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(LocalizationSetContentPickerField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), async model => - { - model.LocalizationSets = string.Join(",", field.LocalizationSets); - - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; + return Initialize( + GetEditorShapeType(context), + async model => + { + model.LocalizationSets = string.Join(",", field.LocalizationSets); - model.SelectedItems = []; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; - foreach (var kvp in await _contentLocalizationManager.GetFirstItemIdForSetsAsync(field.LocalizationSets)) - { - var contentItem = await _contentManager.GetAsync(kvp.Value, VersionOptions.Latest); + model.SelectedItems = []; - if (contentItem == null) + foreach (var kvp in await _contentLocalizationManager.GetFirstItemIdForSetsAsync(field.LocalizationSets)) { - continue; + var contentItem = await _contentManager.GetAsync(kvp.Value, VersionOptions.Latest); + + if (contentItem == null) + { + continue; + } + + model.SelectedItems.Add( + new VueMultiselectItemViewModel + { + Id = kvp.Key, // localization set + DisplayText = contentItem.ToString(), + HasPublished = await _contentManager.HasPublishedVersionAsync(contentItem) + } + ); } - - model.SelectedItems.Add(new VueMultiselectItemViewModel - { - Id = kvp.Key, // localization set - DisplayText = contentItem.ToString(), - HasPublished = await _contentManager.HasPublishedVersionAsync(contentItem) - }); } - }); + ); } public override async Task UpdateAsync(LocalizationSetContentPickerField field, IUpdateModel updater, UpdateFieldEditorContext context) @@ -87,8 +96,7 @@ public override async Task UpdateAsync(LocalizationSetContentPic return Edit(field, context); } - field.LocalizationSets = viewModel.LocalizationSets == null - ? [] : viewModel.LocalizationSets.Split(',', StringSplitOptions.RemoveEmptyEntries); + field.LocalizationSets = viewModel.LocalizationSets == null ? [] : viewModel.LocalizationSets.Split(',', StringSplitOptions.RemoveEmptyEntries); var settings = context.PartFieldDefinition.GetSettings(); @@ -99,7 +107,11 @@ public override async Task UpdateAsync(LocalizationSetContentPic if (!settings.Multiple && field.LocalizationSets.Length > 1) { - updater.ModelState.AddModelError(Prefix, nameof(field.LocalizationSets), S["The {0} field cannot contain multiple items.", context.PartFieldDefinition.DisplayName()]); + updater.ModelState.AddModelError( + Prefix, + nameof(field.LocalizationSets), + S["The {0} field cannot contain multiple items.", context.PartFieldDefinition.DisplayName()] + ); } return Edit(field, context); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/MultiTextFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/MultiTextFieldDisplayDriver.cs index 913a73f30f1..62db4b2d923 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/MultiTextFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/MultiTextFieldDisplayDriver.cs @@ -24,36 +24,42 @@ public MultiTextFieldDisplayDriver(IStringLocalizer public override IDisplayResult Display(MultiTextField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - var settings = context.PartFieldDefinition.GetSettings(); + return Initialize( + GetDisplayShapeType(context), + model => + { + var settings = context.PartFieldDefinition.GetSettings(); - model.Values = settings.Options.Where(o => field.Values?.Contains(o.Value) == true).Select(o => o.Value).ToArray(); - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + model.Values = settings.Options.Where(o => field.Values?.Contains(o.Value) == true).Select(o => o.Value).ToArray(); + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(MultiTextField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - if (context.IsNew) - { - var settings = context.PartFieldDefinition.GetSettings(); - model.Values = settings.Options.Where(o => o.Default).Select(o => o.Value).ToArray(); - } - else + return Initialize( + GetEditorShapeType(context), + model => { - model.Values = field.Values; + if (context.IsNew) + { + var settings = context.PartFieldDefinition.GetSettings(); + model.Values = settings.Options.Where(o => o.Default).Select(o => o.Value).ToArray(); + } + else + { + model.Values = field.Values; + } + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; } - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + ); } public override async Task UpdateAsync(MultiTextField field, IUpdateModel updater, UpdateFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/NumericFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/NumericFieldDisplayDriver.cs index 61f63cbef0a..9627a034e1a 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/NumericFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/NumericFieldDisplayDriver.cs @@ -25,42 +25,48 @@ public NumericFieldDisplayDriver(IStringLocalizer loc public override IDisplayResult Display(NumericField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(NumericField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - var settings = context.PartFieldDefinition.GetSettings(); + return Initialize( + GetEditorShapeType(context), + model => + { + var settings = context.PartFieldDefinition.GetSettings(); - // The default value of a field is intended for the editor when a new content item - // is created (not for APIs). Since we may want to render the editor of a content - // item that was created by code, we only set the default value in the - // of the field if it doesn't already have a value. + // The default value of a field is intended for the editor when a new content item + // is created (not for APIs). Since we may want to render the editor of a content + // item that was created by code, we only set the default value in the + // of the field if it doesn't already have a value. - if (field.Value.HasValue) - { - model.Value = Convert.ToString(field.Value, CultureInfo.CurrentUICulture); - } - else if (context.IsNew) - { - // The content item is new and the field is not initialized, we can - // use the default value from the settings in the editor. - model.Value = settings.DefaultValue; - } + if (field.Value.HasValue) + { + model.Value = Convert.ToString(field.Value, CultureInfo.CurrentUICulture); + } + else if (context.IsNew) + { + // The content item is new and the field is not initialized, we can + // use the default value from the settings in the editor. + model.Value = settings.DefaultValue; + } - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(NumericField field, IUpdateModel updater, UpdateFieldEditorContext context) @@ -107,7 +113,11 @@ public override async Task UpdateAsync(NumericField field, IUpda } else { - updater.ModelState.AddModelError(Prefix, nameof(field.Value), S["Invalid number of digits for {0}, max allowed: {1}.", context.PartFieldDefinition.DisplayName(), settings.Scale]); + updater.ModelState.AddModelError( + Prefix, + nameof(field.Value), + S["Invalid number of digits for {0}, max allowed: {1}.", context.PartFieldDefinition.DisplayName(), settings.Scale] + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/TextFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/TextFieldDisplayDriver.cs index cf8518c535d..8edb7f125b8 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/TextFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/TextFieldDisplayDriver.cs @@ -23,26 +23,32 @@ public TextFieldDisplayDriver(IStringLocalizer localizer public override IDisplayResult Display(TextField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(TextField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - var settings = context.PartFieldDefinition.GetSettings(); - model.Text = context.IsNew && field.Text == null ? settings.DefaultValue : field.Text; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + return Initialize( + GetEditorShapeType(context), + model => + { + var settings = context.PartFieldDefinition.GetSettings(); + model.Text = context.IsNew && field.Text == null ? settings.DefaultValue : field.Text; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(TextField field, IUpdateModel updater, UpdateFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/TimeFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/TimeFieldDisplayDriver.cs index 21029aa74bc..05e1af39231 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/TimeFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/TimeFieldDisplayDriver.cs @@ -23,25 +23,31 @@ public TimeFieldDisplayDriver(IStringLocalizer localizer public override IDisplayResult Display(TimeField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(TimeField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.Value = field.Value; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + return Initialize( + GetEditorShapeType(context), + model => + { + model.Value = field.Value; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(TimeField field, IUpdateModel updater, UpdateFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/UserPickerFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/UserPickerFieldDisplayDriver.cs index 47a506eef35..21833f8456b 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/UserPickerFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/UserPickerFieldDisplayDriver.cs @@ -23,9 +23,7 @@ public class UserPickerFieldDisplayDriver : ContentFieldDisplayDriver stringLocalizer) + public UserPickerFieldDisplayDriver(ISession session, IStringLocalizer stringLocalizer) { _session = session; S = stringLocalizer; @@ -33,43 +31,52 @@ public UserPickerFieldDisplayDriver( public override IDisplayResult Display(UserPickerField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(UserPickerField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), async model => - { - model.UserIds = string.Join(",", field.UserIds); - - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - model.TypePartDefinition = context.TypePartDefinition; - - if (field.UserIds.Length > 0) + return Initialize( + GetEditorShapeType(context), + async model => { - var users = (await _session.Query().Where(x => x.UserId.IsIn(field.UserIds)).ListAsync()) - .OrderBy(o => Array.FindIndex(field.UserIds, x => string.Equals(o.UserId, x, StringComparison.OrdinalIgnoreCase))); + model.UserIds = string.Join(",", field.UserIds); - foreach (var user in users) + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + model.TypePartDefinition = context.TypePartDefinition; + + if (field.UserIds.Length > 0) { - model.SelectedUsers.Add(new VueMultiselectUserViewModel + var users = (await _session.Query().Where(x => x.UserId.IsIn(field.UserIds)).ListAsync()).OrderBy(o => + Array.FindIndex(field.UserIds, x => string.Equals(o.UserId, x, StringComparison.OrdinalIgnoreCase)) + ); + + foreach (var user in users) { - Id = user.UserId, - DisplayText = user.UserName, - IsEnabled = user.IsEnabled - }); + model.SelectedUsers.Add( + new VueMultiselectUserViewModel + { + Id = user.UserId, + DisplayText = user.UserName, + IsEnabled = user.IsEnabled + } + ); + } } } - }); + ); } public override async Task UpdateAsync(UserPickerField field, IUpdateModel updater, UpdateFieldEditorContext context) @@ -78,8 +85,7 @@ public override async Task UpdateAsync(UserPickerField field, IU if (await updater.TryUpdateModelAsync(viewModel, Prefix, f => f.UserIds)) { - field.UserIds = viewModel.UserIds == null - ? [] : viewModel.UserIds.Split(',', StringSplitOptions.RemoveEmptyEntries); + field.UserIds = viewModel.UserIds == null ? [] : viewModel.UserIds.Split(',', StringSplitOptions.RemoveEmptyEntries); var settings = context.PartFieldDefinition.GetSettings(); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/UserPickerFieldUserNamesDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/UserPickerFieldUserNamesDisplayDriver.cs index 04736d637ac..e88b8f1349a 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/UserPickerFieldUserNamesDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/UserPickerFieldUserNamesDisplayDriver.cs @@ -10,14 +10,17 @@ public class UserPickerFieldUserNamesDisplayDriver : ContentFieldDisplayDriver(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/YoutubeFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/YoutubeFieldDisplayDriver.cs index 83bbe74cee3..2c2a6dbdb5d 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/YoutubeFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/YoutubeFieldDisplayDriver.cs @@ -25,26 +25,32 @@ public YoutubeFieldDisplayDriver(IStringLocalizer loc public override IDisplayResult Display(YoutubeField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(YoutubeField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.RawAddress = field.RawAddress; - model.EmbeddedAddress = field.EmbeddedAddress; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + return Initialize( + GetEditorShapeType(context), + model => + { + model.RawAddress = field.RawAddress; + model.EmbeddedAddress = field.EmbeddedAddress; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(YoutubeField field, IUpdateModel updater, UpdateFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Extensions/ContentPartFieldDefinitionExtensions.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Extensions/ContentPartFieldDefinitionExtensions.cs index cd8c62e25c0..80522610b29 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Extensions/ContentPartFieldDefinitionExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Extensions/ContentPartFieldDefinitionExtensions.cs @@ -8,13 +8,10 @@ public static class ContentPartFieldDefinitionExtensions /// /// Returns the value of the defined content field from the . /// - public static TField GetContentField( - this ContentPartFieldDefinition fieldDefinition, - ContentItem contentItem) + public static TField GetContentField(this ContentPartFieldDefinition fieldDefinition, ContentItem contentItem) where TField : ContentField { - if (((JsonObject)contentItem.Content)[fieldDefinition.PartDefinition.Name] is not JsonObject jPart || - jPart[fieldDefinition.Name] is not JsonObject jField) + if (((JsonObject)contentItem.Content)[fieldDefinition.PartDefinition.Name] is not JsonObject jPart || jPart[fieldDefinition.Name] is not JsonObject jField) { return null; } @@ -28,7 +25,8 @@ public static TField GetContentField( /// public static IEnumerable<(ContentPartFieldDefinition Definition, TField Field)> GetContentFields( this IEnumerable fieldDefinitions, - ContentItem contentItem) + ContentItem contentItem + ) where TField : ContentField { foreach (var fieldDefinition in fieldDefinitions) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ContentFieldsProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ContentFieldsProvider.cs index 6e3238a6e04..0ad71017448 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ContentFieldsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ContentFieldsProvider.cs @@ -12,79 +12,80 @@ namespace OrchardCore.ContentFields.GraphQL.Fields { public class ContentFieldsProvider : IContentFieldProvider { - private static readonly Dictionary _contentFieldTypeMappings = new() - { + private static readonly Dictionary _contentFieldTypeMappings = + new() { - nameof(BooleanField), - new FieldTypeDescriptor { - Description = "Boolean field", - FieldType = typeof(BooleanGraphType), - UnderlyingType = typeof(BooleanField), - FieldAccessor = field => field.Content.Value, - } - }, - { - nameof(DateField), - new FieldTypeDescriptor + nameof(BooleanField), + new FieldTypeDescriptor + { + Description = "Boolean field", + FieldType = typeof(BooleanGraphType), + UnderlyingType = typeof(BooleanField), + FieldAccessor = field => field.Content.Value, + } + }, { - Description = "Date field", - FieldType = typeof(DateGraphType), - UnderlyingType = typeof(DateField), - FieldAccessor = field => field.Content.Value, - } - }, - { - nameof(DateTimeField), - new FieldTypeDescriptor + nameof(DateField), + new FieldTypeDescriptor + { + Description = "Date field", + FieldType = typeof(DateGraphType), + UnderlyingType = typeof(DateField), + FieldAccessor = field => field.Content.Value, + } + }, { - Description = "Date & time field", - FieldType = typeof(DateTimeGraphType), - UnderlyingType = typeof(DateTimeField), - FieldAccessor = field => field.Content.Value, - } - }, - { - nameof(NumericField), - new FieldTypeDescriptor + nameof(DateTimeField), + new FieldTypeDescriptor + { + Description = "Date & time field", + FieldType = typeof(DateTimeGraphType), + UnderlyingType = typeof(DateTimeField), + FieldAccessor = field => field.Content.Value, + } + }, { - Description = "Numeric field", - FieldType = typeof(DecimalGraphType), - UnderlyingType = typeof(NumericField), - FieldAccessor = field => field.Content.Value, - } - }, - { - nameof(TextField), - new FieldTypeDescriptor + nameof(NumericField), + new FieldTypeDescriptor + { + Description = "Numeric field", + FieldType = typeof(DecimalGraphType), + UnderlyingType = typeof(NumericField), + FieldAccessor = field => field.Content.Value, + } + }, { - Description = "Text field", - FieldType = typeof(StringGraphType), - UnderlyingType = typeof(TextField), - FieldAccessor = field => field.Content.Text, - } - }, - { - nameof(TimeField), - new FieldTypeDescriptor + nameof(TextField), + new FieldTypeDescriptor + { + Description = "Text field", + FieldType = typeof(StringGraphType), + UnderlyingType = typeof(TextField), + FieldAccessor = field => field.Content.Text, + } + }, { - Description = "Time field", - FieldType = typeof(TimeSpanGraphType), - UnderlyingType = typeof(TimeField), - FieldAccessor = field => field.Content.Value, - } - }, - { - nameof(MultiTextField), - new FieldTypeDescriptor + nameof(TimeField), + new FieldTypeDescriptor + { + Description = "Time field", + FieldType = typeof(TimeSpanGraphType), + UnderlyingType = typeof(TimeField), + FieldAccessor = field => field.Content.Value, + } + }, { - Description = "Multi text field", - FieldType = typeof(ListGraphType), - UnderlyingType = typeof(MultiTextField), - FieldAccessor = field => field.Content.Values, + nameof(MultiTextField), + new FieldTypeDescriptor + { + Description = "Multi text field", + FieldType = typeof(ListGraphType), + UnderlyingType = typeof(MultiTextField), + FieldAccessor = field => field.Content.Values, + } } - } - }; + }; public FieldType GetField(ContentPartFieldDefinition field) { diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ObjectGraphTypeFieldProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ObjectGraphTypeFieldProvider.cs index 7bcc4f00dda..7f4dbcb31cc 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ObjectGraphTypeFieldProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ObjectGraphTypeFieldProvider.cs @@ -24,10 +24,10 @@ public ObjectGraphTypeFieldProvider(IHttpContextAccessor httpContextAccessor) public FieldType GetField(ContentPartFieldDefinition field) { var serviceProvider = _httpContextAccessor.HttpContext.RequestServices; - var queryGraphType = _partObjectGraphTypes.GetOrAdd(field.FieldDefinition.Name, - partName => serviceProvider.GetService>()? - .FirstOrDefault(x => x.GetType().BaseType.GetGenericArguments().First().Name == partName) - ); + var queryGraphType = _partObjectGraphTypes.GetOrAdd( + field.FieldDefinition.Name, + partName => serviceProvider.GetService>()?.FirstOrDefault(x => x.GetType().BaseType.GetGenericArguments().First().Name == partName) + ); if (queryGraphType != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Types/HtmlFieldQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Types/HtmlFieldQueryObjectType.cs index a0146cdf6c0..fb3965bf2cc 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Types/HtmlFieldQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Types/HtmlFieldQueryObjectType.cs @@ -27,9 +27,7 @@ public HtmlFieldQueryObjectType(IStringLocalizer S) Name = nameof(HtmlField); Description = S["Content stored as HTML."]; - Field("html") - .Description(S["the HTML content"]) - .ResolveLockedAsync(RenderHtml); + Field("html").Description(S["the HTML content"]).ResolveLockedAsync(RenderHtml); } private static async ValueTask RenderHtml(IResolveFieldContext ctx) @@ -63,16 +61,15 @@ private static async ValueTask RenderHtml(IResolveFieldContext(); var htmlEncoder = serviceProvider.GetService(); - html = await liquidTemplateManager.RenderStringAsync(html, htmlEncoder, model, - new Dictionary() { ["ContentItem"] = new ObjectValue(ctx.Source.ContentItem) }); + html = await liquidTemplateManager.RenderStringAsync( + html, + htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(ctx.Source.ContentItem) } + ); } - return await shortcodeService.ProcessAsync(html, - new Context - { - ["ContentItem"] = ctx.Source.ContentItem, - ["PartFieldDefinition"] = contentPartFieldDefinition - }); + return await shortcodeService.ProcessAsync(html, new Context { ["ContentItem"] = ctx.Source.ContentItem, ["PartFieldDefinition"] = contentPartFieldDefinition }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Types/TimeSpanGraphType.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Types/TimeSpanGraphType.cs index a528e3fd9a1..af01ee95ef9 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Types/TimeSpanGraphType.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Types/TimeSpanGraphType.cs @@ -21,9 +21,7 @@ public override object Serialize(object value) public override object ParseValue(object value) { var timespan = value?.ToString().StripQuotes(); - return string.IsNullOrWhiteSpace(timespan) - ? null - : (TimeSpan?)TimeSpan.Parse(timespan, CultureInfo.CurrentCulture); + return string.IsNullOrWhiteSpace(timespan) ? null : (TimeSpan?)TimeSpan.Parse(timespan, CultureInfo.CurrentCulture); } public override object ParseLiteral(GraphQLValue value) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Handlers/ContentPickerFieldHandler.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Handlers/ContentPickerFieldHandler.cs index a52133c4a5f..9c2438be655 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Handlers/ContentPickerFieldHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Handlers/ContentPickerFieldHandler.cs @@ -33,4 +33,3 @@ public override Task ValidatingAsync(ValidateContentFieldContext context, Conten return Task.CompletedTask; } } - diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Handlers/LinkFieldHandler.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Handlers/LinkFieldHandler.cs index 2fca7f884e4..816ab439368 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Handlers/LinkFieldHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Handlers/LinkFieldHandler.cs @@ -25,7 +25,8 @@ public LinkFieldHandler( IActionContextAccessor actionContextAccessor, IStringLocalizer localizer, IHtmlSanitizerService htmlSanitizerService, - HtmlEncoder htmlencoder) + HtmlEncoder htmlencoder + ) { _urlHelperFactory = urlHelperFactory; _actionContextAccessor = actionContextAccessor; diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/BooleanFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/BooleanFieldIndexProvider.cs index f5fac542076..44e54bec44f 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/BooleanFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/BooleanFieldIndexProvider.cs @@ -28,7 +28,8 @@ public BooleanFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -69,18 +70,17 @@ public override void Describe(DescribeContext context) return fieldDefinitions .GetContentFields(contentItem) - .Select(pair => - new BooleanFieldIndex - { - Latest = contentItem.Latest, - Published = contentItem.Published, - ContentItemId = contentItem.ContentItemId, - ContentItemVersionId = contentItem.ContentItemVersionId, - ContentType = contentItem.ContentType, - ContentPart = pair.Definition.PartDefinition.Name, - ContentField = pair.Definition.Name, - Boolean = pair.Field.Value, - }); + .Select(pair => new BooleanFieldIndex + { + Latest = contentItem.Latest, + Published = contentItem.Published, + ContentItemId = contentItem.ContentItemId, + ContentItemVersionId = contentItem.ContentItemVersionId, + ContentType = contentItem.ContentType, + ContentPart = pair.Definition.PartDefinition.Name, + ContentField = pair.Definition.Name, + Boolean = pair.Field.Value, + }); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/ContentFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/ContentFieldIndexProvider.cs index 8c7f0a3bf60..66b5ee9e289 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/ContentFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/ContentFieldIndexProvider.cs @@ -15,7 +15,5 @@ public abstract class ContentFieldIndex : MapIndex public bool Latest { get; set; } } - public abstract class ContentFieldIndexProvider : IndexProvider, IScopedIndexProvider - { - } + public abstract class ContentFieldIndexProvider : IndexProvider, IScopedIndexProvider { } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/ContentPickerFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/ContentPickerFieldIndexProvider.cs index 24234bb5379..bab78185799 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/ContentPickerFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/ContentPickerFieldIndexProvider.cs @@ -28,7 +28,8 @@ public ContentPickerFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -70,20 +71,18 @@ public override void Describe(DescribeContext context) // Get all field values return fieldDefinitions .GetContentFields(contentItem) - .SelectMany(pair => - pair.Field.ContentItemIds.Select(id => (pair.Definition, ContentItemId: id))) - .Select(pair => - new ContentPickerFieldIndex - { - Latest = contentItem.Latest, - Published = contentItem.Published, - ContentItemId = contentItem.ContentItemId, - ContentItemVersionId = contentItem.ContentItemVersionId, - ContentType = contentItem.ContentType, - ContentPart = pair.Definition.PartDefinition.Name, - ContentField = pair.Definition.Name, - SelectedContentItemId = pair.ContentItemId, - }); + .SelectMany(pair => pair.Field.ContentItemIds.Select(id => (pair.Definition, ContentItemId: id))) + .Select(pair => new ContentPickerFieldIndex + { + Latest = contentItem.Latest, + Published = contentItem.Published, + ContentItemId = contentItem.ContentItemId, + ContentItemVersionId = contentItem.ContentItemVersionId, + ContentType = contentItem.ContentType, + ContentPart = pair.Definition.PartDefinition.Name, + ContentField = pair.Definition.Name, + SelectedContentItemId = pair.ContentItemId, + }); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/DateFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/DateFieldIndexProvider.cs index 202c01cca17..1be9d3dcd23 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/DateFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/DateFieldIndexProvider.cs @@ -28,7 +28,8 @@ public DateFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -56,9 +57,7 @@ public override void Describe(DescribeContext context) return null; } - var fieldDefinitions = contentTypeDefinition - .Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(DateField))) - .ToArray(); + var fieldDefinitions = contentTypeDefinition.Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(DateField))).ToArray(); // This type doesn't have any DateField, ignore it if (fieldDefinitions.Length == 0) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/DateTimeFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/DateTimeFieldIndexProvider.cs index b3e2e64298c..f0d532fb69a 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/DateTimeFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/DateTimeFieldIndexProvider.cs @@ -28,7 +28,8 @@ public DateTimeFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -69,18 +70,17 @@ public override void Describe(DescribeContext context) return fieldDefinitions .GetContentFields(contentItem) - .Select(pair => - new DateTimeFieldIndex - { - Latest = contentItem.Latest, - Published = contentItem.Published, - ContentItemId = contentItem.ContentItemId, - ContentItemVersionId = contentItem.ContentItemVersionId, - ContentType = contentItem.ContentType, - ContentPart = pair.Definition.PartDefinition.Name, - ContentField = pair.Definition.Name, - DateTime = pair.Field.Value, - }); + .Select(pair => new DateTimeFieldIndex + { + Latest = contentItem.Latest, + Published = contentItem.Published, + ContentItemId = contentItem.ContentItemId, + ContentItemVersionId = contentItem.ContentItemVersionId, + ContentType = contentItem.ContentType, + ContentPart = pair.Definition.PartDefinition.Name, + ContentField = pair.Definition.Name, + DateTime = pair.Field.Value, + }); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/HtmlFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/HtmlFieldIndexProvider.cs index 1723484b605..ae1c0a13fb5 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/HtmlFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/HtmlFieldIndexProvider.cs @@ -28,7 +28,8 @@ public HtmlFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -56,9 +57,7 @@ public override void Describe(DescribeContext context) return null; } - var fieldDefinitions = contentTypeDefinition - .Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(HtmlField))) - .ToArray(); + var fieldDefinitions = contentTypeDefinition.Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(HtmlField))).ToArray(); // This type doesn't have any HtmlField, ignore it if (fieldDefinitions.Length == 0) @@ -69,18 +68,17 @@ public override void Describe(DescribeContext context) return fieldDefinitions .GetContentFields(contentItem) - .Select(pair => - new HtmlFieldIndex - { - Latest = contentItem.Latest, - Published = contentItem.Published, - ContentItemId = contentItem.ContentItemId, - ContentItemVersionId = contentItem.ContentItemVersionId, - ContentType = contentItem.ContentType, - ContentPart = pair.Definition.PartDefinition.Name, - ContentField = pair.Definition.Name, - Html = pair.Field.Html, - }); + .Select(pair => new HtmlFieldIndex + { + Latest = contentItem.Latest, + Published = contentItem.Published, + ContentItemId = contentItem.ContentItemId, + ContentItemVersionId = contentItem.ContentItemVersionId, + ContentType = contentItem.ContentType, + ContentPart = pair.Definition.PartDefinition.Name, + ContentField = pair.Definition.Name, + Html = pair.Field.Html, + }); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/LinkFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/LinkFieldIndexProvider.cs index 6dd04f73036..c95f6a5f990 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/LinkFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/LinkFieldIndexProvider.cs @@ -37,7 +37,8 @@ public LinkFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -70,9 +71,7 @@ public override void Describe(DescribeContext context) return null; } - var fieldDefinitions = contentTypeDefinition - .Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(LinkField))) - .ToArray(); + var fieldDefinitions = contentTypeDefinition.Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(LinkField))).ToArray(); // This type doesn't have any LinkField, ignore it if (fieldDefinitions.Length == 0) @@ -83,21 +82,20 @@ public override void Describe(DescribeContext context) return fieldDefinitions .GetContentFields(contentItem) - .Select(pair => - new LinkFieldIndex - { - Latest = contentItem.Latest, - Published = contentItem.Published, - ContentItemId = contentItem.ContentItemId, - ContentItemVersionId = contentItem.ContentItemVersionId, - ContentType = contentItem.ContentType, - ContentPart = pair.Definition.PartDefinition.Name, - ContentField = pair.Definition.Name, - Url = pair.Field.Url?[..Math.Min(pair.Field.Url.Length, LinkFieldIndex.MaxUrlSize)], - BigUrl = pair.Field.Url, - Text = pair.Field.Text?[..Math.Min(pair.Field.Text.Length, LinkFieldIndex.MaxTextSize)], - BigText = pair.Field.Text, - }); + .Select(pair => new LinkFieldIndex + { + Latest = contentItem.Latest, + Published = contentItem.Published, + ContentItemId = contentItem.ContentItemId, + ContentItemVersionId = contentItem.ContentItemVersionId, + ContentType = contentItem.ContentType, + ContentPart = pair.Definition.PartDefinition.Name, + ContentField = pair.Definition.Name, + Url = pair.Field.Url?[..Math.Min(pair.Field.Url.Length, LinkFieldIndex.MaxUrlSize)], + BigUrl = pair.Field.Url, + Text = pair.Field.Text?[..Math.Min(pair.Field.Text.Length, LinkFieldIndex.MaxTextSize)], + BigText = pair.Field.Text, + }); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/Migrations.cs index a06d99c46b8..30a8201e8f8 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/Migrations.cs @@ -12,6 +12,7 @@ namespace OrchardCore.ContentFields.Indexing.SQL public class Migrations : DataMigration { private readonly ILogger _logger; + public Migrations(ILogger logger) { _logger = logger; @@ -22,416 +23,300 @@ public async Task CreateAsync() // NOTE: The Text Length has been decreased from 4000 characters to 768. // For existing SQL databases update the TextFieldIndex tables Text column length manually. // INFO: The Text Length is now of 766 chars, but this is only used on a new installation. - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("Text", column => column.Nullable().WithLength(TextFieldIndex.MaxTextSize)) - .Column("BigText", column => column.Nullable().Unlimited()) - ); - - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TextFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("Text", column => column.Nullable().WithLength(TextFieldIndex.MaxTextSize)) + .Column("BigText", column => column.Nullable().Unlimited()) + ); + + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TextFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TextFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TextFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + Text (764) + Published and Latest (1) = 767 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TextFieldIndex_DocumentId_Text", - "DocumentId", - "Text(764)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TextFieldIndex_DocumentId_Text", "DocumentId", "Text(764)", "Published", "Latest") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("Boolean", column => column.Nullable()) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("Boolean", column => column.Nullable()) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_BooleanFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_BooleanFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Boolean, Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_BooleanFieldIndex_DocumentId_ContentType", + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex( + "IDX_BooleanFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Boolean", "Published", - "Latest") + "Latest" + ) ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("Numeric", column => column.Nullable()) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("Numeric", column => column.Nullable()) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_NumericFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_NumericFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_NumericFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_NumericFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_NumericFieldIndex_DocumentId_Numeric", - "DocumentId", - "Numeric", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_NumericFieldIndex_DocumentId_Numeric", "DocumentId", "Numeric", "Published", "Latest") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("DateTime", column => column.Nullable()) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("DateTime", column => column.Nullable()) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateTimeFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateTimeFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateTimeFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateTimeFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateTimeFieldIndex_DocumentId_DateTime", - "DocumentId", - "DateTime", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateTimeFieldIndex_DocumentId_DateTime", "DocumentId", "DateTime", "Published", "Latest") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("Date", column => column.Nullable()) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("Date", column => column.Nullable()) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateFieldIndex_DocumentId_Date", - "DocumentId", - "ContentType", - "Date", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateFieldIndex_DocumentId_Date", "DocumentId", "ContentType", "Date", "Published", "Latest") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("SelectedContentItemId", column => column.WithLength(26)) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("SelectedContentItemId", column => column.WithLength(26)) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentPickerFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentPickerFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentPickerFieldIndex_DocumentId_ContentType", + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex( + "IDX_ContentPickerFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", - "Latest") + "Latest" + ) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentPickerField_DocumentId_SelectedItemId", - "DocumentId", - "SelectedContentItemId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentPickerField_DocumentId_SelectedItemId", "DocumentId", "SelectedContentItemId", "Published", "Latest") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("Time", column => column.Nullable()) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("Time", column => column.Nullable()) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TimeFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TimeFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TimeFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TimeFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TimeFieldIndex_DocumentId_Time", - "DocumentId", - "Time", - "Published", - "Latest") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_TimeFieldIndex_DocumentId_Time", "DocumentId", "Time", "Published", "Latest")); // NOTE: The Url and Text Length has been decreased from 4000 characters to 768. // For existing SQL databases update the LinkFieldIndex tables Url and Text column length manually. // The BigText and BigUrl columns are new additions so will not be populated until the content item is republished. // INFO: The Url and Text Length is now of 766 chars, but this is only used on a new installation. - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("Url", column => column.Nullable().WithLength(LinkFieldIndex.MaxUrlSize)) - .Column("BigUrl", column => column.Nullable().Unlimited()) - .Column("Text", column => column.Nullable().WithLength(LinkFieldIndex.MaxTextSize)) - .Column("BigText", column => column.Nullable().Unlimited()) - ); - - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LinkFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("Url", column => column.Nullable().WithLength(LinkFieldIndex.MaxUrlSize)) + .Column("BigUrl", column => column.Nullable().Unlimited()) + .Column("Text", column => column.Nullable().WithLength(LinkFieldIndex.MaxTextSize)) + .Column("BigText", column => column.Nullable().Unlimited()) ); + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_LinkFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") + ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LinkFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_LinkFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + Url (764) + Published and Latest (1) = 767 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LinkFieldIndex_DocumentId_Url", - "DocumentId", - "Url(764)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_LinkFieldIndex_DocumentId_Url", "DocumentId", "Url(764)", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + Text (764) + Published and Latest (1) = 767 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LinkFieldIndex_DocumentId_Text", - "DocumentId", - "Text(764)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_LinkFieldIndex_DocumentId_Text", "DocumentId", "Text(764)", "Published", "Latest") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("Html", column => column.Nullable().Unlimited()) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("Html", column => column.Nullable().Unlimited()) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_HtmlFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_HtmlFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_HtmlFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_HtmlFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("Value", column => column.Nullable().WithLength(MultiTextFieldIndex.MaxValueSize)) - .Column("BigValue", column => column.Nullable().Unlimited()) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("Value", column => column.Nullable().WithLength(MultiTextFieldIndex.MaxValueSize)) + .Column("BigValue", column => column.Nullable().Unlimited()) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_MultiTextFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_MultiTextFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_MultiTextFieldIndex_DocumentId_ContentType", + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex( + "IDX_MultiTextFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", - "Latest") + "Latest" + ) ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + Value (764) + Published and Latest (1) = 767 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_MultiTextFieldIndex_DocumentId_Value", - "DocumentId", - "Value(764)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_MultiTextFieldIndex_DocumentId_Value", "DocumentId", "Value(764)", "Published", "Latest") ); // Shortcut other migration steps on new content definition schemas. @@ -441,11 +326,9 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom1Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("BigUrl", column => column.Nullable().Unlimited())); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("BigUrl", column => column.Nullable().Unlimited())); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("BigText", column => column.Nullable().Unlimited())); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("BigText", column => column.Nullable().Unlimited())); return 2; } @@ -453,16 +336,17 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom2Async() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("Value", column => column.Nullable().WithLength(MultiTextFieldIndex.MaxValueSize)) - .Column("BigValue", column => column.Nullable().Unlimited()) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("Value", column => column.Nullable().WithLength(MultiTextFieldIndex.MaxValueSize)) + .Column("BigValue", column => column.Nullable().Unlimited()) ); return 3; @@ -471,295 +355,169 @@ await SchemaBuilder.CreateMapIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom3Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TextFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TextFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TextFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TextFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + Text (764) + Published and Latest (1) = 767 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TextFieldIndex_DocumentId_Text", - "DocumentId", - "Text(764)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TextFieldIndex_DocumentId_Text", "DocumentId", "Text(764)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_BooleanFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_BooleanFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Boolean, Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_BooleanFieldIndex_DocumentId_ContentType", + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex( + "IDX_BooleanFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Boolean", "Published", - "Latest") + "Latest" + ) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_NumericFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_NumericFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_NumericFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_NumericFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_NumericFieldIndex_DocumentId_Numeric", - "DocumentId", - "Numeric", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_NumericFieldIndex_DocumentId_Numeric", "DocumentId", "Numeric", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateTimeFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateTimeFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateTimeFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateTimeFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateTimeFieldIndex_DocumentId_DateTime", - "DocumentId", - "DateTime", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateTimeFieldIndex_DocumentId_DateTime", "DocumentId", "DateTime", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_DateFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_DateFieldIndex_DocumentId_Date", - "DocumentId", - "Date", - "Published", - "Latest") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_DateFieldIndex_DocumentId_Date", "DocumentId", "Date", "Published", "Latest")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentPickerFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentPickerFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentPickerFieldIndex_DocumentId_ContentType", + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex( + "IDX_ContentPickerFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", - "Latest") + "Latest" + ) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentPickerField_DocumentId_SelectedItemId", - "DocumentId", - "SelectedContentItemId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentPickerField_DocumentId_SelectedItemId", "DocumentId", "SelectedContentItemId", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TimeFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TimeFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TimeFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TimeFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TimeFieldIndex_DocumentId_Time", - "DocumentId", - "Time", - "Published", - "Latest") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_TimeFieldIndex_DocumentId_Time", "DocumentId", "Time", "Published", "Latest")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LinkFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_LinkFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LinkFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_LinkFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + Url (764) + Published and Latest (1) = 767 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LinkFieldIndex_DocumentId_Url", - "DocumentId", - "Url(764)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_LinkFieldIndex_DocumentId_Url", "DocumentId", "Url(764)", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + Text (764) + Published and Latest (1) = 767 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LinkFieldIndex_DocumentId_Text", - "DocumentId", - "Text(764)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_LinkFieldIndex_DocumentId_Text", "DocumentId", "Text(764)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_HtmlFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_HtmlFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_HtmlFieldIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_HtmlFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_MultiTextFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_MultiTextFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_MultiTextFieldIndex_DocumentId_ContentType", + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex( + "IDX_MultiTextFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", - "Latest") + "Latest" + ) ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + Value (764) + Published and Latest (1) = 767 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_MultiTextFieldIndex_DocumentId_Value", - "DocumentId", - "Value(764)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_MultiTextFieldIndex_DocumentId_Value", "DocumentId", "Value(764)", "Published", "Latest") ); return 4; @@ -771,40 +529,28 @@ public async Task UpdateFrom4Async() // Attempts to drop an index that existed only in RC2. try { - await SchemaBuilder.AlterIndexTableAsync(table => table - .DropIndex("IDX_TimeFieldIndex_Time") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.DropIndex("IDX_TimeFieldIndex_Time")); } catch { _logger.LogWarning("Failed to drop an index that does not exist 'IDX_TimeFieldIndex_Time'"); } - await SchemaBuilder.AlterIndexTableAsync(table => table - .DropIndex("IDX_TimeFieldIndex_DocumentId_Time") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.DropIndex("IDX_TimeFieldIndex_DocumentId_Time")); // SqLite does not support dropping columns. try { - await SchemaBuilder.AlterIndexTableAsync(table => table - .DropColumn("Time")); + await SchemaBuilder.AlterIndexTableAsync(table => table.DropColumn("Time")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Time", column => column.Nullable())); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Time", column => column.Nullable())); } catch { _logger.LogWarning("Failed to alter 'Time' column. This is not an error when using SqLite"); } - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TimeFieldIndex_DocumentId_Time", - "DocumentId", - "Time", - "Published", - "Latest") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_TimeFieldIndex_DocumentId_Time", "DocumentId", "Time", "Published", "Latest")); return 5; } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/MultiTextFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/MultiTextFieldIndexProvider.cs index f8126161632..044dfc5af6a 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/MultiTextFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/MultiTextFieldIndexProvider.cs @@ -34,7 +34,8 @@ public MultiTextFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -75,21 +76,19 @@ public override void Describe(DescribeContext context) return fieldDefinitions .GetContentFields(contentItem) - .SelectMany(pair => - pair.Field.Values.Select(value => (pair.Definition, Value: value))) - .Select(pair => - new MultiTextFieldIndex - { - Latest = contentItem.Latest, - Published = contentItem.Published, - ContentItemId = contentItem.ContentItemId, - ContentItemVersionId = contentItem.ContentItemVersionId, - ContentType = contentItem.ContentType, - ContentPart = pair.Definition.PartDefinition.Name, - ContentField = pair.Definition.Name, - Value = pair.Value?[..Math.Min(pair.Value.Length, MultiTextFieldIndex.MaxValueSize)], - BigValue = pair.Value, - }); + .SelectMany(pair => pair.Field.Values.Select(value => (pair.Definition, Value: value))) + .Select(pair => new MultiTextFieldIndex + { + Latest = contentItem.Latest, + Published = contentItem.Published, + ContentItemId = contentItem.ContentItemId, + ContentItemVersionId = contentItem.ContentItemVersionId, + ContentType = contentItem.ContentType, + ContentPart = pair.Definition.PartDefinition.Name, + ContentField = pair.Definition.Name, + Value = pair.Value?[..Math.Min(pair.Value.Length, MultiTextFieldIndex.MaxValueSize)], + BigValue = pair.Value, + }); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/NumericFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/NumericFieldIndexProvider.cs index 363f90eed55..47829b2dd37 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/NumericFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/NumericFieldIndexProvider.cs @@ -28,7 +28,8 @@ public NumericFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -46,7 +47,7 @@ public override void Describe(DescribeContext context) // Lazy initialization because of ISession cyclic dependency _contentDefinitionManager ??= _serviceProvider.GetRequiredService(); - // Search for NumericField + // Search for NumericField var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); // This can occur when content items become orphaned, particularly layer widgets when a layer is removed, before its widgets have been unpublished. @@ -69,18 +70,17 @@ public override void Describe(DescribeContext context) return fieldDefinitions .GetContentFields(contentItem) - .Select(pair => - new NumericFieldIndex - { - Latest = contentItem.Latest, - Published = contentItem.Published, - ContentItemId = contentItem.ContentItemId, - ContentItemVersionId = contentItem.ContentItemVersionId, - ContentType = contentItem.ContentType, - ContentPart = pair.Definition.PartDefinition.Name, - ContentField = pair.Definition.Name, - Numeric = pair.Field.Value, - }); + .Select(pair => new NumericFieldIndex + { + Latest = contentItem.Latest, + Published = contentItem.Published, + ContentItemId = contentItem.ContentItemId, + ContentItemVersionId = contentItem.ContentItemVersionId, + ContentType = contentItem.ContentType, + ContentPart = pair.Definition.PartDefinition.Name, + ContentField = pair.Definition.Name, + Numeric = pair.Field.Value, + }); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/TextFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/TextFieldIndexProvider.cs index b6e784cbf98..35f00ef1f42 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/TextFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/TextFieldIndexProvider.cs @@ -34,7 +34,8 @@ public TextFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -62,9 +63,7 @@ public override void Describe(DescribeContext context) return null; } - var fieldDefinitions = contentTypeDefinition - .Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(TextField))) - .ToArray(); + var fieldDefinitions = contentTypeDefinition.Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(TextField))).ToArray(); // This type doesn't have any TextField, ignore it if (fieldDefinitions.Length == 0) @@ -75,19 +74,18 @@ public override void Describe(DescribeContext context) return fieldDefinitions .GetContentFields(contentItem) - .Select(pair => - new TextFieldIndex - { - Latest = contentItem.Latest, - Published = contentItem.Published, - ContentItemId = contentItem.ContentItemId, - ContentItemVersionId = contentItem.ContentItemVersionId, - ContentType = contentItem.ContentType, - ContentPart = pair.Definition.PartDefinition.Name, - ContentField = pair.Definition.Name, - Text = pair.Field.Text?[..Math.Min(pair.Field.Text.Length, TextFieldIndex.MaxTextSize)], - BigText = pair.Field.Text, - }); + .Select(pair => new TextFieldIndex + { + Latest = contentItem.Latest, + Published = contentItem.Published, + ContentItemId = contentItem.ContentItemId, + ContentItemVersionId = contentItem.ContentItemVersionId, + ContentType = contentItem.ContentType, + ContentPart = pair.Definition.PartDefinition.Name, + ContentField = pair.Definition.Name, + Text = pair.Field.Text?[..Math.Min(pair.Field.Text.Length, TextFieldIndex.MaxTextSize)], + BigText = pair.Field.Text, + }); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/TimeFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/TimeFieldIndexProvider.cs index bed5826ce40..2c21f8fe0d1 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/TimeFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/TimeFieldIndexProvider.cs @@ -28,7 +28,8 @@ public TimeFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -56,9 +57,7 @@ public override void Describe(DescribeContext context) return null; } - var fieldDefinitions = contentTypeDefinition - .Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(TimeField))) - .ToArray(); + var fieldDefinitions = contentTypeDefinition.Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(TimeField))).ToArray(); // This type doesn't have any TimeField, ignore it if (fieldDefinitions.Length == 0) @@ -69,18 +68,17 @@ public override void Describe(DescribeContext context) return fieldDefinitions .GetContentFields(contentItem) - .Select(pair => - new TimeFieldIndex - { - Latest = contentItem.Latest, - Published = contentItem.Published, - ContentItemId = contentItem.ContentItemId, - ContentItemVersionId = contentItem.ContentItemVersionId, - ContentType = contentItem.ContentType, - ContentPart = pair.Definition.PartDefinition.Name, - ContentField = pair.Definition.Name, - Time = pair.Field.Value, - }); + .Select(pair => new TimeFieldIndex + { + Latest = contentItem.Latest, + Published = contentItem.Published, + ContentItemId = contentItem.ContentItemId, + ContentItemVersionId = contentItem.ContentItemVersionId, + ContentType = contentItem.ContentType, + ContentPart = pair.Definition.PartDefinition.Name, + ContentField = pair.Definition.Name, + Time = pair.Field.Value, + }); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/UserPickerFieldIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/UserPickerFieldIndexProvider.cs index 3023c76eaa9..a31fa80ede4 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/UserPickerFieldIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/UserPickerFieldIndexProvider.cs @@ -28,7 +28,8 @@ public UserPickerFieldIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -69,20 +70,18 @@ public override void Describe(DescribeContext context) return fieldDefinitions .GetContentFields(contentItem) - .SelectMany(pair => - pair.Field.UserIds.Select(value => (pair.Definition, UserId: value))) - .Select(pair => - new UserPickerFieldIndex - { - Latest = contentItem.Latest, - Published = contentItem.Published, - ContentItemId = contentItem.ContentItemId, - ContentItemVersionId = contentItem.ContentItemVersionId, - ContentType = contentItem.ContentType, - ContentPart = pair.Definition.PartDefinition.Name, - ContentField = pair.Definition.Name, - SelectedUserId = pair.UserId, - }); + .SelectMany(pair => pair.Field.UserIds.Select(value => (pair.Definition, UserId: value))) + .Select(pair => new UserPickerFieldIndex + { + Latest = contentItem.Latest, + Published = contentItem.Published, + ContentItemId = contentItem.ContentItemId, + ContentItemVersionId = contentItem.ContentItemVersionId, + ContentType = contentItem.ContentType, + ContentPart = pair.Definition.PartDefinition.Name, + ContentField = pair.Definition.Name, + SelectedUserId = pair.UserId, + }); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/UserPickerMigrations.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/UserPickerMigrations.cs index 06fd0dac97d..0758ab3cf71 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/UserPickerMigrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/SQL/UserPickerMigrations.cs @@ -11,44 +11,38 @@ public class UserPickerMigrations : DataMigration { public async Task CreateAsync() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ContentItemVersionId", column => column.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("Published", column => column.Nullable()) - .Column("Latest", column => column.Nullable()) - .Column("SelectedUserId") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ContentItemVersionId", column => column.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("Published", column => column.Nullable()) + .Column("Latest", column => column.Nullable()) + .Column("SelectedUserId") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserPickerFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_UserPickerFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserPickerFieldIndex_DocumentId_ContentType", + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex( + "IDX_UserPickerFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", - "Latest") + "Latest" + ) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserPickerFieldIndex_DocumentId_SelectedUserId", - "DocumentId", - "SelectedUserId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_UserPickerFieldIndex_DocumentId_SelectedUserId", "DocumentId", "SelectedUserId", "Published", "Latest") ); // Shortcut other migration steps on new content definition schemas. @@ -58,33 +52,26 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom1Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserPickerFieldIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_UserPickerFieldIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserPickerFieldIndex_DocumentId_ContentType", + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex( + "IDX_UserPickerFieldIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", - "Latest") + "Latest" + ) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserPickerFieldIndex_DocumentId_SelectedUserId", - "DocumentId", - "SelectedUserId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_UserPickerFieldIndex_DocumentId_SelectedUserId", "DocumentId", "SelectedUserId", "Published", "Latest") ); return 2; diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Media/MediaShapes.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Media/MediaShapes.cs index 64e362deb59..fc70c5e0803 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Media/MediaShapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Media/MediaShapes.cs @@ -9,7 +9,8 @@ public class MediaShapes : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("HtmlField_Edit") + builder + .Describe("HtmlField_Edit") .OnDisplaying(displaying => { var editor = displaying.Shape; diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Migrations.cs index 4131435aa4e..e03ed2feeb8 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Migrations.cs @@ -87,16 +87,22 @@ public async Task UpdateFrom1Async() { if (partDefinition.Fields.Any(x => x.FieldDefinition.Name == "HtmlField")) { - await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, partBuilder => - { - foreach (var fieldDefinition in partDefinition.Fields.Where(x => x.FieldDefinition.Name == "HtmlField")) + await _contentDefinitionManager.AlterPartDefinitionAsync( + partDefinition.Name, + partBuilder => { - partBuilder.WithField(fieldDefinition.Name, fieldBuilder => + foreach (var fieldDefinition in partDefinition.Fields.Where(x => x.FieldDefinition.Name == "HtmlField")) { - fieldBuilder.MergeSettings(x => x.SanitizeHtml = false); - }); + partBuilder.WithField( + fieldDefinition.Name, + fieldBuilder => + { + fieldBuilder.MergeSettings(x => x.SanitizeHtml = false); + } + ); + } } - }); + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Services/DefaultContentPickerResultProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Services/DefaultContentPickerResultProvider.cs index 177a5b2b5a2..973b381a4d1 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Services/DefaultContentPickerResultProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Services/DefaultContentPickerResultProvider.cs @@ -23,7 +23,12 @@ public class DefaultContentPickerResultProvider : IContentPickerResultProvider private readonly IContentDefinitionManager _contentDefinitionManager; private readonly ISession _session; - public DefaultContentPickerResultProvider(IContentManager contentManager, IContentDefinitionManager contentDefinitionManager, ISession session, ILiquidTemplateManager templateManager) + public DefaultContentPickerResultProvider( + IContentManager contentManager, + IContentDefinitionManager contentDefinitionManager, + ISession session, + ILiquidTemplateManager templateManager + ) { _templateManager = templateManager; _contentManager = contentManager; @@ -38,14 +43,10 @@ public async Task> Search(ContentPickerSearchCo var contentTypes = searchContext.ContentTypes; if (searchContext.DisplayAllContentTypes) { - contentTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(x => !x.HasStereotype()) - .Select(x => x.Name) - .AsEnumerable(); + contentTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(x => !x.HasStereotype()).Select(x => x.Name).AsEnumerable(); } - var query = _session.Query() - .With(x => x.ContentType.IsIn(contentTypes) && x.Latest); + var query = _session.Query().With(x => x.ContentType.IsIn(contentTypes) && x.Latest); if (!string.IsNullOrEmpty(searchContext.Query)) { @@ -62,13 +63,19 @@ public async Task> Search(ContentPickerSearchCo var cultureAspect = await _contentManager.PopulateAspectAsync(contentItem, new CultureAspect()); using (CultureScope.Create(cultureAspect.Culture)) { - results.Add(new ContentPickerResult - { - ContentItemId = contentItem.ContentItemId, - DisplayText = await _templateManager.RenderStringAsync(settings.TitlePattern, NullEncoder.Default, contentItem, - new Dictionary() { [nameof(ContentItem)] = new ObjectValue(contentItem) }), - HasPublished = await _contentManager.HasPublishedVersionAsync(contentItem) - }); + results.Add( + new ContentPickerResult + { + ContentItemId = contentItem.ContentItemId, + DisplayText = await _templateManager.RenderStringAsync( + settings.TitlePattern, + NullEncoder.Default, + contentItem, + new Dictionary() { [nameof(ContentItem)] = new ObjectValue(contentItem) } + ), + HasPublished = await _contentManager.HasPublishedVersionAsync(contentItem) + } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Services/DefaultUserPickerResultProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Services/DefaultUserPickerResultProvider.cs index 52b8ec10b11..fed97cdc9db 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Services/DefaultUserPickerResultProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Services/DefaultUserPickerResultProvider.cs @@ -18,10 +18,7 @@ public class DefaultUserPickerResultProvider : IUserPickerResultProvider private readonly UserManager _userManager; private readonly ISession _session; - public DefaultUserPickerResultProvider( - RoleManager roleManager, - UserManager userManager, - ISession session) + public DefaultUserPickerResultProvider(RoleManager roleManager, UserManager userManager, ISession session) { _roleManager = roleManager; _userManager = userManager; @@ -51,12 +48,14 @@ public async Task> Search(UserPickerSearchContext foreach (var user in users) { - results.Add(new UserPickerResult - { - UserId = user.UserId, - DisplayText = user.UserName, - IsEnabled = user.IsEnabled - }); + results.Add( + new UserPickerResult + { + UserId = user.UserId, + DisplayText = user.UserName, + IsEnabled = user.IsEnabled + } + ); } return results.OrderBy(x => x.DisplayText); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/BooleanFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/BooleanFieldSettingsDriver.cs index 9f3759b332d..e8fe2a97ab8 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/BooleanFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/BooleanFieldSettingsDriver.cs @@ -11,14 +11,17 @@ public class BooleanFieldSettingsDriver : ContentPartFieldDefinitionDisplayDrive { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("BooleanFieldSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "BooleanFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Hint = settings.Hint; - model.Label = settings.Label; - model.DefaultValue = settings.DefaultValue; - }) + model.Hint = settings.Hint; + model.Label = settings.Label; + model.DefaultValue = settings.DefaultValue; + } + ) .Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/ContentPickerFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/ContentPickerFieldSettingsDriver.cs index 19cb2705da6..955f7ea83fe 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/ContentPickerFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/ContentPickerFieldSettingsDriver.cs @@ -24,17 +24,21 @@ public ContentPickerFieldSettingsDriver(ILiquidTemplateManager templateManager, public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("ContentPickerFieldSettings_Edit", model => - { - var settings = partFieldDefinition.GetSettings(); - model.Hint = settings.Hint; - model.Required = settings.Required; - model.Multiple = settings.Multiple; - model.Source = GetSource(settings); - model.DisplayedContentTypes = settings.DisplayedContentTypes; - model.TitlePattern = settings.TitlePattern; - model.Stereotypes = string.Join(',', settings.DisplayedStereotypes ?? []); - }).Location("Content"); + return Initialize( + "ContentPickerFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.GetSettings(); + model.Hint = settings.Hint; + model.Required = settings.Required; + model.Multiple = settings.Multiple; + model.Source = GetSource(settings); + model.DisplayedContentTypes = settings.DisplayedContentTypes; + model.TitlePattern = settings.TitlePattern; + model.Stereotypes = string.Join(',', settings.DisplayedStereotypes ?? []); + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) @@ -77,7 +81,10 @@ private bool IsValidTitlePattern(UpdatePartFieldEditorContext context, ContentPi { if (!string.IsNullOrEmpty(model.TitlePattern) && !_templateManager.Validate(model.TitlePattern, out var titleErrors)) { - context.Updater.ModelState.AddModelError(nameof(model.TitlePattern), S["Title Pattern does not contain a valid Liquid expression. Details: {0}", string.Join(" ", titleErrors)]); + context.Updater.ModelState.AddModelError( + nameof(model.TitlePattern), + S["Title Pattern does not contain a valid Liquid expression. Details: {0}", string.Join(" ", titleErrors)] + ); return false; } @@ -115,9 +122,7 @@ private static ContentPickerSettingType GetSource(ContentPickerFieldSettings set return ContentPickerSettingType.AllTypes; } - return settings.DisplayedStereotypes != null && settings.DisplayedStereotypes.Length > 0 - ? ContentPickerSettingType.Stereotypes - : ContentPickerSettingType.ContentTypes; + return settings.DisplayedStereotypes != null && settings.DisplayedStereotypes.Length > 0 ? ContentPickerSettingType.Stereotypes : ContentPickerSettingType.ContentTypes; } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/DateFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/DateFieldSettingsDriver.cs index c332cd76ff6..cefbe2ee094 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/DateFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/DateFieldSettingsDriver.cs @@ -11,13 +11,16 @@ public class DateFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriver("DateFieldSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "DateFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Hint = settings.Hint; - model.Required = settings.Required; - }) + model.Hint = settings.Hint; + model.Required = settings.Required; + } + ) .Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/DateTimeFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/DateTimeFieldSettingsDriver.cs index 4041c83874f..bebd466b2f1 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/DateTimeFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/DateTimeFieldSettingsDriver.cs @@ -11,13 +11,16 @@ public class DateTimeFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriv { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("DateTimeFieldSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "DateTimeFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Hint = settings.Hint; - model.Required = settings.Required; - }) + model.Hint = settings.Hint; + model.Required = settings.Required; + } + ) .Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldMonacoEditorSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldMonacoEditorSettingsDriver.cs index bcfdbd501f8..02733aacb4f 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldMonacoEditorSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldMonacoEditorSettingsDriver.cs @@ -22,17 +22,20 @@ public HtmlFieldMonacoEditorSettingsDriver(IStringLocalizer("HtmlFieldMonacoEditorSettings_Edit", model => - { - var settings = partFieldDefinition.GetSettings(); - if (string.IsNullOrWhiteSpace(settings.Options)) - { - settings.Options = JConvert.SerializeObject(new { automaticLayout = true, language = "html" }, JOptions.Indented); - } + return Initialize( + "HtmlFieldMonacoEditorSettings_Edit", + model => + { + var settings = partFieldDefinition.GetSettings(); + if (string.IsNullOrWhiteSpace(settings.Options)) + { + settings.Options = JConvert.SerializeObject(new { automaticLayout = true, language = "html" }, JOptions.Indented); + } - model.Options = settings.Options; - }) - .Location("Editor"); + model.Options = settings.Options; + } + ) + .Location("Editor"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldSettingsDriver.cs index 14ca5ef86c8..8abfa73e154 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldSettingsDriver.cs @@ -11,14 +11,17 @@ public class HtmlFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriver("HtmlFieldSettings_Edit", model => - { - var settings = partFieldDefinition.GetSettings(); + return Initialize( + "HtmlFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.GetSettings(); - model.SanitizeHtml = settings.SanitizeHtml; - model.Hint = settings.Hint; - }) - .Location("Content:20"); + model.SanitizeHtml = settings.SanitizeHtml; + model.Hint = settings.Hint; + } + ) + .Location("Content:20"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldTrumbowygEditorSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldTrumbowygEditorSettingsDriver.cs index 6a92ba42dcb..b404784c332 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldTrumbowygEditorSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldTrumbowygEditorSettingsDriver.cs @@ -20,14 +20,17 @@ public HtmlFieldTrumbowygEditorSettingsDriver(IStringLocalizer("HtmlFieldTrumbowygEditorSettings_Edit", model => - { - var settings = partFieldDefinition.GetSettings(); - - model.Options = settings.Options; - model.InsertMediaWithUrl = settings.InsertMediaWithUrl; - }) - .Location("Editor"); + return Initialize( + "HtmlFieldTrumbowygEditorSettings_Edit", + model => + { + var settings = partFieldDefinition.GetSettings(); + + model.Options = settings.Options; + model.InsertMediaWithUrl = settings.InsertMediaWithUrl; + } + ) + .Location("Editor"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/LinkFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/LinkFieldSettingsDriver.cs index 6d61f64e832..6ef73f49a9a 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/LinkFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/LinkFieldSettingsDriver.cs @@ -11,19 +11,22 @@ public class LinkFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriver("LinkFieldSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "LinkFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Hint = settings.Hint; - model.HintLinkText = settings.HintLinkText; - model.Required = settings.Required; - model.LinkTextMode = settings.LinkTextMode; - model.UrlPlaceholder = settings.UrlPlaceholder; - model.TextPlaceholder = settings.TextPlaceholder; - model.DefaultUrl = settings.DefaultUrl; - model.DefaultText = settings.DefaultText; - }) + model.Hint = settings.Hint; + model.HintLinkText = settings.HintLinkText; + model.Required = settings.Required; + model.LinkTextMode = settings.LinkTextMode; + model.UrlPlaceholder = settings.UrlPlaceholder; + model.TextPlaceholder = settings.TextPlaceholder; + model.DefaultUrl = settings.DefaultUrl; + model.DefaultText = settings.DefaultText; + } + ) .Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/LocalizationSetContentPickerFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/LocalizationSetContentPickerFieldSettingsDriver.cs index fb2a4018eb0..105fc27e5a7 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/LocalizationSetContentPickerFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/LocalizationSetContentPickerFieldSettingsDriver.cs @@ -13,16 +13,19 @@ public class LocalizationSetContentPickerFieldSettingsDriver : ContentPartFieldD { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("LocalizationSetContentPickerFieldSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "LocalizationSetContentPickerFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Hint = settings.Hint; - model.Required = settings.Required; - model.Multiple = settings.Multiple; - model.DisplayedContentTypes = settings.DisplayedContentTypes; - }) - .Location("Content"); + model.Hint = settings.Hint; + model.Required = settings.Required; + model.Multiple = settings.Multiple; + model.DisplayedContentTypes = settings.DisplayedContentTypes; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/MultiTextFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/MultiTextFieldSettingsDriver.cs index b39c9d07a0b..cc295ef1831 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/MultiTextFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/MultiTextFieldSettingsDriver.cs @@ -20,15 +20,18 @@ public MultiTextFieldSettingsDriver(IStringLocalizer("MultiTextFieldSettings_Edit", model => - { - var settings = partFieldDefinition.GetSettings(); - - model.Required = settings.Required; - model.Hint = settings.Hint; - model.Options = JConvert.SerializeObject(settings.Options, JOptions.Indented); - }) - .Location("Content"); + return Initialize( + "MultiTextFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.GetSettings(); + + model.Required = settings.Required; + model.Hint = settings.Hint; + model.Options = JConvert.SerializeObject(settings.Options, JOptions.Indented); + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/NumericFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/NumericFieldSettingsDriver.cs index ddf2c171f48..4056399287f 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/NumericFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/NumericFieldSettingsDriver.cs @@ -11,18 +11,21 @@ public class NumericFieldSettingsDriver : ContentPartFieldDefinitionDisplayDrive { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("NumericFieldSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "NumericFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Hint = settings.Hint; - model.Required = settings.Required; - model.Scale = settings.Scale; - model.Minimum = settings.Minimum; - model.Maximum = settings.Maximum; - model.Placeholder = settings.Placeholder; - model.DefaultValue = settings.DefaultValue; - }) + model.Hint = settings.Hint; + model.Required = settings.Required; + model.Scale = settings.Scale; + model.Minimum = settings.Minimum; + model.Maximum = settings.Maximum; + model.Placeholder = settings.Placeholder; + model.DefaultValue = settings.DefaultValue; + } + ) .Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldHeaderDisplaySettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldHeaderDisplaySettingsDriver.cs index 2017684565a..06daaaaa0ed 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldHeaderDisplaySettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldHeaderDisplaySettingsDriver.cs @@ -11,13 +11,16 @@ public class TextFieldHeaderDisplaySettingsDriver : ContentPartFieldDefinitionDi { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("TextFieldHeaderDisplaySettings_Edit", model => - { - var settings = partFieldDefinition.GetSettings(); + return Initialize( + "TextFieldHeaderDisplaySettings_Edit", + model => + { + var settings = partFieldDefinition.GetSettings(); - model.Level = settings.Level; - }) - .Location("DisplayMode"); + model.Level = settings.Level; + } + ) + .Location("DisplayMode"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldMonacoEditorSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldMonacoEditorSettingsDriver.cs index cd07a5f61ba..39ce912e2a6 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldMonacoEditorSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldMonacoEditorSettingsDriver.cs @@ -21,17 +21,20 @@ public TextFieldMonacoEditorSettingsDriver(IStringLocalizer("TextFieldMonacoEditorSettings_Edit", model => - { - var settings = partFieldDefinition.GetSettings(); - if (string.IsNullOrWhiteSpace(settings.Options)) - { - settings.Options = JConvert.SerializeObject(new { automaticLayout = true, language = "html" }, JOptions.Indented); - } - - model.Options = settings.Options; - }) - .Location("Editor"); + return Initialize( + "TextFieldMonacoEditorSettings_Edit", + model => + { + var settings = partFieldDefinition.GetSettings(); + if (string.IsNullOrWhiteSpace(settings.Options)) + { + settings.Options = JConvert.SerializeObject(new { automaticLayout = true, language = "html" }, JOptions.Indented); + } + + model.Options = settings.Options; + } + ) + .Location("Editor"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldPredefinedListEditorSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldPredefinedListEditorSettingsDriver.cs index 2638ab53a51..45b6bc2868c 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldPredefinedListEditorSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldPredefinedListEditorSettingsDriver.cs @@ -20,15 +20,18 @@ public TextFieldPredefinedListEditorSettingsDriver(IStringLocalizer("TextFieldPredefinedListEditorSettings_Edit", model => - { - var settings = partFieldDefinition.GetSettings(); + return Initialize( + "TextFieldPredefinedListEditorSettings_Edit", + model => + { + var settings = partFieldDefinition.GetSettings(); - model.DefaultValue = settings.DefaultValue; - model.Editor = settings.Editor; - model.Options = JConvert.SerializeObject(settings.Options ?? [], JOptions.Indented); - }) - .Location("Editor"); + model.DefaultValue = settings.DefaultValue; + model.Editor = settings.Editor; + model.Options = JConvert.SerializeObject(settings.Options ?? [], JOptions.Indented); + } + ) + .Location("Editor"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) @@ -44,9 +47,7 @@ public override async Task UpdateAsync(ContentPartFieldDefinitio { settings.DefaultValue = model.DefaultValue; settings.Editor = model.Editor; - settings.Options = string.IsNullOrWhiteSpace(model.Options) - ? [] - : JConvert.DeserializeObject(model.Options); + settings.Options = string.IsNullOrWhiteSpace(model.Options) ? [] : JConvert.DeserializeObject(model.Options); } catch { diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldSettingsDriver.cs index ed5eb8d2c5e..69e397afb6f 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TextFieldSettingsDriver.cs @@ -11,14 +11,17 @@ public class TextFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriver("TextFieldSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "TextFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Hint = settings.Hint; - model.Required = settings.Required; - model.DefaultValue = settings.DefaultValue; - }) + model.Hint = settings.Hint; + model.Required = settings.Required; + model.DefaultValue = settings.DefaultValue; + } + ) .Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TimeFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TimeFieldSettingsDriver.cs index dfa539ab27b..3e057b60739 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TimeFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/TimeFieldSettingsDriver.cs @@ -11,14 +11,17 @@ public class TimeFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriver("TimeFieldSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "TimeFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Hint = settings.Hint; - model.Required = settings.Required; - model.Step = settings.Step; - }) + model.Hint = settings.Hint; + model.Required = settings.Required; + model.Step = settings.Step; + } + ) .Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/UserPickerFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/UserPickerFieldSettingsDriver.cs index 0c5459e3ab1..2a378fe80f0 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/UserPickerFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/UserPickerFieldSettingsDriver.cs @@ -20,25 +20,24 @@ public UserPickerFieldSettingsDriver(IRoleService roleService) public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("UserPickerFieldSettings_Edit", async model => - { - var settings = partFieldDefinition.GetSettings(); - model.Hint = settings.Hint; - model.Required = settings.Required; - model.Multiple = settings.Multiple; - var roles = (await _roleService.GetRoleNamesAsync()) - .Except(RoleHelper.SystemRoleNames, StringComparer.OrdinalIgnoreCase) - .Select(roleName => new RoleEntry + return Initialize( + "UserPickerFieldSettings_Edit", + async model => { - Role = roleName, - IsSelected = settings.DisplayedRoles.Contains(roleName, StringComparer.OrdinalIgnoreCase) - }) - .ToArray(); - - model.Roles = roles; - model.DisplayAllUsers = settings.DisplayAllUsers || !roles.Where(x => x.IsSelected).Any(); + var settings = partFieldDefinition.GetSettings(); + model.Hint = settings.Hint; + model.Required = settings.Required; + model.Multiple = settings.Multiple; + var roles = (await _roleService.GetRoleNamesAsync()) + .Except(RoleHelper.SystemRoleNames, StringComparer.OrdinalIgnoreCase) + .Select(roleName => new RoleEntry { Role = roleName, IsSelected = settings.DisplayedRoles.Contains(roleName, StringComparer.OrdinalIgnoreCase) }) + .ToArray(); - }).Location("Content"); + model.Roles = roles; + model.DisplayAllUsers = settings.DisplayAllUsers || !roles.Where(x => x.IsSelected).Any(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/YoutubeFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/YoutubeFieldSettingsDriver.cs index 436395fe7e6..010e3ab1084 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/YoutubeFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/YoutubeFieldSettingsDriver.cs @@ -11,17 +11,20 @@ public class YoutubeFieldSettingsDriver : ContentPartFieldDefinitionDisplayDrive { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("YoutubeFieldSetting_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "YoutubeFieldSetting_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Height = model.Height != default ? model.Height : 315; - model.Width = model.Width != default ? model.Width : 560; - }) + model.Height = model.Height != default ? model.Height : 315; + model.Width = model.Width != default ? model.Width : 560; + } + ) .Location("Content"); } - public async override Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) + public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) { var model = new YoutubeFieldSettings(); await context.Updater.TryUpdateModelAsync(model, Prefix); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Startup.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Startup.cs index 105438153e8..4be8f9c0d56 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Startup.cs @@ -1,3 +1,4 @@ +using System; using Fluid; using Microsoft.Extensions.DependencyInjection; using OrchardCore.ContentFields.Drivers; @@ -15,7 +16,6 @@ using OrchardCore.Data.Migration; using OrchardCore.Indexing; using OrchardCore.Modules; -using System; namespace OrchardCore.ContentFields { @@ -50,15 +50,12 @@ public override void ConfigureServices(IServiceCollection services) }); // Boolean Field - services.AddContentField() - .UseDisplayDriver(); + services.AddContentField().UseDisplayDriver(); services.AddScoped(); services.AddScoped(); // Text Field - services.AddContentField() - .UseDisplayDriver() - .AddHandler(); + services.AddContentField().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); services.AddScoped(); @@ -66,73 +63,56 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); // Html Field - services.AddContentField() - .UseDisplayDriver(); + services.AddContentField().UseDisplayDriver(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); // Link Field - services.AddContentField() - .UseDisplayDriver() - .AddHandler(); + services.AddContentField().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); // MultiText Field - services.AddContentField() - .UseDisplayDriver() - .AddHandler(); + services.AddContentField().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); // Numeric Field - services.AddContentField() - .UseDisplayDriver() - .AddHandler(); + services.AddContentField().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); // DateTime Field - services.AddContentField() - .UseDisplayDriver() - .AddHandler(); + services.AddContentField().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); // Date Field - services.AddContentField() - .UseDisplayDriver() - .AddHandler(); + services.AddContentField().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); // Time Field - services.AddContentField() - .UseDisplayDriver() - .AddHandler(); + services.AddContentField().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); // Video field - services.AddContentField() - .UseDisplayDriver() - .AddHandler(); + services.AddContentField().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); // Content picker field - services.AddContentField() - .UseDisplayDriver() - .AddHandler(); + services.AddContentField().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); @@ -148,7 +128,8 @@ public class LocalizationSetContentPickerStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddContentField() + services + .AddContentField() .UseDisplayDriver() .AddHandler(); @@ -188,7 +169,8 @@ public override void ConfigureServices(IServiceCollection services) o.MemberAccessStrategy.Register(); }); - services.AddContentField() + services + .AddContentField() .UseDisplayDriver(d => !string.Equals(d, "UserNames", StringComparison.OrdinalIgnoreCase)) .UseDisplayDriver(d => string.Equals(d, "UserNames", StringComparison.OrdinalIgnoreCase)) .AddHandler(); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/AdminMenu.cs index 0b8726ff7db..ff7376fd5d4 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/AdminMenu.cs @@ -10,17 +10,10 @@ namespace OrchardCore.ContentLocalization [Feature("OrchardCore.ContentLocalization.ContentCulturePicker")] public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _providersRouteValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", ContentRequestCultureProviderSettingsDriver.GroupId }, - }; + private static readonly RouteValueDictionary _providersRouteValues = + new() { { "area", "OrchardCore.Settings" }, { "groupId", ContentRequestCultureProviderSettingsDriver.GroupId }, }; - private static readonly RouteValueDictionary _pickerRouteValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", ContentCulturePickerSettingsDriver.GroupId }, - }; + private static readonly RouteValueDictionary _pickerRouteValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", ContentCulturePickerSettingsDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -36,27 +29,41 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Localization"], localization => localization - .Add(S["Content Request Culture Provider"], S["Content Request Culture Provider"].PrefixPosition(), provider => provider - .AddClass("contentrequestcultureprovider") - .Id("contentrequestcultureprovider") - .Action("Index", "Admin", _providersRouteValues) - .Permission(Permissions.ManageContentCulturePicker) - .LocalNav() - ) - .Add(S["Content Culture Picker"], S["Content Culture Picker"].PrefixPosition(), picker => picker - .AddClass("contentculturepicker") - .Id("contentculturepicker") - .Action("Index", "Admin", _pickerRouteValues) - .Permission(Permissions.ManageContentCulturePicker) - .LocalNav() + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Localization"], + localization => + localization + .Add( + S["Content Request Culture Provider"], + S["Content Request Culture Provider"].PrefixPosition(), + provider => + provider + .AddClass("contentrequestcultureprovider") + .Id("contentrequestcultureprovider") + .Action("Index", "Admin", _providersRouteValues) + .Permission(Permissions.ManageContentCulturePicker) + .LocalNav() + ) + .Add( + S["Content Culture Picker"], + S["Content Culture Picker"].PrefixPosition(), + picker => + picker + .AddClass("contentculturepicker") + .Id("contentculturepicker") + .Action("Index", "Admin", _pickerRouteValues) + .Permission(Permissions.ManageContentCulturePicker) + .LocalNav() + ) ) - ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Controllers/AdminController.cs index f54879c561e..cb3a956cc1e 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Controllers/AdminController.cs @@ -25,7 +25,8 @@ public AdminController( INotifier notifier, IContentLocalizationManager localizationManager, IHtmlLocalizer localizer, - IAuthorizationService authorizationService) + IAuthorizationService authorizationService + ) { _contentManager = contentManager; _notifier = notifier; diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Controllers/ContentCulturePickerController.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Controllers/ContentCulturePickerController.cs index 1f4917ec918..f2eff5c97d4 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Controllers/ContentCulturePickerController.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Controllers/ContentCulturePickerController.cs @@ -20,10 +20,7 @@ public class ContentCulturePickerController : Controller private readonly ILocalizationService _locationService; private readonly IContentCulturePickerService _culturePickerService; - public ContentCulturePickerController( - ISiteService siteService, - ILocalizationService locationService, - IContentCulturePickerService culturePickerService) + public ContentCulturePickerController(ISiteService siteService, ILocalizationService locationService, IContentCulturePickerService culturePickerService) { _siteService = siteService; _locationService = locationService; diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/DefaultContentLocalizationManager.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/DefaultContentLocalizationManager.cs index 85c24505a43..31145fa2c3c 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/DefaultContentLocalizationManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/DefaultContentLocalizationManager.cs @@ -35,7 +35,8 @@ public DefaultContentLocalizationManager( ILocalizationService localizationService, ILogger logger, IEnumerable handlers, - Entities.IIdGenerator iidGenerator) + Entities.IIdGenerator iidGenerator + ) { _contentManager = contentManager; _session = session; @@ -50,11 +51,9 @@ public DefaultContentLocalizationManager( public Task GetContentItemAsync(string localizationSet, string culture) { var invariantCulture = culture.ToLowerInvariant(); - return _session.Query(i => - (i.Published || i.Latest) && - i.LocalizationSet == localizationSet && - i.Culture == invariantCulture) - .FirstOrDefaultAsync(); + return _session + .Query(i => (i.Published || i.Latest) && i.LocalizationSet == localizationSet && i.Culture == invariantCulture) + .FirstOrDefaultAsync(); } public Task> GetItemsForSetAsync(string localizationSet) @@ -65,7 +64,9 @@ public Task> GetItemsForSetAsync(string localizationSet public Task> GetItemsForSetsAsync(IEnumerable localizationSets, string culture) { var invariantCulture = culture.ToLowerInvariant(); - return _session.Query(i => (i.Published || i.Latest) && i.LocalizationSet.IsIn(localizationSets) && i.Culture == invariantCulture).ListAsync(); + return _session + .Query(i => (i.Published || i.Latest) && i.LocalizationSet.IsIn(localizationSets) && i.Culture == invariantCulture) + .ListAsync(); } public async Task LocalizeAsync(ContentItem content, string targetCulture) @@ -160,29 +161,37 @@ public async Task> GetFirstItemIdForSetsAsync(IEnume /// OR null if nothing found. /// /// List of ContentItemId. - private static List GetSingleContentItemIdPerSet(IEnumerable indexValues, string currentCulture, string defaultCulture) + private static List GetSingleContentItemIdPerSet( + IEnumerable indexValues, + string currentCulture, + string defaultCulture + ) { - return indexValues.GroupBy(l => l.LocalizationSet).Select(set => - { - var currentCultureContentItem = set.FirstOrDefault(f => f.Culture == currentCulture); - if (currentCultureContentItem is not null) + return indexValues + .GroupBy(l => l.LocalizationSet) + .Select(set => { - return currentCultureContentItem; - } - - var defaultCultureContentItem = set.FirstOrDefault(f => f.Culture == defaultCulture); - if (defaultCultureContentItem is not null) - { - return defaultCultureContentItem; - } - - if (set.Any()) - { - return set.FirstOrDefault(); - } - - return null; - }).OfType().ToList(); + var currentCultureContentItem = set.FirstOrDefault(f => f.Culture == currentCulture); + if (currentCultureContentItem is not null) + { + return currentCultureContentItem; + } + + var defaultCultureContentItem = set.FirstOrDefault(f => f.Culture == defaultCulture); + if (defaultCultureContentItem is not null) + { + return defaultCultureContentItem; + } + + if (set.Any()) + { + return set.FirstOrDefault(); + } + + return null; + }) + .OfType() + .ToList(); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentCulturePickerNavbarDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentCulturePickerNavbarDisplayDriver.cs index a8ed26a24a0..9560ff23e2e 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentCulturePickerNavbarDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentCulturePickerNavbarDisplayDriver.cs @@ -16,9 +16,7 @@ public class ContentCulturePickerNavbarDisplayDriver : DisplayDriver private readonly IHttpContextAccessor _httpContextAccessor; private readonly ILocalizationService _localizationService; - public ContentCulturePickerNavbarDisplayDriver( - IHttpContextAccessor httpContextAccessor, - ILocalizationService localizationService) + public ContentCulturePickerNavbarDisplayDriver(IHttpContextAccessor httpContextAccessor, ILocalizationService localizationService) { _httpContextAccessor = httpContextAccessor; _localizationService = localizationService; @@ -28,15 +26,15 @@ public override async Task DisplayAsync(Navbar model, BuildDispl { var supportedCultures = (await _localizationService.GetSupportedCulturesAsync()).Select(c => CultureInfo.GetCultureInfo(c)); - return Initialize("ContentCulturePicker", model => - { - model.SupportedCultures = supportedCultures; - model.CurrentCulture = _httpContextAccessor - .HttpContext - .Features - .Get()?.RequestCulture?.Culture ?? CultureInfo.CurrentUICulture; - - }).RenderWhen(() => Task.FromResult(supportedCultures.Count() > 1)) - .Location("Detail", "Content:5"); + return Initialize( + "ContentCulturePicker", + model => + { + model.SupportedCultures = supportedCultures; + model.CurrentCulture = _httpContextAccessor.HttpContext.Features.Get()?.RequestCulture?.Culture ?? CultureInfo.CurrentUICulture; + } + ) + .RenderWhen(() => Task.FromResult(supportedCultures.Count() > 1)) + .Location("Detail", "Content:5"); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentCulturePickerSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentCulturePickerSettingsDriver.cs index 1904052433b..fbdc8269650 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentCulturePickerSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentCulturePickerSettingsDriver.cs @@ -16,9 +16,7 @@ public class ContentCulturePickerSettingsDriver : SectionDisplayDriver EditAsync(ContentCulturePickerSetting return null; } - return Initialize("ContentCulturePickerSettings_Edit", model => - { - model.SetCookie = settings.SetCookie; - model.RedirectToHomepage = settings.RedirectToHomepage; - }).Location("Content:5").OnGroup(GroupId); + return Initialize( + "ContentCulturePickerSettings_Edit", + model => + { + model.SetCookie = settings.SetCookie; + model.RedirectToHomepage = settings.RedirectToHomepage; + } + ) + .Location("Content:5") + .OnGroup(GroupId); } public override async Task UpdateAsync(ContentCulturePickerSettings section, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentRequestCultureProviderSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentRequestCultureProviderSettingsDriver.cs index 04256a09ebb..188633fda11 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentRequestCultureProviderSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/ContentRequestCultureProviderSettingsDriver.cs @@ -16,9 +16,7 @@ public class ContentRequestCultureProviderSettingsDriver : SectionDisplayDriver< private readonly IHttpContextAccessor _httpContextAccessor; private readonly IAuthorizationService _authorizationService; - public ContentRequestCultureProviderSettingsDriver( - IHttpContextAccessor httpContextAccessor, - IAuthorizationService authorizationService) + public ContentRequestCultureProviderSettingsDriver(IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -33,10 +31,15 @@ public override async Task EditAsync(ContentRequestCultureProvid return null; } - return Initialize("ContentRequestCultureProviderSettings_Edit", model => - { - model.SetCookie = settings.SetCookie; - }).Location("Content:5").OnGroup(GroupId); + return Initialize( + "ContentRequestCultureProviderSettings_Edit", + model => + { + model.SetCookie = settings.SetCookie; + } + ) + .Location("Content:5") + .OnGroup(GroupId); } public override async Task UpdateAsync(ContentRequestCultureProviderSettings section, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/LocalizationContentsAdminListDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/LocalizationContentsAdminListDisplayDriver.cs index 1bbf1455e77..a234d9c2f27 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/LocalizationContentsAdminListDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/LocalizationContentsAdminListDisplayDriver.cs @@ -17,9 +17,7 @@ public class LocalizationContentsAdminListDisplayDriver : DisplayDriver stringLocalizer) + public LocalizationContentsAdminListDisplayDriver(ILocalizationService localizationService, IStringLocalizer stringLocalizer) { _localizationService = localizationService; S = stringLocalizer; @@ -30,23 +28,38 @@ protected override void BuildPrefix(ContentOptionsViewModel model, string htmlFi Prefix = "Localization"; } - public override IDisplayResult Display(ContentOptionsViewModel model) - => View("ContentsAdminFilters_Thumbnail__Culture", model).Location("Thumbnail", "Content:20.1"); + public override IDisplayResult Display(ContentOptionsViewModel model) => View("ContentsAdminFilters_Thumbnail__Culture", model).Location("Thumbnail", "Content:20.1"); public override IDisplayResult Edit(ContentOptionsViewModel model, IUpdateModel updater) { - return Initialize("ContentsAdminList__LocalizationPartFilter", async m => - { - model.FilterResult.MapTo(m); - var supportedCultures = await _localizationService.GetSupportedCulturesAsync(); - var cultures = new List + return Initialize( + "ContentsAdminList__LocalizationPartFilter", + async m => { - new() { Text = S["All cultures"], Value = "", Selected = string.IsNullOrEmpty(m.SelectedCulture) } - }; - cultures.AddRange(supportedCultures.Select(culture => new SelectListItem() { Text = culture, Value = culture, Selected = culture == m.SelectedCulture })); + model.FilterResult.MapTo(m); + var supportedCultures = await _localizationService.GetSupportedCulturesAsync(); + var cultures = new List + { + new() + { + Text = S["All cultures"], + Value = "", + Selected = string.IsNullOrEmpty(m.SelectedCulture) + } + }; + cultures.AddRange( + supportedCultures.Select(culture => new SelectListItem() + { + Text = culture, + Value = culture, + Selected = culture == m.SelectedCulture + }) + ); - m.Cultures = cultures; - }).Location("Actions:20"); + m.Cultures = cultures; + } + ) + .Location("Actions:20"); } public override async Task UpdateAsync(ContentOptionsViewModel model, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/LocalizationPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/LocalizationPartDisplayDriver.cs index 9ed4a6996c1..2b9ed3bfa9a 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/LocalizationPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Drivers/LocalizationPartDisplayDriver.cs @@ -19,11 +19,7 @@ public class LocalizationPartDisplayDriver : ContentPartDisplayDriver c != model.Culture).Select(culture => - { - return new LocalizationLinksViewModel() - { - IsDeleted = false, - Culture = CultureInfo.GetCultureInfo(culture), - ContentItemId = alreadyTranslated.FirstOrDefault(c => c.As()?.Culture == culture)?.ContentItemId, - }; - }).ToList(); + var currentCultures = supportedCultures + .Where(c => c != model.Culture) + .Select(culture => + { + return new LocalizationLinksViewModel() + { + IsDeleted = false, + Culture = CultureInfo.GetCultureInfo(culture), + ContentItemId = alreadyTranslated.FirstOrDefault(c => c.As()?.Culture == culture)?.ContentItemId, + }; + }) + .ToList(); // Content items that have been translated but the culture was removed from the settings page - var deletedCultureTranslations = alreadyTranslated.Where(c => c.As()?.Culture != model.Culture).Select(ci => - { - var culture = ci.As()?.Culture; - if (currentCultures.Any(c => c.ContentItemId == ci.ContentItemId) || culture == null) - { - return null; - } - return new LocalizationLinksViewModel() + var deletedCultureTranslations = alreadyTranslated + .Where(c => c.As()?.Culture != model.Culture) + .Select(ci => { - IsDeleted = true, - Culture = CultureInfo.GetCultureInfo(culture), - ContentItemId = ci?.ContentItemId - }; - }).OfType().ToList(); + var culture = ci.As()?.Culture; + if (currentCultures.Any(c => c.ContentItemId == ci.ContentItemId) || culture == null) + { + return null; + } + return new LocalizationLinksViewModel() + { + IsDeleted = true, + Culture = CultureInfo.GetCultureInfo(culture), + ContentItemId = ci?.ContentItemId + }; + }) + .OfType() + .ToList(); model.ContentItemCultures = currentCultures.Concat(deletedCultureTranslations).ToList(); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Handlers/ContentLocalizationPartHandlerCoordinator.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Handlers/ContentLocalizationPartHandlerCoordinator.cs index 32687dba983..3372eff652f 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Handlers/ContentLocalizationPartHandlerCoordinator.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Handlers/ContentLocalizationPartHandlerCoordinator.cs @@ -15,7 +15,6 @@ internal class ContentLocalizationPartHandlerCoordinator : ContentLocalizationHa private readonly ILogger _logger; public ContentLocalizationPartHandlerCoordinator( - ITypeActivatorFactory contentPartFactory, IEnumerable partHandlers, IContentDefinitionManager contentDefinitionManager, diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Liquid/SwitchCultureUrlFilter.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Liquid/SwitchCultureUrlFilter.cs index 945a3244aaa..85a28576723 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Liquid/SwitchCultureUrlFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Liquid/SwitchCultureUrlFilter.cs @@ -24,19 +24,20 @@ public ValueTask ProcessAsync(FluidValue input, FilterArguments argu { var urlHelper = _urlHelperFactory.GetUrlHelper(context.ViewContext); - var request = _httpContextAccessor.HttpContext?.Request - ?? throw new ArgumentException("HttpRequest missing while invoking 'switch_culture_url'"); + var request = _httpContextAccessor.HttpContext?.Request ?? throw new ArgumentException("HttpRequest missing while invoking 'switch_culture_url'"); var targetCulture = input.ToStringValue(); - var url = urlHelper.RouteUrl("RedirectToLocalizedContent", + var url = urlHelper.RouteUrl( + "RedirectToLocalizedContent", new { area = "OrchardCore.ContentLocalization", targetCulture, contentItemUrl = request.Path.Value, queryStringValue = request.QueryString.Value, - }); + } + ); return new ValueTask(FluidValue.Create(url, context.Options)); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Migrations.cs index 0e1e20217fe..dc7ee160228 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Migrations.cs @@ -22,26 +22,22 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync(nameof(LocalizationPart), builder => builder - .Attachable() - .WithDescription("Provides a way to create localized version of content.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + nameof(LocalizationPart), + builder => builder.Attachable().WithDescription("Provides a way to create localized version of content.") + ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("LocalizationSet", col => col.WithLength(26)) - .Column("Culture", col => col.WithLength(16)) - .Column("ContentItemId", c => c.WithLength(26)) - .Column("Published") - .Column("Latest") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("LocalizationSet", col => col.WithLength(26)) + .Column("Culture", col => col.WithLength(16)) + .Column("ContentItemId", c => c.WithLength(26)) + .Column("Published") + .Column("Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LocalizationPartIndex_DocumentId", - "DocumentId", - "LocalizationSet", - "Culture", - "ContentItemId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_LocalizationPartIndex_DocumentId", "DocumentId", "LocalizationSet", "Culture", "ContentItemId", "Published", "Latest") ); // Shortcut other migration steps on new content definition schemas. @@ -51,8 +47,7 @@ await SchemaBuilder.AlterIndexTableAsync(table => tab // This code can be removed in a later version. public async Task UpdateFrom1Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn(nameof(LocalizedContentItemIndex.Published))); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn(nameof(LocalizedContentItemIndex.Published))); return 2; } @@ -60,18 +55,10 @@ await SchemaBuilder.AlterIndexTableAsync(table => tab // This code can be removed in a later version. public async Task UpdateFrom2Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn(nameof(LocalizedContentItemIndex.Latest)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn(nameof(LocalizedContentItemIndex.Latest))); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LocalizationPartIndex_DocumentId", - "DocumentId", - "LocalizationSet", - "Culture", - "ContentItemId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_LocalizationPartIndex_DocumentId", "DocumentId", "LocalizationSet", "Culture", "ContentItemId", "Published", "Latest") ); return 3; diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Permissions.cs index 4e3d42e6c6b..e74b48fb5e3 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Permissions.cs @@ -10,42 +10,17 @@ public class Permissions : IPermissionProvider public static readonly Permission LocalizeOwnContent = new("LocalizeOwnContent", "Localize own content", new[] { LocalizeContent }); public static readonly Permission ManageContentCulturePicker = new("ManageContentCulturePicker", "Manage ContentCulturePicker settings"); - private readonly IEnumerable _allPermissions = - [ - LocalizeContent, - LocalizeOwnContent, - ManageContentCulturePicker, - ]; + private readonly IEnumerable _allPermissions = [LocalizeContent, LocalizeOwnContent, ManageContentCulturePicker,]; - private readonly IEnumerable _generalPermissions = - [ - LocalizeOwnContent, - ]; + private readonly IEnumerable _generalPermissions = [LocalizeOwnContent,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Author", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Contributor", - Permissions = _generalPermissions, - }, - ]; + [ + new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Editor", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Author", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Contributor", Permissions = _generalPermissions, }, + ]; } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/ServiceCollectionExtensions.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/ServiceCollectionExtensions.cs index 763badabe2e..a8ebd91c023 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/ServiceCollectionExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/ServiceCollectionExtensions.cs @@ -16,9 +16,7 @@ public static class ServiceCollectionExtensions { public static IServiceCollection AddContentLocalization(this IServiceCollection services) { - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.TryAddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/ContentCulturePickerService.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/ContentCulturePickerService.cs index 6ef78e2e22e..84176b60fb6 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/ContentCulturePickerService.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/ContentCulturePickerService.cs @@ -23,7 +23,8 @@ public ContentCulturePickerService( ILocalizationEntries localizationEntries, ISiteService siteService, IHttpContextAccessor httpContextAccessor, - IOptions culturePickerOptions) + IOptions culturePickerOptions + ) { _autorouteEntries = autorouteEntries; _localizationEntries = localizationEntries; diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/IContentCulturePickerService.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/IContentCulturePickerService.cs index 193ed9ef8b1..73e9329120f 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/IContentCulturePickerService.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/IContentCulturePickerService.cs @@ -12,16 +12,19 @@ public interface IContentCulturePickerService /// /// ContentItemId or null if not found. Task GetContentItemIdFromRouteAsync(PathString url); + /// /// Get the Localization of the ContentItem from an url. /// /// Culture or null if not found. Task GetLocalizationFromRouteAsync(PathString url); + /// /// Get the Localizations of the LocalizationSet from a URL. /// /// List of Localization for the url or null if not found. Task> GetLocalizationsFromRouteAsync(PathString url); + /// /// Sets the culture cookie to the target culture. /// diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationEntries.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationEntries.cs index 450ca837b34..3c760bd2911 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationEntries.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationEntries.cs @@ -18,8 +18,7 @@ public class LocalizationEntries : ILocalizationEntries private ImmutableDictionary _localizations = ImmutableDictionary.Empty; - private ImmutableDictionary> _localizationSets = - ImmutableDictionary>.Empty; + private ImmutableDictionary> _localizationSets = ImmutableDictionary>.Empty; private readonly SemaphoreSlim _semaphore = new(1); @@ -135,10 +134,7 @@ private async Task RefreshEntriesAsync(LocalizationStateDocument state) { if (_stateIdentifier != state.Identifier) { - var indexes = await Session - .QueryIndex(i => i.Id > _lastIndexId) - .OrderBy(i => i.Id) - .ListAsync(); + var indexes = await Session.QueryIndex(i => i.Id > _lastIndexId).OrderBy(i => i.Id).ListAsync(); // A draft is indexed to check for conflicts, and to remove an entry, but only if an item is unpublished, // so only if the entry 'DocumentId' matches, this because when a draft is saved more than once, the index @@ -146,17 +142,23 @@ private async Task RefreshEntriesAsync(LocalizationStateDocument state) var entriesToRemove = indexes .Where(i => !i.Published || i.Culture == null) - .SelectMany(i => _localizations.Values.Where(e => - // The item was removed. - ((!i.Published && !i.Latest) || - // The part was removed. - (i.Culture == null && i.Published) || - // The item was unpublished. - (!i.Published && e.DocumentId == i.DocumentId)) && - (e.ContentItemId == i.ContentItemId))); - - var entriesToAdd = indexes. - Where(i => i.Published && i.Culture != null) + .SelectMany(i => + _localizations.Values.Where(e => + // The item was removed. + ( + (!i.Published && !i.Latest) + || + // The part was removed. + (i.Culture == null && i.Published) + || + // The item was unpublished. + (!i.Published && e.DocumentId == i.DocumentId) + ) && (e.ContentItemId == i.ContentItemId) + ) + ); + + var entriesToAdd = indexes + .Where(i => i.Published && i.Culture != null) .Select(i => new LocalizationEntry { DocumentId = i.DocumentId, @@ -192,10 +194,7 @@ protected virtual async Task InitializeEntriesAsync() { var state = await _localizationStateManager.GetOrCreateImmutableAsync(); - var indexes = await Session - .QueryIndex(i => i.Published && i.Culture != null) - .OrderBy(i => i.Id) - .ListAsync(); + var indexes = await Session.QueryIndex(i => i.Published && i.Culture != null).OrderBy(i => i.Id).ListAsync(); var entries = indexes.Select(i => new LocalizationEntry { diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationPartContentsAdminListFilter.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationPartContentsAdminListFilter.cs index 2682fd54750..bd63bd7547e 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationPartContentsAdminListFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationPartContentsAdminListFilter.cs @@ -32,9 +32,7 @@ public async Task FilterAsync(ContentOptionsViewModel model, IQuery if (viewModel.ShowLocalizedContentTypes) { var localizedTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(x => - x.Parts.Any(p => - p.PartDefinition.Name == nameof(LocalizationPart))) + .Where(x => x.Parts.Any(p => p.PartDefinition.Name == nameof(LocalizationPart))) .Select(x => x.Name); query.With(x => x.ContentType.IsIn(localizedTypes)); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationPartContentsAdminListFilterProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationPartContentsAdminListFilterProvider.cs index efe2737a967..83e0e3c4022 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationPartContentsAdminListFilterProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationPartContentsAdminListFilterProvider.cs @@ -10,27 +10,33 @@ public class LocalizationPartContentsAdminListFilterProvider : IContentsAdminLis { public void Build(QueryEngineBuilder builder) { - builder - .WithNamedTerm("culture", builder => builder - .OneCondition((val, query) => - { - if (!string.IsNullOrEmpty(val)) - { - query.With(i => (i.Published || i.Latest) && i.Culture == val); - } + builder.WithNamedTerm( + "culture", + builder => + builder + .OneCondition( + (val, query) => + { + if (!string.IsNullOrEmpty(val)) + { + query.With(i => (i.Published || i.Latest) && i.Culture == val); + } - return query; - }) - .MapTo((val, model) => model.SelectedCulture = val) - .MapFrom((model) => - { - if (!string.IsNullOrEmpty(model.SelectedCulture)) - { - return (true, model.SelectedCulture); - } - return (false, string.Empty); - }) - ); + return query; + } + ) + .MapTo((val, model) => model.SelectedCulture = val) + .MapFrom( + (model) => + { + if (!string.IsNullOrEmpty(model.SelectedCulture)) + { + return (true, model.SelectedCulture); + } + return (false, string.Empty); + } + ) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationStateDocument.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationStateDocument.cs index 37f14d5a46d..94826ecac8d 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationStateDocument.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/LocalizationStateDocument.cs @@ -2,7 +2,5 @@ namespace OrchardCore.ContentLocalization.Services { - public class LocalizationStateDocument : Document - { - } + public class LocalizationStateDocument : Document { } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Sitemaps/LocalizedContentItemsQueryProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Sitemaps/LocalizedContentItemsQueryProvider.cs index 4b7f66dd08a..1fd043ae720 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Sitemaps/LocalizedContentItemsQueryProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Sitemaps/LocalizedContentItemsQueryProvider.cs @@ -19,11 +19,7 @@ public class LocalizedContentItemsQueryProvider : IContentItemsQueryProvider private readonly IRouteableContentTypeCoordinator _routeableContentTypeCoordinator; private readonly ILocalizationService _localizationService; - public LocalizedContentItemsQueryProvider( - ISession session, - IRouteableContentTypeCoordinator routeableContentTypeCoordinator, - ILocalizationService localizationService - ) + public LocalizedContentItemsQueryProvider(ISession session, IRouteableContentTypeCoordinator routeableContentTypeCoordinator, ILocalizationService localizationService) { _session = session; _routeableContentTypeCoordinator = routeableContentTypeCoordinator; @@ -39,7 +35,8 @@ public async Task GetContentItemsAsync(ContentTypesSitemapSource source, Content // Assumption here is that at least one content type will be localized. var ctdNames = routeableContentTypeDefinitions.Select(ctd => ctd.Name); - var queryResults = await _session.Query() + var queryResults = await _session + .Query() .With(x => x.Published && x.ContentType.IsIn(ctdNames)) .OrderBy(x => x.CreatedUtc) .ListAsync(); @@ -47,14 +44,12 @@ public async Task GetContentItemsAsync(ContentTypesSitemapSource source, Content queryContext.ContentItems = queryResults; // Provide all content items with localization as reference content items. - queryContext.ReferenceContentItems = queryResults - .Where(ci => ci.Has()); + queryContext.ReferenceContentItems = queryResults.Where(ci => ci.Has()); } else if (source.LimitItems) { // Test that content type is still valid to include in sitemap. - var contentType = routeableContentTypeDefinitions - .FirstOrDefault(ctd => string.Equals(source.LimitedContentType.ContentTypeName, ctd.Name)); + var contentType = routeableContentTypeDefinitions.FirstOrDefault(ctd => string.Equals(source.LimitedContentType.ContentTypeName, ctd.Name)); if (contentType == null) { @@ -66,11 +61,12 @@ public async Task GetContentItemsAsync(ContentTypesSitemapSource source, Content // Get all content items here for reference. Then reduce by default culture. // We know that the content item should be localized. // If it doesn't have a localization part, the content item should have been saved. - var queryResults = await _session.Query() - .With(ci => ci.ContentType == source.LimitedContentType.ContentTypeName && ci.Published) - .OrderBy(ci => ci.CreatedUtc) - .With() - .ListAsync(); + var queryResults = await _session + .Query() + .With(ci => ci.ContentType == source.LimitedContentType.ContentTypeName && ci.Published) + .OrderBy(ci => ci.CreatedUtc) + .With() + .ListAsync(); // When limiting items Content item is valid if it is for the default culture. var defaultCulture = await _localizationService.GetDefaultCultureAsync(); @@ -84,13 +80,13 @@ public async Task GetContentItemsAsync(ContentTypesSitemapSource source, Content queryContext.ContentItems = items; // Provide all content items with localization as reference content items. - queryContext.ReferenceContentItems = queryResults - .Where(ci => ci.Has()); + queryContext.ReferenceContentItems = queryResults.Where(ci => ci.Has()); } else { // Content type is not localized. Produce standard results. - var queryResults = await _session.Query() + var queryResults = await _session + .Query() .With(x => x.ContentType == source.LimitedContentType.ContentTypeName && x.Published) .OrderBy(x => x.CreatedUtc) .Skip(source.LimitedContentType.Skip) @@ -103,12 +99,11 @@ public async Task GetContentItemsAsync(ContentTypesSitemapSource source, Content else { // Test that content types are still valid to include in sitemap. - var typesToIndex = routeableContentTypeDefinitions - .Where(ctd => source.ContentTypes.Any(s => string.Equals(ctd.Name, s.ContentTypeName))) - .Select(x => x.Name); + var typesToIndex = routeableContentTypeDefinitions.Where(ctd => source.ContentTypes.Any(s => string.Equals(ctd.Name, s.ContentTypeName))).Select(x => x.Name); // No advantage here in reducing with localized index. - var queryResults = await _session.Query() + var queryResults = await _session + .Query() .With(x => x.ContentType.IsIn(typesToIndex) && x.Published) .OrderBy(x => x.CreatedUtc) .ListAsync(); @@ -116,8 +111,7 @@ public async Task GetContentItemsAsync(ContentTypesSitemapSource source, Content queryContext.ContentItems = queryResults; // Provide all content items with localization as reference content items. - queryContext.ReferenceContentItems = queryResults - .Where(ci => ci.Has()); + queryContext.ReferenceContentItems = queryResults.Where(ci => ci.Has()); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Sitemaps/SitemapUrlHrefLangExtendedMetadataProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Sitemaps/SitemapUrlHrefLangExtendedMetadataProvider.cs index 6f04a469a5a..93b140ba8c8 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Sitemaps/SitemapUrlHrefLangExtendedMetadataProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Sitemaps/SitemapUrlHrefLangExtendedMetadataProvider.cs @@ -17,10 +17,7 @@ public class SitemapUrlHrefLangExtendedMetadataProvider : ISitemapContentItemExt private readonly IContentManager _contentManager; private readonly IRouteableContentTypeCoordinator _routeableContentTypeCoordinator; - public SitemapUrlHrefLangExtendedMetadataProvider( - IContentManager contentManager, - IRouteableContentTypeCoordinator routeableContentTypeCoordinator - ) + public SitemapUrlHrefLangExtendedMetadataProvider(IContentManager contentManager, IRouteableContentTypeCoordinator routeableContentTypeCoordinator) { _contentManager = contentManager; _routeableContentTypeCoordinator = routeableContentTypeCoordinator; @@ -28,11 +25,7 @@ IRouteableContentTypeCoordinator routeableContentTypeCoordinator public XAttribute GetExtendedAttribute => _extendedAttribute; - public async Task ApplyExtendedMetadataAsync( - SitemapBuilderContext context, - ContentItemsQueryContext queryContext, - ContentItem contentItem, - XElement url) + public async Task ApplyExtendedMetadataAsync(SitemapBuilderContext context, ContentItemsQueryContext queryContext, ContentItem contentItem, XElement url) { var part = contentItem.As(); if (part == null) @@ -40,9 +33,7 @@ public async Task ApplyExtendedMetadataAsync( return true; } - var localizedContentParts = queryContext.ReferenceContentItems - .Select(ci => ci.As()) - .Where(cp => cp.LocalizationSet == part.LocalizationSet); + var localizedContentParts = queryContext.ReferenceContentItems.Select(ci => ci.As()).Where(cp => cp.LocalizationSet == part.LocalizationSet); foreach (var localizedPart in localizedContentParts) { @@ -54,10 +45,12 @@ public async Task ApplyExtendedMetadataAsync( var hrefValue = await _routeableContentTypeCoordinator.GetRouteAsync(context, localizedPart.ContentItem); - var linkNode = new XElement(_extendedNamespace + "link", + var linkNode = new XElement( + _extendedNamespace + "link", new XAttribute("rel", "alternate"), new XAttribute("hreflang", localizedPart.Culture), - new XAttribute("href", hrefValue)); + new XAttribute("href", hrefValue) + ); url.Add(linkNode); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Startup.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Startup.cs index 1e465f9c8a2..093f63dc20d 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/Startup.cs @@ -1,3 +1,5 @@ +using System; +using System.Globalization; using Fluid; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; @@ -23,8 +25,6 @@ using OrchardCore.Security.Permissions; using OrchardCore.Settings; using OrchardCore.Sitemaps.Builders; -using System; -using System.Globalization; namespace OrchardCore.ContentLocalization { @@ -32,12 +32,13 @@ public class Startup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.Configure(o => - { - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - }) - .AddLiquidFilter("localization_set"); + services + .Configure(o => + { + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); + }) + .AddLiquidFilter("localization_set"); services.AddScoped(); services.AddSingleton(); @@ -56,6 +57,7 @@ public override void ConfigureServices(IServiceCollection services) public class ContentPickerStartup : StartupBase { private readonly IShellConfiguration _shellConfiguration; + public ContentPickerStartup(IShellConfiguration shellConfiguration) { _shellConfiguration = shellConfiguration; @@ -76,11 +78,11 @@ public override void ConfigureServices(IServiceCollection services) public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { routes.MapAreaControllerRoute( - name: "RedirectToLocalizedContent", - areaName: "OrchardCore.ContentLocalization", - pattern: "RedirectToLocalizedContent", - defaults: new { controller = "ContentCulturePicker", action = "RedirectToLocalizedContent" } - ); + name: "RedirectToLocalizedContent", + areaName: "OrchardCore.ContentLocalization", + pattern: "RedirectToLocalizedContent", + defaults: new { controller = "ContentCulturePicker", action = "RedirectToLocalizedContent" } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/ViewModels/LocalizationPartViewModel.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/ViewModels/LocalizationPartViewModel.cs index 842fb531dde..cc783589ec1 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/ViewModels/LocalizationPartViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/ViewModels/LocalizationPartViewModel.cs @@ -12,7 +12,10 @@ public class LocalizationPartViewModel : ShapeViewModel public string Culture { get; set; } [BindNever] - public CultureInfo CultureInfo { get { return new CultureInfo(Culture); } } + public CultureInfo CultureInfo + { + get { return new CultureInfo(Culture); } + } [BindNever] public LocalizationPart LocalizationPart { get; set; } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Controllers/PreviewController.cs b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Controllers/PreviewController.cs index db53aebb116..2e85c18f303 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Controllers/PreviewController.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Controllers/PreviewController.cs @@ -29,7 +29,8 @@ public PreviewController( IContentManagerSession contentManagerSession, IAuthorizationService authorizationService, IClock clock, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _authorizationService = authorizationService; _clock = clock; @@ -133,10 +134,7 @@ public static string GetModelErrorMessageOrDefault(ModelError modelError) return string.Empty; } - public static string GetModelErrorMessageOrDefault( - ModelError modelError, - ModelStateEntry containingEntry, - ModelExplorer modelExplorer) + public static string GetModelErrorMessageOrDefault(ModelError modelError, ModelStateEntry containingEntry, ModelExplorer modelExplorer) { Debug.Assert(modelError != null); Debug.Assert(containingEntry != null); @@ -153,9 +151,7 @@ public static string GetModelErrorMessageOrDefault( } // Returns non-null list of model states, which caller will render in order provided. - public static IList GetModelStateList( - ViewDataDictionary viewData, - bool excludePropertyErrors) + public static IList GetModelStateList(ViewDataDictionary viewData, bool excludePropertyErrors) { if (excludePropertyErrors) { @@ -191,10 +187,7 @@ public static IList GetModelStateList( return Array.Empty(); } - private static void Visit( - ModelStateEntry modelStateEntry, - ModelMetadata metadata, - List orderedModelStateEntries) + private static void Visit(ModelStateEntry modelStateEntry, ModelMetadata metadata, List orderedModelStateEntries) { if (metadata.ElementMetadata != null && modelStateEntry.Children != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Handlers/PreviewPartHandler.cs b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Handlers/PreviewPartHandler.cs index 115c7a922e5..01c526d30d8 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Handlers/PreviewPartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Handlers/PreviewPartHandler.cs @@ -17,9 +17,7 @@ public class PreviewPartHandler : ContentPartHandler private readonly ILiquidTemplateManager _liquidTemplateManager; private readonly IContentDefinitionManager _contentDefinitionManager; - public PreviewPartHandler( - ILiquidTemplateManager liquidTemplateManager, - IContentDefinitionManager contentDefinitionManager) + public PreviewPartHandler(ILiquidTemplateManager liquidTemplateManager, IContentDefinitionManager contentDefinitionManager) { _liquidTemplateManager = liquidTemplateManager; _contentDefinitionManager = contentDefinitionManager; @@ -45,14 +43,14 @@ public override async Task GetContentItemAspectAsync(ContentItemAspectContext co { await context.ForAsync(async previewAspect => { - var model = new PreviewPartViewModel() - { - PreviewPart = part, - ContentItem = part.ContentItem, - }; - - previewAspect.PreviewUrl = await _liquidTemplateManager.RenderStringAsync(pattern, NullEncoder.Default, model, - new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) }); + var model = new PreviewPartViewModel() { PreviewPart = part, ContentItem = part.ContentItem, }; + + previewAspect.PreviewUrl = await _liquidTemplateManager.RenderStringAsync( + pattern, + NullEncoder.Default, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); previewAspect.PreviewUrl = previewAspect.PreviewUrl.Replace("\r", string.Empty).Replace("\n", string.Empty); }); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Migrations.cs index 9abbb8ddc87..b5af1b6290a 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Migrations.cs @@ -16,9 +16,15 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("PreviewPart", builder => builder - .Attachable() - .WithDescription("Provides a way to define the url that is used to render your content item for preview. You only need to use this for the content preview feature when running the frontend decoupled from the admin.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "PreviewPart", + builder => + builder + .Attachable() + .WithDescription( + "Provides a way to define the url that is used to render your content item for preview. You only need to use this for the content preview feature when running the frontend decoupled from the admin." + ) + ); return 1; } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Models/PreviewPart.cs b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Models/PreviewPart.cs index 12bebdbf993..f9e732e82ae 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Models/PreviewPart.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Models/PreviewPart.cs @@ -6,7 +6,5 @@ namespace OrchardCore.ContentPreview.Models /// When attached to a content type, provides a way to define the /// url that is used to render the content item. /// - public class PreviewPart : ContentPart - { - } + public class PreviewPart : ContentPart { } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentPreview/PreviewStartupFilter.cs b/src/OrchardCore.Modules/OrchardCore.ContentPreview/PreviewStartupFilter.cs index 3e2eedd5cb7..867cbf2a6c3 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentPreview/PreviewStartupFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentPreview/PreviewStartupFilter.cs @@ -11,39 +11,41 @@ public Action Configure(Action next) { return app => { - app.Use(async (context, next) => - { - await next(); - - if (!context.Items.TryGetValue("PreviewPath", out var previewPathObject) || previewPathObject == null) - { - return; - } - - var previewPath = previewPathObject.ToString(); - - if (!string.IsNullOrWhiteSpace(previewPath) && previewPath.StartsWith('/')) + app.Use( + async (context, next) => { - var originalPath = context.Request.Path; - var originalQueryString = context.Request.QueryString; + await next(); - context.Request.Path = previewPath; - context.Items.Remove("PreviewPath"); - - context.SetEndpoint(endpoint: null); - context.Request.RouteValues.Clear(); - - try + if (!context.Items.TryGetValue("PreviewPath", out var previewPathObject) || previewPathObject == null) { - await next(); + return; } - finally + + var previewPath = previewPathObject.ToString(); + + if (!string.IsNullOrWhiteSpace(previewPath) && previewPath.StartsWith('/')) { - context.Request.QueryString = originalQueryString; - context.Request.Path = originalPath; + var originalPath = context.Request.Path; + var originalQueryString = context.Request.QueryString; + + context.Request.Path = previewPath; + context.Items.Remove("PreviewPath"); + + context.SetEndpoint(endpoint: null); + context.Request.RouteValues.Clear(); + + try + { + await next(); + } + finally + { + context.Request.QueryString = originalQueryString; + context.Request.Path = originalPath; + } } } - }); + ); next(app); }; diff --git a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Settings/PreviewPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Settings/PreviewPartSettingsDisplayDriver.cs index 49eeaada535..3a264e9fc41 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Settings/PreviewPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Settings/PreviewPartSettingsDisplayDriver.cs @@ -23,22 +23,24 @@ public PreviewPartSettingsDisplayDriver(ILiquidTemplateManager templateManager, public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("PreviewPartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); - - model.Pattern = settings.Pattern; - model.PreviewPartSettings = settings; - }).Location("Content"); + return Initialize( + "PreviewPartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); + + model.Pattern = settings.Pattern; + model.PreviewPartSettings = settings; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) { var model = new PreviewPartSettingsViewModel(); - await context.Updater.TryUpdateModelAsync(model, Prefix, - m => m.Pattern - ); + await context.Updater.TryUpdateModelAsync(model, Prefix, m => m.Pattern); if (!string.IsNullOrEmpty(model.Pattern) && !_templateManager.Validate(model.Pattern, out var errors)) { @@ -46,10 +48,7 @@ await context.Updater.TryUpdateModelAsync(model, Prefix, } else { - context.Builder.WithSettings(new PreviewPartSettings - { - Pattern = model.Pattern - }); + context.Builder.WithSettings(new PreviewPartSettings { Pattern = model.Pattern }); } return Edit(contentTypePartDefinition, context.Updater); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Startup.cs b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Startup.cs index b1d805463c8..fd39f26b1bd 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentPreview/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentPreview/Startup.cs @@ -23,8 +23,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); // Preview Part - services.AddContentPart() - .AddHandler(); + services.AddContentPart().AddHandler(); services.AddDataMigration(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/AdminMenu.cs index f6bc91032ad..d1d71b58fbc 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/AdminMenu.cs @@ -24,21 +24,34 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Content"], content => content - .Add(S["Content Definition"], S["Content Definition"].PrefixPosition("9"), contentDefinition => contentDefinition - .Add(S["Content Types"], S["Content Types"].PrefixPosition("1"), contentTypes => contentTypes - .Action(nameof(AdminController.List), _adminControllerName, "OrchardCore.ContentTypes") - .Permission(Permissions.ViewContentTypes) - .LocalNav() - ) - .Add(S["Content Parts"], S["Content Parts"].PrefixPosition("2"), contentParts => contentParts - .Action(nameof(AdminController.ListParts), _adminControllerName, "OrchardCore.ContentTypes") - .Permission(Permissions.ViewContentTypes) - .LocalNav() - ) + builder.Add( + S["Content"], + content => + content.Add( + S["Content Definition"], + S["Content Definition"].PrefixPosition("9"), + contentDefinition => + contentDefinition + .Add( + S["Content Types"], + S["Content Types"].PrefixPosition("1"), + contentTypes => + contentTypes + .Action(nameof(AdminController.List), _adminControllerName, "OrchardCore.ContentTypes") + .Permission(Permissions.ViewContentTypes) + .LocalNav() + ) + .Add( + S["Content Parts"], + S["Content Parts"].PrefixPosition("2"), + contentParts => + contentParts + .Action(nameof(AdminController.ListParts), _adminControllerName, "OrchardCore.ContentTypes") + .Permission(Permissions.ViewContentTypes) + .LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Controllers/AdminController.cs index 7fd9f421fb5..e37a50991b1 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Controllers/AdminController.cs @@ -42,7 +42,8 @@ public AdminController( IHtmlLocalizer htmlLocalizer, IStringLocalizer stringLocalizer, INotifier notifier, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _notifier = notifier; _contentDefinitionDisplayManager = contentDefinitionDisplayManager; @@ -71,10 +72,7 @@ public async Task List() return Forbid(); } - return View("List", new ListContentTypesViewModel - { - Types = await _contentDefinitionService.GetTypesAsync() - }); + return View("List", new ListContentTypesViewModel { Types = await _contentDefinitionService.GetTypesAsync() }); } [Admin("ContentTypes/Create", "CreateType")] @@ -255,8 +253,17 @@ public async Task AddPartsTo(string id) { Type = typeViewModel, PartSelections = (await _contentDefinitionService.GetPartsAsync(metadataPartsOnly: false)) - .Where(cpd => !typePartNames.Contains(cpd.Name, StringComparer.OrdinalIgnoreCase) && cpd.PartDefinition != null && cpd.PartDefinition.GetSettings().Attachable) - .Select(cpd => new PartSelectionViewModel { PartName = cpd.Name, PartDisplayName = cpd.DisplayName, PartDescription = cpd.Description }) + .Where(cpd => + !typePartNames.Contains(cpd.Name, StringComparer.OrdinalIgnoreCase) + && cpd.PartDefinition != null + && cpd.PartDefinition.GetSettings().Attachable + ) + .Select(cpd => new PartSelectionViewModel + { + PartName = cpd.Name, + PartDisplayName = cpd.DisplayName, + PartDescription = cpd.Description + }) .ToList() }; @@ -278,16 +285,20 @@ public async Task AddReusablePartTo(string id) return NotFound(); } - var reusableParts = (await _contentDefinitionService.GetPartsAsync(metadataPartsOnly: false)) - .Where(cpd => cpd.PartDefinition != null && - cpd.PartDefinition.GetSettings().Attachable && - cpd.PartDefinition.GetSettings().Reusable); + var reusableParts = (await _contentDefinitionService.GetPartsAsync(metadataPartsOnly: false)).Where(cpd => + cpd.PartDefinition != null && cpd.PartDefinition.GetSettings().Attachable && cpd.PartDefinition.GetSettings().Reusable + ); var viewModel = new AddReusablePartViewModel { Type = typeViewModel, PartSelections = reusableParts - .Select(cpd => new PartSelectionViewModel { PartName = cpd.Name, PartDisplayName = cpd.DisplayName, PartDescription = cpd.Description }) + .Select(cpd => new PartSelectionViewModel + { + PartName = cpd.Name, + PartDisplayName = cpd.DisplayName, + PartDescription = cpd.Description + }) .ToList(), SelectedPartName = reusableParts.FirstOrDefault()?.Name }; @@ -441,11 +452,15 @@ public async Task ListParts() return Forbid(); } - return View(new ListContentPartsViewModel - { - // only user-defined parts (not code as they are not configurable) - Parts = await _contentDefinitionService.GetPartsAsync(true/*metadataPartsOnly*/) - }); + return View( + new ListContentPartsViewModel + { + // only user-defined parts (not code as they are not configurable) + Parts = await _contentDefinitionService.GetPartsAsync( + true /*metadataPartsOnly*/ + ) + } + ); } [Admin("ContentParts/Create", "CreatePart")] @@ -617,11 +632,7 @@ public async Task AddFieldTo(string id, string returnUrl = null) return NotFound(); } - var viewModel = new AddFieldViewModel - { - Part = partViewModel.PartDefinition, - Fields = fields.Select(field => field.Name).OrderBy(name => name).ToList() - }; + var viewModel = new AddFieldViewModel { Part = partViewModel.PartDefinition, Fields = fields.Select(field => field.Name).OrderBy(name => name).ToList() }; ViewData["ReturnUrl"] = returnUrl; return View(viewModel); @@ -726,8 +737,12 @@ public async Task EditField(string id, string name, string returnU var partFieldDefinition = partViewModel.PartDefinition.Fields.FirstOrDefault(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)); - if (partFieldDefinition?.FieldDefinition?.Name == null - || !(await _contentDefinitionService.GetFieldsAsync()).Any(field => string.Equals(field.Name, partFieldDefinition.FieldDefinition.Name, StringComparison.OrdinalIgnoreCase))) + if ( + partFieldDefinition?.FieldDefinition?.Name == null + || !(await _contentDefinitionService.GetFieldsAsync()).Any(field => + string.Equals(field.Name, partFieldDefinition.FieldDefinition.Name, StringComparison.OrdinalIgnoreCase) + ) + ) { return NotFound(); } @@ -767,7 +782,9 @@ public async Task EditFieldPOST(string id, EditFieldViewModel view return NotFound(); } - var field = (await _contentDefinitionManager.LoadPartDefinitionAsync(id)).Fields.FirstOrDefault(x => string.Equals(x.Name, viewModel.Name, StringComparison.OrdinalIgnoreCase)); + var field = (await _contentDefinitionManager.LoadPartDefinitionAsync(id)).Fields.FirstOrDefault(x => + string.Equals(x.Name, viewModel.Name, StringComparison.OrdinalIgnoreCase) + ); if (field == null) { @@ -786,7 +803,11 @@ public async Task EditFieldPOST(string id, EditFieldViewModel view ModelState.AddModelError("DisplayName", S["The Display Name can't be empty."]); } - if ((await _contentDefinitionService.LoadPartAsync(partViewModel.Name)).PartDefinition.Fields.Any(t => t.Name != viewModel.Name && string.Equals(t.DisplayName().Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase))) + if ( + (await _contentDefinitionService.LoadPartAsync(partViewModel.Name)).PartDefinition.Fields.Any(t => + t.Name != viewModel.Name && string.Equals(t.DisplayName().Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase) + ) + ) { ModelState.AddModelError("DisplayName", S["A field with the same Display Name already exists."]); } @@ -807,7 +828,9 @@ public async Task EditFieldPOST(string id, EditFieldViewModel view await _contentDefinitionService.AlterFieldAsync(partViewModel, viewModel); // Refresh the local field variable in case it has been altered - field = (await _contentDefinitionManager.LoadPartDefinitionAsync(id)).Fields.FirstOrDefault(x => string.Equals(x.Name, viewModel.Name, StringComparison.OrdinalIgnoreCase)); + field = (await _contentDefinitionManager.LoadPartDefinitionAsync(id)).Fields.FirstOrDefault(x => + string.Equals(x.Name, viewModel.Name, StringComparison.OrdinalIgnoreCase) + ); viewModel.Shape = await _contentDefinitionDisplayManager.UpdatePartFieldEditorAsync(field, _updateModelAccessor.ModelUpdater); @@ -956,7 +979,11 @@ public async Task EditTypePartPOST(string id, EditTypePartViewMode ModelState.AddModelError("DisplayName", S["The Display Name can't be empty."]); } - if (typeDefinition.Parts.Any(t => t.Name != viewModel.Name && string.Equals(t.DisplayName()?.Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase))) + if ( + typeDefinition.Parts.Any(t => + t.Name != viewModel.Name && string.Equals(t.DisplayName()?.Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase) + ) + ) { ModelState.AddModelError("DisplayName", S["A part with the same Display Name already exists."]); } @@ -973,7 +1000,9 @@ public async Task EditTypePartPOST(string id, EditTypePartViewMode await _contentDefinitionService.AlterTypePartAsync(viewModel); // Refresh the local part variable in case it has been altered - part = (await _contentDefinitionManager.LoadTypeDefinitionAsync(id)).Parts.FirstOrDefault(x => string.Equals(x.Name, viewModel.Name, StringComparison.OrdinalIgnoreCase)); + part = (await _contentDefinitionManager.LoadTypeDefinitionAsync(id)).Parts.FirstOrDefault(x => + string.Equals(x.Name, viewModel.Name, StringComparison.OrdinalIgnoreCase) + ); viewModel.Shape = await _contentDefinitionDisplayManager.UpdateTypePartEditorAsync(part, _updateModelAccessor.ModelUpdater); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ContentDefinitionDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ContentDefinitionDeploymentSource.cs index 2f88284061e..7178480692b 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ContentDefinitionDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ContentDefinitionDeploymentSource.cs @@ -26,20 +26,20 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan var contentTypes = contentDefinitionStep.IncludeAll ? contentTypeDefinitionRecord.ContentTypeDefinitionRecords - : contentTypeDefinitionRecord.ContentTypeDefinitionRecords - .Where(x => contentDefinitionStep.ContentTypes.Contains(x.Name)); + : contentTypeDefinitionRecord.ContentTypeDefinitionRecords.Where(x => contentDefinitionStep.ContentTypes.Contains(x.Name)); var contentParts = contentDefinitionStep.IncludeAll ? contentTypeDefinitionRecord.ContentPartDefinitionRecords - : contentTypeDefinitionRecord.ContentPartDefinitionRecords - .Where(x => contentDefinitionStep.ContentParts.Contains(x.Name)); + : contentTypeDefinitionRecord.ContentPartDefinitionRecords.Where(x => contentDefinitionStep.ContentParts.Contains(x.Name)); - result.Steps.Add(new JsonObject - { - ["name"] = "ContentDefinition", - ["ContentTypes"] = JArray.FromObject(contentTypes), - ["ContentParts"] = JArray.FromObject(contentParts), - }); + result.Steps.Add( + new JsonObject + { + ["name"] = "ContentDefinition", + ["ContentTypes"] = JArray.FromObject(contentTypes), + ["ContentParts"] = JArray.FromObject(contentParts), + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ContentDefinitionDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ContentDefinitionDeploymentStepDriver.cs index 47d03252e43..2ce4eade48b 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ContentDefinitionDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ContentDefinitionDeploymentStepDriver.cs @@ -12,21 +12,24 @@ public class ContentDefinitionDeploymentStepDriver : DisplayDriver("ContentDefinitionDeploymentStep_Fields_Edit", model => - { - model.ContentParts = step.ContentParts; - model.ContentTypes = step.ContentTypes; - model.IncludeAll = step.IncludeAll; - }).Location("Content"); + return Initialize( + "ContentDefinitionDeploymentStep_Fields_Edit", + model => + { + model.ContentParts = step.ContentParts; + model.ContentTypes = step.ContentTypes; + model.IncludeAll = step.IncludeAll; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentDefinitionDeploymentStep step, IUpdateModel updater) @@ -35,12 +38,7 @@ public override async Task UpdateAsync(ContentDefinitionDeployme step.ContentTypes = []; step.ContentParts = []; - await updater.TryUpdateModelAsync( - step, - Prefix, - x => x.ContentTypes, - x => x.ContentParts, - x => x.IncludeAll); + await updater.TryUpdateModelAsync(step, Prefix, x => x.ContentTypes, x => x.ContentParts, x => x.IncludeAll); // don't have the selected option if include all if (step.IncludeAll) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/DeleteContentDefinitionDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/DeleteContentDefinitionDeploymentSource.cs index b54de8c1e0c..3004452ed05 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/DeleteContentDefinitionDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/DeleteContentDefinitionDeploymentSource.cs @@ -13,12 +13,14 @@ public Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult return Task.CompletedTask; } - result.Steps.Add(new JsonObject - { - ["name"] = "DeleteContentDefinition", - ["ContentTypes"] = JArray.FromObject(deleteContentDefinitionStep.ContentTypes), - ["ContentParts"] = JArray.FromObject(deleteContentDefinitionStep.ContentParts), - }); + result.Steps.Add( + new JsonObject + { + ["name"] = "DeleteContentDefinition", + ["ContentTypes"] = JArray.FromObject(deleteContentDefinitionStep.ContentTypes), + ["ContentParts"] = JArray.FromObject(deleteContentDefinitionStep.ContentParts), + } + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/DeleteContentDefinitionDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/DeleteContentDefinitionDeploymentStepDriver.cs index 06d6003beb1..7cf363c5bab 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/DeleteContentDefinitionDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/DeleteContentDefinitionDeploymentStepDriver.cs @@ -14,20 +14,23 @@ public class DeleteContentDefinitionDeploymentStepDriver : DisplayDriver("DeleteContentDefinitionDeploymentStep_Fields_Edit", model => - { - model.ContentParts = string.Join(", ", step.ContentParts); - model.ContentTypes = string.Join(", ", step.ContentTypes); - }).Location("Content"); + return Initialize( + "DeleteContentDefinitionDeploymentStep_Fields_Edit", + model => + { + model.ContentParts = string.Join(", ", step.ContentParts); + model.ContentTypes = string.Join(", ", step.ContentTypes); + } + ) + .Location("Content"); } public override async Task UpdateAsync(DeleteContentDefinitionDeploymentStep step, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ReplaceContentDefinitionDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ReplaceContentDefinitionDeploymentSource.cs index 0b35e8c324d..f94cb276d35 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ReplaceContentDefinitionDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ReplaceContentDefinitionDeploymentSource.cs @@ -26,20 +26,20 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan var contentTypes = replaceContentDefinitionStep.IncludeAll ? contentTypeDefinitionRecord.ContentTypeDefinitionRecords - : contentTypeDefinitionRecord.ContentTypeDefinitionRecords - .Where(x => replaceContentDefinitionStep.ContentTypes.Contains(x.Name)); + : contentTypeDefinitionRecord.ContentTypeDefinitionRecords.Where(x => replaceContentDefinitionStep.ContentTypes.Contains(x.Name)); var contentParts = replaceContentDefinitionStep.IncludeAll ? contentTypeDefinitionRecord.ContentPartDefinitionRecords - : contentTypeDefinitionRecord.ContentPartDefinitionRecords - .Where(x => replaceContentDefinitionStep.ContentParts.Contains(x.Name)); + : contentTypeDefinitionRecord.ContentPartDefinitionRecords.Where(x => replaceContentDefinitionStep.ContentParts.Contains(x.Name)); - result.Steps.Add(new JsonObject - { - ["name"] = "ReplaceContentDefinition", - ["ContentTypes"] = JArray.FromObject(contentTypes), - ["ContentParts"] = JArray.FromObject(contentParts), - }); + result.Steps.Add( + new JsonObject + { + ["name"] = "ReplaceContentDefinition", + ["ContentTypes"] = JArray.FromObject(contentTypes), + ["ContentParts"] = JArray.FromObject(contentParts), + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ReplaceContentDefinitionDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ReplaceContentDefinitionDeploymentStepDriver.cs index b6c73a34cf5..2ad6c32d548 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ReplaceContentDefinitionDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Deployment/ReplaceContentDefinitionDeploymentStepDriver.cs @@ -12,21 +12,24 @@ public class ReplaceContentDefinitionDeploymentStepDriver : DisplayDriver("ReplaceContentDefinitionDeploymentStep_Fields_Edit", model => - { - model.ContentParts = step.ContentParts; - model.ContentTypes = step.ContentTypes; - model.IncludeAll = step.IncludeAll; - }).Location("Content"); + return Initialize( + "ReplaceContentDefinitionDeploymentStep_Fields_Edit", + model => + { + model.ContentParts = step.ContentParts; + model.ContentTypes = step.ContentTypes; + model.IncludeAll = step.IncludeAll; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ReplaceContentDefinitionDeploymentStep step, IUpdateModel updater) @@ -35,12 +38,7 @@ public override async Task UpdateAsync(ReplaceContentDefinitionD step.ContentTypes = []; step.ContentParts = []; - await updater.TryUpdateModelAsync( - step, - Prefix, - x => x.ContentTypes, - x => x.ContentParts, - x => x.IncludeAll); + await updater.TryUpdateModelAsync(step, Prefix, x => x.ContentTypes, x => x.ContentParts, x => x.IncludeAll); // don't have the selected option if include all if (step.IncludeAll) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentDefinitionDisplayCoordinator.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentDefinitionDisplayCoordinator.cs index e0489fd525b..93541e9bd32 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentDefinitionDisplayCoordinator.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentDefinitionDisplayCoordinator.cs @@ -20,7 +20,8 @@ public ContentDefinitionDisplayCoordinator( IEnumerable typePartDisplayDrivers, IEnumerable partDisplayDrivers, IEnumerable partFieldDisplayDrivers, - ILogger logger) + ILogger logger + ) { _partFieldDisplayDrivers = partFieldDisplayDrivers; _partDisplayDrivers = partDisplayDrivers; @@ -31,82 +32,122 @@ public ContentDefinitionDisplayCoordinator( public Task BuildTypeEditorAsync(ContentTypeDefinition model, BuildEditorContext context) { - return _typeDisplayDrivers.InvokeAsync(async (contentDisplay, model, context) => - { - var result = await contentDisplay.BuildEditorAsync(model, context); - if (result != null) - await result.ApplyAsync(context); - }, model, context, _logger); + return _typeDisplayDrivers.InvokeAsync( + async (contentDisplay, model, context) => + { + var result = await contentDisplay.BuildEditorAsync(model, context); + if (result != null) + await result.ApplyAsync(context); + }, + model, + context, + _logger + ); } public Task UpdateTypeEditorAsync(ContentTypeDefinition model, UpdateTypeEditorContext context) { - return _typeDisplayDrivers.InvokeAsync(async (contentDisplay, model, context) => - { - var result = await contentDisplay.UpdateEditorAsync(model, context); - if (result != null) - await result.ApplyAsync(context); - }, model, context, _logger); + return _typeDisplayDrivers.InvokeAsync( + async (contentDisplay, model, context) => + { + var result = await contentDisplay.UpdateEditorAsync(model, context); + if (result != null) + await result.ApplyAsync(context); + }, + model, + context, + _logger + ); } public Task BuildTypePartEditorAsync(ContentTypePartDefinition model, BuildEditorContext context) { - return _typePartDisplayDrivers.InvokeAsync(async (contentDisplay, model, context) => - { - var result = await contentDisplay.BuildEditorAsync(model, context); - if (result != null) - await result.ApplyAsync(context); - }, model, context, _logger); + return _typePartDisplayDrivers.InvokeAsync( + async (contentDisplay, model, context) => + { + var result = await contentDisplay.BuildEditorAsync(model, context); + if (result != null) + await result.ApplyAsync(context); + }, + model, + context, + _logger + ); } public Task UpdateTypePartEditorAsync(ContentTypePartDefinition model, UpdateTypePartEditorContext context) { - return _typePartDisplayDrivers.InvokeAsync(async (contentDisplay, model, context) => - { - var result = await contentDisplay.UpdateEditorAsync(model, context); - if (result != null) - await result.ApplyAsync(context); - }, model, context, _logger); + return _typePartDisplayDrivers.InvokeAsync( + async (contentDisplay, model, context) => + { + var result = await contentDisplay.UpdateEditorAsync(model, context); + if (result != null) + await result.ApplyAsync(context); + }, + model, + context, + _logger + ); } public Task BuildPartEditorAsync(ContentPartDefinition model, BuildEditorContext context) { - return _partDisplayDrivers.InvokeAsync(async (contentDisplay, model, context) => - { - var result = await contentDisplay.BuildEditorAsync(model, context); - if (result != null) - await result.ApplyAsync(context); - }, model, context, _logger); + return _partDisplayDrivers.InvokeAsync( + async (contentDisplay, model, context) => + { + var result = await contentDisplay.BuildEditorAsync(model, context); + if (result != null) + await result.ApplyAsync(context); + }, + model, + context, + _logger + ); } public Task UpdatePartEditorAsync(ContentPartDefinition model, UpdatePartEditorContext context) { - return _partDisplayDrivers.InvokeAsync(async (contentDisplay, model, context) => - { - var result = await contentDisplay.UpdateEditorAsync(model, context); - if (result != null) - await result.ApplyAsync(context); - }, model, context, _logger); + return _partDisplayDrivers.InvokeAsync( + async (contentDisplay, model, context) => + { + var result = await contentDisplay.UpdateEditorAsync(model, context); + if (result != null) + await result.ApplyAsync(context); + }, + model, + context, + _logger + ); } public async Task BuildPartFieldEditorAsync(ContentPartFieldDefinition model, BuildEditorContext context) { - await _partFieldDisplayDrivers.InvokeAsync(async (contentDisplay, model, context) => - { - var result = await contentDisplay.BuildEditorAsync(model, context); - if (result != null) - await result.ApplyAsync(context); - }, model, context, _logger); + await _partFieldDisplayDrivers.InvokeAsync( + async (contentDisplay, model, context) => + { + var result = await contentDisplay.BuildEditorAsync(model, context); + if (result != null) + await result.ApplyAsync(context); + }, + model, + context, + _logger + ); } public async Task UpdatePartFieldEditorAsync(ContentPartFieldDefinition model, UpdatePartFieldEditorContext context) { - await _partFieldDisplayDrivers.InvokeAsync(async (contentDisplay, model, context) => - { - var result = await contentDisplay.UpdateEditorAsync(model, context); - if (result != null) - await result.ApplyAsync(context); - }, model, context, _logger); + await _partFieldDisplayDrivers.InvokeAsync( + async (contentDisplay, model, context) => + { + var result = await contentDisplay.UpdateEditorAsync(model, context); + if (result != null) + await result.ApplyAsync(context); + }, + model, + context, + _logger + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentPartSettingsDisplayDriver.cs index 7c55a5cdfbe..ae729031c99 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentPartSettingsDisplayDriver.cs @@ -10,16 +10,20 @@ public class ContentPartSettingsDisplayDriver : ContentPartDefinitionDisplayDriv { public override IDisplayResult Edit(ContentPartDefinition contentPartDefinition) { - return Initialize("ContentPartSettings_Edit", model => - { - var settings = contentPartDefinition.GetSettings(); + return Initialize( + "ContentPartSettings_Edit", + model => + { + var settings = contentPartDefinition.GetSettings(); - model.Attachable = settings.Attachable; - model.Reusable = settings.Reusable; - model.Description = settings.Description; - model.DisplayName = settings.DisplayName; - model.ContentPartDefinition = contentPartDefinition; - }).Location("Content"); + model.Attachable = settings.Attachable; + model.Reusable = settings.Reusable; + model.Description = settings.Description; + model.DisplayName = settings.DisplayName; + model.ContentPartDefinition = contentPartDefinition; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentPartDefinition contentPartDefinition, UpdatePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentTypeSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentTypeSettingsDisplayDriver.cs index 59b19eafbed..7802169d03a 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentTypeSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/ContentTypeSettingsDisplayDriver.cs @@ -19,18 +19,22 @@ public ContentTypeSettingsDisplayDriver(IStringLocalizer("ContentTypeSettings_Edit", model => - { - var settings = contentTypeDefinition.GetSettings(); + return Initialize( + "ContentTypeSettings_Edit", + model => + { + var settings = contentTypeDefinition.GetSettings(); - model.Creatable = settings.Creatable; - model.Listable = settings.Listable; - model.Draftable = settings.Draftable; - model.Versionable = settings.Versionable; - model.Securable = settings.Securable; - model.Stereotype = settings.Stereotype; - model.Description = settings.Description; - }).Location("Content:5"); + model.Creatable = settings.Creatable; + model.Listable = settings.Listable; + model.Draftable = settings.Draftable; + model.Versionable = settings.Versionable; + model.Securable = settings.Securable; + model.Stereotype = settings.Stereotype; + model.Description = settings.Description; + } + ) + .Location("Content:5"); } public override async Task UpdateAsync(ContentTypeDefinition contentTypeDefinition, UpdateTypeEditorContext context) @@ -67,9 +71,7 @@ private static bool IsAlphaNumericOrEmpty(string value) var startWithLetter = char.IsLetter(value[0]); - return value.Length == 1 - ? startWithLetter - : startWithLetter && value.Skip(1).All(c => char.IsLetterOrDigit(c)); + return value.Length == 1 ? startWithLetter : startWithLetter && value.Skip(1).All(c => char.IsLetterOrDigit(c)); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/DefaultContentDefinitionDisplayManager.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/DefaultContentDefinitionDisplayManager.cs index a4a02a639d6..161691409e8 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/DefaultContentDefinitionDisplayManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/DefaultContentDefinitionDisplayManager.cs @@ -30,7 +30,8 @@ public DefaultContentDefinitionDisplayManager( IEnumerable placementProviders, ILogger logger, ILayoutAccessor layoutAccessor - ) : base(shapeFactory, placementProviders) + ) + : base(shapeFactory, placementProviders) { _handlers = handlers; _shapeTableManager = shapeTableManager; @@ -47,19 +48,16 @@ public async Task BuildTypeEditorAsync(ContentTypeDefinition contentTyp dynamic contentTypeDefinitionShape = await CreateContentShapeAsync("ContentTypeDefinition_Edit"); contentTypeDefinitionShape.ContentTypeDefinition = contentTypeDefinition; - var typeContext = new BuildEditorContext( - contentTypeDefinitionShape, - groupId, - false, - "", - _shapeFactory, - await _layoutAccessor.GetLayoutAsync(), - updater - ); + var typeContext = new BuildEditorContext(contentTypeDefinitionShape, groupId, false, "", _shapeFactory, await _layoutAccessor.GetLayoutAsync(), updater); await BindPlacementAsync(typeContext); - await _handlers.InvokeAsync((handler, contentTypeDefinition, typeContext) => handler.BuildTypeEditorAsync(contentTypeDefinition, typeContext), contentTypeDefinition, typeContext, _logger); + await _handlers.InvokeAsync( + (handler, contentTypeDefinition, typeContext) => handler.BuildTypeEditorAsync(contentTypeDefinition, typeContext), + contentTypeDefinition, + typeContext, + _logger + ); return contentTypeDefinitionShape; } @@ -73,22 +71,22 @@ public async Task UpdateTypeEditorAsync(ContentTypeDefinition contentTy var layout = await _layoutAccessor.GetLayoutAsync(); - await _contentDefinitionManager.AlterTypeDefinitionAsync(contentTypeDefinition.Name, async typeBuilder => - { - var typeContext = new UpdateTypeEditorContext( - typeBuilder, - contentTypeDefinitionShape, - groupId, - false, - _shapeFactory, - layout, - updater - ); + await _contentDefinitionManager.AlterTypeDefinitionAsync( + contentTypeDefinition.Name, + async typeBuilder => + { + var typeContext = new UpdateTypeEditorContext(typeBuilder, contentTypeDefinitionShape, groupId, false, _shapeFactory, layout, updater); - await BindPlacementAsync(typeContext); + await BindPlacementAsync(typeContext); - await _handlers.InvokeAsync((handler, contentTypeDefinition, typeContext) => handler.UpdateTypeEditorAsync(contentTypeDefinition, typeContext), contentTypeDefinition, typeContext, _logger); - }); + await _handlers.InvokeAsync( + (handler, contentTypeDefinition, typeContext) => handler.UpdateTypeEditorAsync(contentTypeDefinition, typeContext), + contentTypeDefinition, + typeContext, + _logger + ); + } + ); return contentTypeDefinitionShape; } @@ -99,19 +97,16 @@ public async Task BuildPartEditorAsync(ContentPartDefinition contentPar var contentPartDefinitionShape = await CreateContentShapeAsync("ContentPartDefinition_Edit"); - var partContext = new BuildEditorContext( - contentPartDefinitionShape, - groupId, - false, - "", - _shapeFactory, - await _layoutAccessor.GetLayoutAsync(), - updater - ); + var partContext = new BuildEditorContext(contentPartDefinitionShape, groupId, false, "", _shapeFactory, await _layoutAccessor.GetLayoutAsync(), updater); await BindPlacementAsync(partContext); - await _handlers.InvokeAsync((handler, contentPartDefinition, partContext) => handler.BuildPartEditorAsync(contentPartDefinition, partContext), contentPartDefinition, partContext, _logger); + await _handlers.InvokeAsync( + (handler, contentPartDefinition, partContext) => handler.BuildPartEditorAsync(contentPartDefinition, partContext), + contentPartDefinition, + partContext, + _logger + ); return contentPartDefinitionShape; } @@ -125,22 +120,22 @@ public async Task UpdatePartEditorAsync(ContentPartDefinition contentPa UpdatePartEditorContext partContext = null; var layout = await _layoutAccessor.GetLayoutAsync(); - await _contentDefinitionManager.AlterPartDefinitionAsync(contentPartDefinition.Name, async partBuilder => - { - partContext = new UpdatePartEditorContext( - partBuilder, - contentPartDefinitionShape, - groupId, - false, - _shapeFactory, - layout, - updater - ); + await _contentDefinitionManager.AlterPartDefinitionAsync( + contentPartDefinition.Name, + async partBuilder => + { + partContext = new UpdatePartEditorContext(partBuilder, contentPartDefinitionShape, groupId, false, _shapeFactory, layout, updater); - await BindPlacementAsync(partContext); + await BindPlacementAsync(partContext); - await _handlers.InvokeAsync((handler, contentPartDefinition, partContext) => handler.UpdatePartEditorAsync(contentPartDefinition, partContext), contentPartDefinition, partContext, _logger); - }); + await _handlers.InvokeAsync( + (handler, contentPartDefinition, partContext) => handler.UpdatePartEditorAsync(contentPartDefinition, partContext), + contentPartDefinition, + partContext, + _logger + ); + } + ); return contentPartDefinitionShape; } @@ -152,19 +147,16 @@ public async Task BuildTypePartEditorAsync(ContentTypePartDefinition co dynamic typePartDefinitionShape = await CreateContentShapeAsync("ContentTypePartDefinition_Edit"); typePartDefinitionShape.ContentPart = contentTypePartDefinition; - var partContext = new BuildEditorContext( - typePartDefinitionShape, - groupId, - false, - "", - _shapeFactory, - await _layoutAccessor.GetLayoutAsync(), - updater - ); + var partContext = new BuildEditorContext(typePartDefinitionShape, groupId, false, "", _shapeFactory, await _layoutAccessor.GetLayoutAsync(), updater); await BindPlacementAsync(partContext); - await _handlers.InvokeAsync((handler, contentTypePartDefinition, partContext) => handler.BuildTypePartEditorAsync(contentTypePartDefinition, partContext), contentTypePartDefinition, partContext, _logger); + await _handlers.InvokeAsync( + (handler, contentTypePartDefinition, partContext) => handler.BuildTypePartEditorAsync(contentTypePartDefinition, partContext), + contentTypePartDefinition, + partContext, + _logger + ); return typePartDefinitionShape; } @@ -176,27 +168,30 @@ public async Task UpdateTypePartEditorAsync(ContentTypePartDefinition c dynamic typePartDefinitionShape = await CreateContentShapeAsync("ContentTypePartDefinition_Edit"); var layout = await _layoutAccessor.GetLayoutAsync(); - await _contentDefinitionManager.AlterTypeDefinitionAsync(contentTypePartDefinition.ContentTypeDefinition.Name, typeBuilder => - { - return typeBuilder.WithPartAsync(contentTypePartDefinition.Name, async typePartBuilder => + await _contentDefinitionManager.AlterTypeDefinitionAsync( + contentTypePartDefinition.ContentTypeDefinition.Name, + typeBuilder => { - typePartDefinitionShape.ContentPart = contentTypePartDefinition; - - var partContext = new UpdateTypePartEditorContext( - typePartBuilder, - typePartDefinitionShape, - groupId, - false, - _shapeFactory, - layout, - updater + return typeBuilder.WithPartAsync( + contentTypePartDefinition.Name, + async typePartBuilder => + { + typePartDefinitionShape.ContentPart = contentTypePartDefinition; + + var partContext = new UpdateTypePartEditorContext(typePartBuilder, typePartDefinitionShape, groupId, false, _shapeFactory, layout, updater); + + await BindPlacementAsync(partContext); + + await _handlers.InvokeAsync( + (handler, contentTypePartDefinition, partContext) => handler.UpdateTypePartEditorAsync(contentTypePartDefinition, partContext), + contentTypePartDefinition, + partContext, + _logger + ); + } ); - - await BindPlacementAsync(partContext); - - await _handlers.InvokeAsync((handler, contentTypePartDefinition, partContext) => handler.UpdateTypePartEditorAsync(contentTypePartDefinition, partContext), contentTypePartDefinition, partContext, _logger); - }); - }); + } + ); return typePartDefinitionShape; } @@ -208,19 +203,16 @@ public async Task BuildPartFieldEditorAsync(ContentPartFieldDefinition dynamic partFieldDefinitionShape = await CreateContentShapeAsync("ContentPartFieldDefinition_Edit"); partFieldDefinitionShape.ContentField = contentPartFieldDefinition; - var fieldContext = new BuildEditorContext( - partFieldDefinitionShape, - groupId, - false, - "", - _shapeFactory, - await _layoutAccessor.GetLayoutAsync(), - updater - ); + var fieldContext = new BuildEditorContext(partFieldDefinitionShape, groupId, false, "", _shapeFactory, await _layoutAccessor.GetLayoutAsync(), updater); await BindPlacementAsync(fieldContext); - await _handlers.InvokeAsync((handler, contentPartFieldDefinition, fieldContext) => handler.BuildPartFieldEditorAsync(contentPartFieldDefinition, fieldContext), contentPartFieldDefinition, fieldContext, _logger); + await _handlers.InvokeAsync( + (handler, contentPartFieldDefinition, fieldContext) => handler.BuildPartFieldEditorAsync(contentPartFieldDefinition, fieldContext), + contentPartFieldDefinition, + fieldContext, + _logger + ); return partFieldDefinitionShape; } @@ -234,27 +226,30 @@ public async Task UpdatePartFieldEditorAsync(ContentPartFieldDefinition var layout = await _layoutAccessor.GetLayoutAsync(); - await _contentDefinitionManager.AlterPartDefinitionAsync(contentPartDefinition.Name, partBuilder => - { - return partBuilder.WithFieldAsync(contentPartFieldDefinition.Name, async partFieldBuilder => + await _contentDefinitionManager.AlterPartDefinitionAsync( + contentPartDefinition.Name, + partBuilder => { - partFieldDefinitionShape.ContentField = contentPartFieldDefinition; - - var fieldContext = new UpdatePartFieldEditorContext( - partFieldBuilder, - partFieldDefinitionShape, - groupId, - false, - _shapeFactory, - layout, - updater + return partBuilder.WithFieldAsync( + contentPartFieldDefinition.Name, + async partFieldBuilder => + { + partFieldDefinitionShape.ContentField = contentPartFieldDefinition; + + var fieldContext = new UpdatePartFieldEditorContext(partFieldBuilder, partFieldDefinitionShape, groupId, false, _shapeFactory, layout, updater); + + await BindPlacementAsync(fieldContext); + + await _handlers.InvokeAsync( + (handler, contentPartFieldDefinition, fieldContext) => handler.UpdatePartFieldEditorAsync(contentPartFieldDefinition, fieldContext), + contentPartFieldDefinition, + fieldContext, + _logger + ); + } ); - - await BindPlacementAsync(fieldContext); - - await _handlers.InvokeAsync((handler, contentPartFieldDefinition, fieldContext) => handler.UpdatePartFieldEditorAsync(contentPartFieldDefinition, fieldContext), contentPartFieldDefinition, fieldContext, _logger); - }); - }); + } + ); return partFieldDefinitionShape; } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/DefaultContentTypeDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/DefaultContentTypeDisplayDriver.cs index fc7ec3a1f59..7dbe22defbf 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/DefaultContentTypeDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Editors/DefaultContentTypeDisplayDriver.cs @@ -17,11 +17,15 @@ public DefaultContentTypeDisplayDriver(IStringLocalizer("ContentType_Edit", model => - { - model.DisplayName = contentTypeDefinition.DisplayName; - model.Name = contentTypeDefinition.Name; - }).Location("Content"); + return Initialize( + "ContentType_Edit", + model => + { + model.DisplayName = contentTypeDefinition.DisplayName; + model.Name = contentTypeDefinition.Name; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypeDefinition contentTypeDefinition, UpdateTypeEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/GraphQL/Drivers/GraphQLContentTypePartSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/GraphQL/Drivers/GraphQLContentTypePartSettingsDriver.cs index 1ce66d2c6ce..923076eb674 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/GraphQL/Drivers/GraphQLContentTypePartSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/GraphQL/Drivers/GraphQLContentTypePartSettingsDriver.cs @@ -25,12 +25,16 @@ public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDef return null; } - return Initialize("GraphQLContentTypePartSettings_Edit", model => - { - model.Definition = contentTypePartDefinition; - model.Options = _contentOptions; - model.Settings = contentTypePartDefinition.GetSettings(); - }).Location("Content"); + return Initialize( + "GraphQLContentTypePartSettings_Edit", + model => + { + model.Definition = contentTypePartDefinition; + model.Options = _contentOptions; + model.Settings = contentTypePartDefinition.GetSettings(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/GraphQL/Drivers/GraphQLContentTypeSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/GraphQL/Drivers/GraphQLContentTypeSettingsDisplayDriver.cs index 62ef1b132ff..735f527a883 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/GraphQL/Drivers/GraphQLContentTypeSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/GraphQL/Drivers/GraphQLContentTypeSettingsDisplayDriver.cs @@ -20,12 +20,16 @@ public GraphQLContentTypeSettingsDisplayDriver(IOptions o public override IDisplayResult Edit(ContentTypeDefinition contentTypeDefinition) { - return Initialize("GraphQLContentTypeSettings_Edit", model => - { - model.Definition = contentTypeDefinition; - model.Settings = contentTypeDefinition.GetSettings(); - model.Options = _contentOptions; - }).Location("Content:5"); + return Initialize( + "GraphQLContentTypeSettings_Edit", + model => + { + model.Definition = contentTypeDefinition; + model.Settings = contentTypeDefinition.GetSettings(); + model.Options = _contentOptions; + } + ) + .Location("Content:5"); } public override async Task UpdateAsync(ContentTypeDefinition contentTypeDefinition, UpdateTypeEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Permissions.cs index 2fdb506986a..bd40a5e8011 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Permissions.cs @@ -9,21 +9,9 @@ public class Permissions : IPermissionProvider public static readonly Permission ViewContentTypes = new("ViewContentTypes", "View content types."); public static readonly Permission EditContentTypes = new("EditContentTypes", "Edit content types.", isSecurityCritical: true); - private readonly IEnumerable _allPermissions = - [ - ViewContentTypes, - EditContentTypes, - ]; + private readonly IEnumerable _allPermissions = [ViewContentTypes, EditContentTypes,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/RecipeSteps/ContentDefinitionStep.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/RecipeSteps/ContentDefinitionStep.cs index 73caa66a5c5..3fc1159cab4 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/RecipeSteps/ContentDefinitionStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/RecipeSteps/ContentDefinitionStep.cs @@ -32,50 +32,57 @@ public async Task ExecuteAsync(RecipeExecutionContext context) foreach (var contentType in step.ContentTypes) { - var newType = await _contentDefinitionManager.LoadTypeDefinitionAsync(contentType.Name) - ?? new ContentTypeDefinition(contentType.Name, contentType.DisplayName); + var newType = await _contentDefinitionManager.LoadTypeDefinitionAsync(contentType.Name) ?? new ContentTypeDefinition(contentType.Name, contentType.DisplayName); await UpdateContentTypeAsync(newType, contentType); } foreach (var contentPart in step.ContentParts) { - var newPart = await _contentDefinitionManager.LoadPartDefinitionAsync(contentPart.Name) - ?? new ContentPartDefinition(contentPart.Name); + var newPart = await _contentDefinitionManager.LoadPartDefinitionAsync(contentPart.Name) ?? new ContentPartDefinition(contentPart.Name); await UpdateContentPartAsync(newPart, contentPart); } } - private Task UpdateContentTypeAsync(ContentTypeDefinition type, ContentTypeDefinitionRecord record) - => _contentDefinitionManager.AlterTypeDefinitionAsync(type.Name, builder => - { - if (!string.IsNullOrEmpty(record.DisplayName)) + private Task UpdateContentTypeAsync(ContentTypeDefinition type, ContentTypeDefinitionRecord record) => + _contentDefinitionManager.AlterTypeDefinitionAsync( + type.Name, + builder => { - builder.DisplayedAs(record.DisplayName); - builder.MergeSettings(record.Settings); - } + if (!string.IsNullOrEmpty(record.DisplayName)) + { + builder.DisplayedAs(record.DisplayName); + builder.MergeSettings(record.Settings); + } - foreach (var part in record.ContentTypePartDefinitionRecords) - { - builder.WithPart(part.Name, part.PartName, partBuilder => partBuilder.MergeSettings(part.Settings)); + foreach (var part in record.ContentTypePartDefinitionRecords) + { + builder.WithPart(part.Name, part.PartName, partBuilder => partBuilder.MergeSettings(part.Settings)); + } } - }); - - private Task UpdateContentPartAsync(ContentPartDefinition part, ContentPartDefinitionRecord record) - => _contentDefinitionManager.AlterPartDefinitionAsync(part.Name, builder => - { - builder.MergeSettings(record.Settings); + ); - foreach (var field in record.ContentPartFieldDefinitionRecords) + private Task UpdateContentPartAsync(ContentPartDefinition part, ContentPartDefinitionRecord record) => + _contentDefinitionManager.AlterPartDefinitionAsync( + part.Name, + builder => { - builder.WithField(field.Name, fieldBuilder => + builder.MergeSettings(record.Settings); + + foreach (var field in record.ContentPartFieldDefinitionRecords) { - fieldBuilder.OfType(field.FieldName); - fieldBuilder.MergeSettings(field.Settings); - }); + builder.WithField( + field.Name, + fieldBuilder => + { + fieldBuilder.OfType(field.FieldName); + fieldBuilder.MergeSettings(field.Settings); + } + ); + } } - }); + ); private class ContentDefinitionStepModel { diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/RecipeSteps/ReplaceContentDefinitionStep.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/RecipeSteps/ReplaceContentDefinitionStep.cs index 6822f856922..a7a4b250278 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/RecipeSteps/ReplaceContentDefinitionStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/RecipeSteps/ReplaceContentDefinitionStep.cs @@ -49,36 +49,45 @@ public async Task ExecuteAsync(RecipeExecutionContext context) private async Task AlterContentTypeAsync(ContentTypeDefinitionRecord record) { - await _contentDefinitionManager.AlterTypeDefinitionAsync(record.Name, builder => - { - if (!string.IsNullOrEmpty(record.DisplayName)) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + record.Name, + builder => { - builder.DisplayedAs(record.DisplayName); - builder.MergeSettings(record.Settings); - } + if (!string.IsNullOrEmpty(record.DisplayName)) + { + builder.DisplayedAs(record.DisplayName); + builder.MergeSettings(record.Settings); + } - foreach (var part in record.ContentTypePartDefinitionRecords) - { - builder.WithPart(part.Name, part.PartName, partBuilder => partBuilder.MergeSettings(part.Settings)); + foreach (var part in record.ContentTypePartDefinitionRecords) + { + builder.WithPart(part.Name, part.PartName, partBuilder => partBuilder.MergeSettings(part.Settings)); + } } - }); + ); } private async Task AlterContentPartAsync(ContentPartDefinitionRecord record) { - await _contentDefinitionManager.AlterPartDefinitionAsync(record.Name, builder => - { - builder.MergeSettings(record.Settings); - - foreach (var field in record.ContentPartFieldDefinitionRecords) + await _contentDefinitionManager.AlterPartDefinitionAsync( + record.Name, + builder => { - builder.WithField(field.Name, fieldBuilder => + builder.MergeSettings(record.Settings); + + foreach (var field in record.ContentPartFieldDefinitionRecords) { - fieldBuilder.OfType(field.FieldName); - fieldBuilder.MergeSettings(field.Settings); - }); + builder.WithField( + field.Name, + fieldBuilder => + { + fieldBuilder.OfType(field.FieldName); + fieldBuilder.MergeSettings(field.Settings); + } + ); + } } - }); + ); } private class ReplaceContentDefinitionStepModel diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Recipes/LuceneRecipeEventHandler.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Recipes/LuceneRecipeEventHandler.cs index 64a7d041392..8d9021ed761 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Recipes/LuceneRecipeEventHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Recipes/LuceneRecipeEventHandler.cs @@ -33,8 +33,10 @@ public Task RecipeStepExecutingAsync(RecipeExecutionContext context) { if (partDefinition.Settings != null) { - if (partDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingPartSettings) && - !partDefinition.Settings.ContainsKey("LuceneContentIndexSettings")) + if ( + partDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingPartSettings) + && !partDefinition.Settings.ContainsKey("LuceneContentIndexSettings") + ) { partDefinition.Settings.Add("LuceneContentIndexSettings", existingPartSettings); } @@ -48,8 +50,10 @@ public Task RecipeStepExecutingAsync(RecipeExecutionContext context) { if (partDefinition.Settings != null) { - if (partDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingPartSettings) && - !partDefinition.Settings.ContainsKey("LuceneContentIndexSettings")) + if ( + partDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingPartSettings) + && !partDefinition.Settings.ContainsKey("LuceneContentIndexSettings") + ) { partDefinition.Settings.Add("LuceneContentIndexSettings", existingPartSettings); } @@ -60,8 +64,10 @@ public Task RecipeStepExecutingAsync(RecipeExecutionContext context) { if (fieldDefinition.Settings != null) { - if (fieldDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingFieldSettings) && - !fieldDefinition.Settings.ContainsKey("LuceneContentIndexSettings")) + if ( + fieldDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingFieldSettings) + && !fieldDefinition.Settings.ContainsKey("LuceneContentIndexSettings") + ) { fieldDefinition.Settings.Add("LuceneContentIndexSettings", existingFieldSettings); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/ContentDefinitionService.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/ContentDefinitionService.cs index 21825fefe2a..bec450b27eb 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/ContentDefinitionService.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/ContentDefinitionService.cs @@ -26,13 +26,14 @@ public class ContentDefinitionService : IContentDefinitionService private readonly ILogger _logger; public ContentDefinitionService( - IContentDefinitionManager contentDefinitionManager, - IEnumerable contentDefinitionEventHandlers, - IEnumerable contentParts, - IEnumerable contentFields, - IOptions contentOptions, - ILogger logger, - IStringLocalizer localizer) + IContentDefinitionManager contentDefinitionManager, + IEnumerable contentDefinitionEventHandlers, + IEnumerable contentParts, + IEnumerable contentFields, + IOptions contentOptions, + ILogger logger, + IStringLocalizer localizer + ) { _contentDefinitionManager = contentDefinitionManager; _contentDefinitionEventHandlers = contentDefinitionEventHandlers; @@ -48,26 +49,20 @@ public ContentDefinitionService( } // TODO: This code can be removed in a future release and rationalized to only use ContentPartOptions. - _contentPartTypes = contentParts.Select(cp => cp.GetType()) - .Union(contentOptions.Value.ContentPartOptions.Select(cpo => cpo.Type)); + _contentPartTypes = contentParts.Select(cp => cp.GetType()).Union(contentOptions.Value.ContentPartOptions.Select(cpo => cpo.Type)); // TODO: This code can be removed in a future release and rationalized to only use ContentFieldOptions. - _contentFieldTypes = contentFields.Select(cf => cf.GetType()) - .Union(contentOptions.Value.ContentFieldOptions.Select(cfo => cfo.Type)); + _contentFieldTypes = contentFields.Select(cf => cf.GetType()).Union(contentOptions.Value.ContentFieldOptions.Select(cfo => cfo.Type)); _logger = logger; S = localizer; } - public async Task> LoadTypesAsync() - => (await _contentDefinitionManager.LoadTypeDefinitionsAsync()) - .Select(ctd => new EditTypeViewModel(ctd)) - .OrderBy(m => m.DisplayName); + public async Task> LoadTypesAsync() => + (await _contentDefinitionManager.LoadTypeDefinitionsAsync()).Select(ctd => new EditTypeViewModel(ctd)).OrderBy(m => m.DisplayName); - public async Task> GetTypesAsync() - => (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Select(ctd => new EditTypeViewModel(ctd)) - .OrderBy(m => m.DisplayName); + public async Task> GetTypesAsync() => + (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Select(ctd => new EditTypeViewModel(ctd)).OrderBy(m => m.DisplayName); public async Task LoadTypeAsync(string name) { @@ -129,7 +124,11 @@ public async Task AddTypeAsync(string name, string displa await _contentDefinitionManager.AlterTypeDefinitionAsync(name, builder => builder.WithPart(name)); await _contentDefinitionManager.AlterTypeDefinitionAsync(name, cfg => cfg.Creatable().Draftable().Versionable().Listable().Securable()); - _contentDefinitionEventHandlers.Invoke((handler, context) => handler.ContentTypeCreated(context), new ContentTypeCreatedContext { ContentTypeDefinition = contentTypeDefinition }, _logger); + _contentDefinitionEventHandlers.Invoke( + (handler, context) => handler.ContentTypeCreated(context), + new ContentTypeCreatedContext { ContentTypeDefinition = contentTypeDefinition }, + _logger + ); return contentTypeDefinition; } @@ -152,32 +151,54 @@ public async Task RemoveTypeAsync(string name, bool deleteContent) await _contentDefinitionManager.DeleteTypeDefinitionAsync(name); - _contentDefinitionEventHandlers.Invoke((handler, context) => handler.ContentTypeRemoved(context), new ContentTypeRemovedContext { ContentTypeDefinition = typeDefinition }, _logger); + _contentDefinitionEventHandlers.Invoke( + (handler, context) => handler.ContentTypeRemoved(context), + new ContentTypeRemovedContext { ContentTypeDefinition = typeDefinition }, + _logger + ); } public async Task AddPartToTypeAsync(string partName, string typeName) { await _contentDefinitionManager.AlterTypeDefinitionAsync(typeName, typeBuilder => typeBuilder.WithPart(partName)); - _contentDefinitionEventHandlers.Invoke((handler, context) => handler.ContentPartAttached(context), new ContentPartAttachedContext { ContentTypeName = typeName, ContentPartName = partName }, _logger); + _contentDefinitionEventHandlers.Invoke( + (handler, context) => handler.ContentPartAttached(context), + new ContentPartAttachedContext { ContentTypeName = typeName, ContentPartName = partName }, + _logger + ); } public async Task AddReusablePartToTypeAsync(string name, string displayName, string description, string partName, string typeName) { - await _contentDefinitionManager.AlterTypeDefinitionAsync(typeName, typeBuilder => typeBuilder - .WithPart(name, partName, partBuilder => - { - partBuilder.WithDisplayName(displayName); - partBuilder.WithDescription(description); - }) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + typeName, + typeBuilder => + typeBuilder.WithPart( + name, + partName, + partBuilder => + { + partBuilder.WithDisplayName(displayName); + partBuilder.WithDescription(description); + } + ) ); - _contentDefinitionEventHandlers.Invoke((handler, context) => handler.ContentPartAttached(context), new ContentPartAttachedContext { ContentTypeName = typeName, ContentPartName = partName }, _logger); + _contentDefinitionEventHandlers.Invoke( + (handler, context) => handler.ContentPartAttached(context), + new ContentPartAttachedContext { ContentTypeName = typeName, ContentPartName = partName }, + _logger + ); } public async Task RemovePartFromTypeAsync(string partName, string typeName) { await _contentDefinitionManager.AlterTypeDefinitionAsync(typeName, typeBuilder => typeBuilder.RemovePart(partName)); - _contentDefinitionEventHandlers.Invoke((handler, context) => handler.ContentPartDetached(context), new ContentPartDetachedContext { ContentTypeName = typeName, ContentPartName = partName }, _logger); + _contentDefinitionEventHandlers.Invoke( + (handler, context) => handler.ContentPartDetached(context), + new ContentPartDetachedContext { ContentTypeName = typeName, ContentPartName = partName }, + _logger + ); } public async Task> LoadPartsAsync(bool metadataPartsOnly) @@ -194,15 +215,10 @@ public async Task> LoadPartsAsync(bool metadataPa // Code-defined parts. var codeDefinedParts = metadataPartsOnly ? [] - : _contentPartTypes - .Where(cpd => !userContentParts.ContainsKey(cpd.Name)) - .Select(cpi => new EditPartViewModel { Name = cpi.Name, DisplayName = cpi.Name }) - .ToList(); + : _contentPartTypes.Where(cpd => !userContentParts.ContainsKey(cpd.Name)).Select(cpi => new EditPartViewModel { Name = cpi.Name, DisplayName = cpi.Name }).ToList(); // Order by display name. - return codeDefinedParts - .Union(userContentParts.Values) - .OrderBy(m => m.DisplayName); + return codeDefinedParts.Union(userContentParts.Values).OrderBy(m => m.DisplayName); } public async Task> GetPartsAsync(bool metadataPartsOnly) @@ -219,15 +235,10 @@ public async Task> GetPartsAsync(bool metadataPar // Code-defined parts. var codeDefinedParts = metadataPartsOnly ? [] - : _contentPartTypes - .Where(cpd => !userContentParts.ContainsKey(cpd.Name)) - .Select(cpi => new EditPartViewModel { Name = cpi.Name, DisplayName = cpi.Name }) - .ToList(); + : _contentPartTypes.Where(cpd => !userContentParts.ContainsKey(cpd.Name)).Select(cpi => new EditPartViewModel { Name = cpi.Name, DisplayName = cpi.Name }).ToList(); // Order by display name. - return codeDefinedParts - .Union(userContentParts.Values) - .OrderBy(m => m.DisplayName); + return codeDefinedParts.Union(userContentParts.Values).OrderBy(m => m.DisplayName); } public async Task LoadPartAsync(string name) @@ -285,7 +296,11 @@ public async Task AddPartAsync(CreatePartViewModel partViewMo { await _contentDefinitionManager.AlterPartDefinitionAsync(name, builder => builder.Attachable()); var partDefinition = await _contentDefinitionManager.LoadPartDefinitionAsync(name); - _contentDefinitionEventHandlers.Invoke((handler, context) => handler.ContentPartCreated(context), new ContentPartCreatedContext { ContentPartDefinition = partDefinition }, _logger); + _contentDefinitionEventHandlers.Invoke( + (handler, context) => handler.ContentPartCreated(context), + new ContentPartCreatedContext { ContentPartDefinition = partDefinition }, + _logger + ); return new EditPartViewModel(partDefinition); } @@ -309,14 +324,16 @@ public async Task RemovePartAsync(string name) } await _contentDefinitionManager.DeletePartDefinitionAsync(name); - _contentDefinitionEventHandlers.Invoke((handler, context) => handler.ContentPartRemoved(context), new ContentPartRemovedContext { ContentPartDefinition = partDefinition }, _logger); + _contentDefinitionEventHandlers.Invoke( + (handler, context) => handler.ContentPartRemoved(context), + new ContentPartRemovedContext { ContentPartDefinition = partDefinition }, + _logger + ); } - public Task> GetFieldsAsync() - => Task.FromResult(_contentFieldTypes); + public Task> GetFieldsAsync() => Task.FromResult(_contentFieldTypes); - public Task AddFieldToPartAsync(string fieldName, string fieldTypeName, string partName) - => AddFieldToPartAsync(fieldName, fieldName, fieldTypeName, partName); + public Task AddFieldToPartAsync(string fieldName, string fieldTypeName, string partName) => AddFieldToPartAsync(fieldName, fieldName, fieldTypeName, partName); public async Task AddFieldToPartAsync(string fieldName, string displayName, string fieldTypeName, string partName) { @@ -336,98 +353,130 @@ public async Task AddFieldToPartAsync(string fieldName, string displayName, stri fieldName = fieldName.ToSafeName(); - await _contentDefinitionManager.AlterPartDefinitionAsync(partName, - partBuilder => partBuilder.WithField(fieldName, fieldBuilder => fieldBuilder.OfType(fieldTypeName).WithDisplayName(displayName))); + await _contentDefinitionManager.AlterPartDefinitionAsync( + partName, + partBuilder => partBuilder.WithField(fieldName, fieldBuilder => fieldBuilder.OfType(fieldTypeName).WithDisplayName(displayName)) + ); - _contentDefinitionEventHandlers.Invoke((handler, context) => handler.ContentFieldAttached(context), new ContentFieldAttachedContext - { - ContentPartName = partName, - ContentFieldTypeName = fieldTypeName, - ContentFieldName = fieldName, - ContentFieldDisplayName = displayName - }, _logger); + _contentDefinitionEventHandlers.Invoke( + (handler, context) => handler.ContentFieldAttached(context), + new ContentFieldAttachedContext + { + ContentPartName = partName, + ContentFieldTypeName = fieldTypeName, + ContentFieldName = fieldName, + ContentFieldDisplayName = displayName + }, + _logger + ); } public async Task RemoveFieldFromPartAsync(string fieldName, string partName) { await _contentDefinitionManager.AlterPartDefinitionAsync(partName, typeBuilder => typeBuilder.RemoveField(fieldName)); - _contentDefinitionEventHandlers.Invoke((handler, context) => handler.ContentFieldDetached(context), new ContentFieldDetachedContext - { - ContentPartName = partName, - ContentFieldName = fieldName - }, _logger); + _contentDefinitionEventHandlers.Invoke( + (handler, context) => handler.ContentFieldDetached(context), + new ContentFieldDetachedContext { ContentPartName = partName, ContentFieldName = fieldName }, + _logger + ); } public async Task AlterFieldAsync(EditPartViewModel partViewModel, EditFieldViewModel fieldViewModel) { - await _contentDefinitionManager.AlterPartDefinitionAsync(partViewModel.Name, partBuilder => - { - partBuilder.WithField(fieldViewModel.Name, fieldBuilder => + await _contentDefinitionManager.AlterPartDefinitionAsync( + partViewModel.Name, + partBuilder => { - fieldBuilder.WithDisplayName(fieldViewModel.DisplayName); - fieldBuilder.WithEditor(fieldViewModel.Editor); - fieldBuilder.WithDisplayMode(fieldViewModel.DisplayMode); - }); - }); + partBuilder.WithField( + fieldViewModel.Name, + fieldBuilder => + { + fieldBuilder.WithDisplayName(fieldViewModel.DisplayName); + fieldBuilder.WithEditor(fieldViewModel.Editor); + fieldBuilder.WithDisplayMode(fieldViewModel.DisplayMode); + } + ); + } + ); } public async Task AlterTypePartAsync(EditTypePartViewModel typePartViewModel) { var typeDefinition = typePartViewModel.TypePartDefinition.ContentTypeDefinition; - await _contentDefinitionManager.AlterTypeDefinitionAsync(typeDefinition.Name, type => - { - type.WithPart(typePartViewModel.Name, typePartViewModel.TypePartDefinition.PartDefinition, part => + await _contentDefinitionManager.AlterTypeDefinitionAsync( + typeDefinition.Name, + type => { - part.WithDisplayName(typePartViewModel.DisplayName); - part.WithDescription(typePartViewModel.Description); - part.WithEditor(typePartViewModel.Editor); - part.WithDisplayMode(typePartViewModel.DisplayMode); - }); - }); - } - - public Task AlterTypePartsOrderAsync(ContentTypeDefinition typeDefinition, string[] partNames) - => _contentDefinitionManager.AlterTypeDefinitionAsync(typeDefinition.Name, type => - { - if (partNames is null) - { - return; + type.WithPart( + typePartViewModel.Name, + typePartViewModel.TypePartDefinition.PartDefinition, + part => + { + part.WithDisplayName(typePartViewModel.DisplayName); + part.WithDescription(typePartViewModel.Description); + part.WithEditor(typePartViewModel.Editor); + part.WithDisplayMode(typePartViewModel.DisplayMode); + } + ); } + ); + } - for (var i = 0; i < partNames.Length; i++) + public Task AlterTypePartsOrderAsync(ContentTypeDefinition typeDefinition, string[] partNames) => + _contentDefinitionManager.AlterTypeDefinitionAsync( + typeDefinition.Name, + type => { - var partDefinition = typeDefinition.Parts?.FirstOrDefault(x => x.Name == partNames[i]); - - if (partDefinition == null) + if (partNames is null) { - continue; + return; } - type.WithPart(partNames[i], partDefinition.PartDefinition, part => + for (var i = 0; i < partNames.Length; i++) { - part.MergeSettings(x => x.Position = i.ToString()); - }); + var partDefinition = typeDefinition.Parts?.FirstOrDefault(x => x.Name == partNames[i]); + + if (partDefinition == null) + { + continue; + } + + type.WithPart( + partNames[i], + partDefinition.PartDefinition, + part => + { + part.MergeSettings(x => x.Position = i.ToString()); + } + ); + } } - }); + ); - public Task AlterPartFieldsOrderAsync(ContentPartDefinition partDefinition, string[] fieldNames) - => _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, type => - { - if (fieldNames is null) + public Task AlterPartFieldsOrderAsync(ContentPartDefinition partDefinition, string[] fieldNames) => + _contentDefinitionManager.AlterPartDefinitionAsync( + partDefinition.Name, + type => { - return; - } + if (fieldNames is null) + { + return; + } - for (var i = 0; i < fieldNames.Length; i++) - { - var fieldDefinition = partDefinition.Fields.FirstOrDefault(x => x.Name == fieldNames[i]); - type.WithField(fieldNames[i], field => + for (var i = 0; i < fieldNames.Length; i++) { - field.MergeSettings(x => x.Position = i.ToString()); - }); + var fieldDefinition = partDefinition.Fields.FirstOrDefault(x => x.Name == fieldNames[i]); + type.WithField( + fieldNames[i], + field => + { + field.MergeSettings(x => x.Position = i.ToString()); + } + ); + } } - }); + ); public async Task GenerateContentTypeNameFromDisplayNameAsync(string displayName) { @@ -450,8 +499,7 @@ public async Task GenerateFieldNameFromDisplayNameAsync(string partName, if (part == null) { - var type = await _contentDefinitionManager.LoadTypeDefinitionAsync(partName) - ?? throw new ArgumentException("The part doesn't exist: " + partName); + var type = await _contentDefinitionManager.LoadTypeDefinitionAsync(partName) ?? throw new ArgumentException("The part doesn't exist: " + partName); var typePart = type.Parts?.FirstOrDefault(x => x.PartDefinition.Name == partName); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/DefaultStereotypesProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/DefaultStereotypesProvider.cs index 5c647b26cd4..174e25a3de4 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/DefaultStereotypesProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/DefaultStereotypesProvider.cs @@ -7,6 +7,7 @@ namespace OrchardCore.ContentTypes.Services public class DefaultStereotypesProvider : IStereotypesProvider { private readonly IContentDefinitionService _contentDefinitionService; + public DefaultStereotypesProvider(IContentDefinitionService contentDefinitionService) { _contentDefinitionService = contentDefinitionService; diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IContentDefinitionService.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IContentDefinitionService.cs index a9358d426d8..e05f098cdac 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IContentDefinitionService.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IContentDefinitionService.cs @@ -59,102 +59,79 @@ public interface IContentDefinitionService Task AlterPartFieldsOrderAsync(ContentPartDefinition partDefinition, string[] fieldNames); [Obsolete($"Instead, utilize the {nameof(LoadTypesAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable LoadTypes() -=> LoadTypesAsync().GetAwaiter().GetResult(); + IEnumerable LoadTypes() => LoadTypesAsync().GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(GetTypesAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable GetTypes() - => GetTypesAsync().GetAwaiter().GetResult(); + IEnumerable GetTypes() => GetTypesAsync().GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(LoadTypeAsync)} method. This current method is slated for removal in upcoming releases.")] - EditTypeViewModel LoadType(string name) - => LoadTypeAsync(name).GetAwaiter().GetResult(); + EditTypeViewModel LoadType(string name) => LoadTypeAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(GetTypeAsync)} method. This current method is slated for removal in upcoming releases.")] - EditTypeViewModel GetType(string name) - => GetTypeAsync(name).GetAwaiter().GetResult(); + EditTypeViewModel GetType(string name) => GetTypeAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(AddTypeAsync)} method. This current method is slated for removal in upcoming releases.")] - ContentTypeDefinition AddType(string name, string displayName) - => AddTypeAsync(name, displayName).GetAwaiter().GetResult(); + ContentTypeDefinition AddType(string name, string displayName) => AddTypeAsync(name, displayName).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(RemoveTypeAsync)} method. This current method is slated for removal in upcoming releases.")] - void RemoveType(string name, bool deleteContent) - => RemoveTypeAsync(name, deleteContent).GetAwaiter().GetResult(); + void RemoveType(string name, bool deleteContent) => RemoveTypeAsync(name, deleteContent).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(AddPartToTypeAsync)} method. This current method is slated for removal in upcoming releases.")] - void AddPartToType(string partName, string typeName) - => AddPartToTypeAsync(partName, typeName).GetAwaiter().GetResult(); + void AddPartToType(string partName, string typeName) => AddPartToTypeAsync(partName, typeName).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(AddReusablePartToTypeAsync)} method. This current method is slated for removal in upcoming releases.")] - void AddReusablePartToType(string name, string displayName, string description, string partName, string typeName) - => AddReusablePartToTypeAsync(name, displayName, description, partName, typeName).GetAwaiter().GetResult(); + void AddReusablePartToType(string name, string displayName, string description, string partName, string typeName) => + AddReusablePartToTypeAsync(name, displayName, description, partName, typeName).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(RemovePartFromTypeAsync)} method. This current method is slated for removal in upcoming releases.")] - void RemovePartFromType(string partName, string typeName) - => RemovePartFromTypeAsync(partName, typeName); + void RemovePartFromType(string partName, string typeName) => RemovePartFromTypeAsync(partName, typeName); [Obsolete($"Instead, utilize the {nameof(GenerateContentTypeNameFromDisplayNameAsync)} method. This current method is slated for removal in upcoming releases.")] - string GenerateContentTypeNameFromDisplayName(string displayName) - => GenerateContentTypeNameFromDisplayNameAsync(displayName).GetAwaiter().GetResult(); + string GenerateContentTypeNameFromDisplayName(string displayName) => GenerateContentTypeNameFromDisplayNameAsync(displayName).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(GenerateFieldNameFromDisplayNameAsync)} method. This current method is slated for removal in upcoming releases.")] - string GenerateFieldNameFromDisplayName(string partName, string displayName) - => GenerateFieldNameFromDisplayNameAsync(partName, displayName).GetAwaiter().GetResult(); + string GenerateFieldNameFromDisplayName(string partName, string displayName) => GenerateFieldNameFromDisplayNameAsync(partName, displayName).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(LoadPartsAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable LoadParts(bool metadataPartsOnly) - => LoadPartsAsync(metadataPartsOnly).GetAwaiter().GetResult(); + IEnumerable LoadParts(bool metadataPartsOnly) => LoadPartsAsync(metadataPartsOnly).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(GetPartsAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable GetParts(bool metadataPartsOnly) - => GetPartsAsync(metadataPartsOnly).GetAwaiter().GetResult(); + IEnumerable GetParts(bool metadataPartsOnly) => GetPartsAsync(metadataPartsOnly).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(LoadPartAsync)} method. This current method is slated for removal in upcoming releases.")] - EditPartViewModel LoadPart(string name) - => LoadPartAsync(name).GetAwaiter().GetResult(); + EditPartViewModel LoadPart(string name) => LoadPartAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(GetPartAsync)} method. This current method is slated for removal in upcoming releases.")] - EditPartViewModel GetPart(string name) - => GetPartAsync(name).GetAwaiter().GetResult(); + EditPartViewModel GetPart(string name) => GetPartAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(AddPartAsync)} method. This current method is slated for removal in upcoming releases.")] - EditPartViewModel AddPart(CreatePartViewModel partViewModel) - => AddPartAsync(partViewModel).GetAwaiter().GetResult(); + EditPartViewModel AddPart(CreatePartViewModel partViewModel) => AddPartAsync(partViewModel).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(RemovePartAsync)} method. This current method is slated for removal in upcoming releases.")] - void RemovePart(string name) - => RemovePartAsync(name).GetAwaiter().GetResult(); + void RemovePart(string name) => RemovePartAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(GetFieldsAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable GetFields() - => GetFieldsAsync().GetAwaiter().GetResult(); + IEnumerable GetFields() => GetFieldsAsync().GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(AddFieldToPartAsync)} method. This current method is slated for removal in upcoming releases.")] - void AddFieldToPart(string fieldName, string fieldTypeName, string partName) - => AddFieldToPartAsync(fieldName, fieldTypeName, partName).GetAwaiter().GetResult(); + void AddFieldToPart(string fieldName, string fieldTypeName, string partName) => AddFieldToPartAsync(fieldName, fieldTypeName, partName).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(AddFieldToPartAsync)} method. This current method is slated for removal in upcoming releases.")] - void AddFieldToPart(string fieldName, string displayName, string fieldTypeName, string partName) - => AddFieldToPartAsync(fieldName, displayName, fieldTypeName, partName).GetAwaiter().GetResult(); + void AddFieldToPart(string fieldName, string displayName, string fieldTypeName, string partName) => + AddFieldToPartAsync(fieldName, displayName, fieldTypeName, partName).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(RemoveFieldFromPartAsync)} method. This current method is slated for removal in upcoming releases.")] - void RemoveFieldFromPart(string fieldName, string partName) - => RemoveFieldFromPartAsync(fieldName, partName).GetAwaiter().GetResult(); + void RemoveFieldFromPart(string fieldName, string partName) => RemoveFieldFromPartAsync(fieldName, partName).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(AlterFieldAsync)} method. This current method is slated for removal in upcoming releases.")] - void AlterField(EditPartViewModel partViewModel, EditFieldViewModel fieldViewModel) - => AlterFieldAsync(partViewModel, fieldViewModel).GetAwaiter().GetResult(); + void AlterField(EditPartViewModel partViewModel, EditFieldViewModel fieldViewModel) => AlterFieldAsync(partViewModel, fieldViewModel).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(AlterTypePartAsync)} method. This current method is slated for removal in upcoming releases.")] - void AlterTypePart(EditTypePartViewModel partViewModel) - => AlterTypePartAsync(partViewModel).GetAwaiter().GetResult(); + void AlterTypePart(EditTypePartViewModel partViewModel) => AlterTypePartAsync(partViewModel).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(AlterTypePartsOrderAsync)} method. This current method is slated for removal in upcoming releases.")] - void AlterTypePartsOrder(ContentTypeDefinition typeDefinition, string[] partNames) - => AlterTypePartsOrderAsync(typeDefinition, partNames).GetAwaiter().GetResult(); + void AlterTypePartsOrder(ContentTypeDefinition typeDefinition, string[] partNames) => AlterTypePartsOrderAsync(typeDefinition, partNames).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(AlterPartFieldsOrderAsync)} method. This current method is slated for removal in upcoming releases.")] - void AlterPartFieldsOrder(ContentPartDefinition partDefinition, string[] fieldNames) - => AlterPartFieldsOrderAsync(partDefinition, fieldNames).GetAwaiter().GetResult(); + void AlterPartFieldsOrder(ContentPartDefinition partDefinition, string[] fieldNames) => AlterPartFieldsOrderAsync(partDefinition, fieldNames).GetAwaiter().GetResult(); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IStereotypeService.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IStereotypeService.cs index 069bd333a16..b6fc2080696 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IStereotypeService.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IStereotypeService.cs @@ -9,6 +9,5 @@ public interface IStereotypeService Task> GetStereotypesAsync(); [Obsolete($"Instead, utilize the {nameof(GetStereotypesAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable GetStereotypes() - => GetStereotypesAsync().GetAwaiter().GetResult(); + IEnumerable GetStereotypes() => GetStereotypesAsync().GetAwaiter().GetResult(); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IStereotypesProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IStereotypesProvider.cs index 10b3f06b44d..37282f8b5fc 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IStereotypesProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Services/IStereotypesProvider.cs @@ -9,6 +9,5 @@ public interface IStereotypesProvider Task> GetStereotypesAsync(); [Obsolete($"Instead, utilize the {nameof(GetStereotypesAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable GetStereotypes() - => GetStereotypesAsync().GetAwaiter().GetResult(); + IEnumerable GetStereotypes() => GetStereotypesAsync().GetAwaiter().GetResult(); } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/ViewModels/EditPartViewModel.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/ViewModels/EditPartViewModel.cs index 69bce871c76..4fd61436293 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/ViewModels/EditPartViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/ViewModels/EditPartViewModel.cs @@ -8,9 +8,7 @@ namespace OrchardCore.ContentTypes.ViewModels { public class EditPartViewModel { - public EditPartViewModel() - { - } + public EditPartViewModel() { } public EditPartViewModel(ContentPartDefinition contentPartDefinition) { diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/ViewModels/ReplaceContentDefinitionStepViewModel.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/ViewModels/ReplaceContentDefinitionStepViewModel.cs index 200a2fa156e..0dedb8b23fa 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/ViewModels/ReplaceContentDefinitionStepViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/ViewModels/ReplaceContentDefinitionStepViewModel.cs @@ -1,6 +1,4 @@ namespace OrchardCore.ContentTypes.ViewModels { - public class ReplaceContentDefinitionStepViewModel : ContentDefinitionStepViewModel - { - } + public class ReplaceContentDefinitionStepViewModel : ContentDefinitionStepViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AdminMenu.cs index 6d96db5449b..12d3915feb7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AdminMenu.cs @@ -18,18 +18,15 @@ namespace OrchardCore.Contents { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Contents" }, - { "contentTypeId", string.Empty }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Contents" }, { "contentTypeId", string.Empty }, }; - private static readonly RouteValueDictionary _adminListRouteValues = new() - { - { "area", "OrchardCore.Contents" }, - { "controller", "Admin" }, - { "Action", "List" }, - }; + private static readonly RouteValueDictionary _adminListRouteValues = + new() + { + { "area", "OrchardCore.Contents" }, + { "controller", "Admin" }, + { "Action", "List" }, + }; private readonly IContentDefinitionManager _contentDefinitionManager; private readonly IContentManager _contentManager; @@ -46,7 +43,8 @@ public AdminMenu( LinkGenerator linkGenerator, IAuthorizationService authorizationService, ISiteService siteService, - IStringLocalizer localizer) + IStringLocalizer localizer + ) { _contentDefinitionManager = contentDefinitionManager; _contentManager = contentManager; @@ -68,44 +66,64 @@ public async Task BuildNavigationAsync(string name, NavigationBuilder builder) var contentTypeDefinitions = (await _contentDefinitionManager.ListTypeDefinitionsAsync()).OrderBy(d => d.Name); var contentTypes = contentTypeDefinitions.Where(ctd => ctd.IsCreatable()).OrderBy(ctd => ctd.DisplayName); - await builder.AddAsync(S["Content"], NavigationConstants.AdminMenuContentPosition, async content => - { - content.AddClass("content").Id("content"); - await content.AddAsync(S["Content Items"], S["Content Items"].PrefixPosition(), async contentItems => + await builder.AddAsync( + S["Content"], + NavigationConstants.AdminMenuContentPosition, + async content => { - if (!await _authorizationService.AuthorizeContentTypeDefinitionsAsync(context.User, CommonPermissions.ListContent, contentTypes, _contentManager)) - { - contentItems.Permission(Permissions.ListContent); - } + content.AddClass("content").Id("content"); + await content.AddAsync( + S["Content Items"], + S["Content Items"].PrefixPosition(), + async contentItems => + { + if (!await _authorizationService.AuthorizeContentTypeDefinitionsAsync(context.User, CommonPermissions.ListContent, contentTypes, _contentManager)) + { + contentItems.Permission(Permissions.ListContent); + } - contentItems.Action(nameof(AdminController.List), typeof(AdminController).ControllerName(), _routeValues); - contentItems.LocalNav(); - }); - }); + contentItems.Action(nameof(AdminController.List), typeof(AdminController).ControllerName(), _routeValues); + contentItems.LocalNav(); + } + ); + } + ); var adminSettings = (await _siteService.GetSiteSettingsAsync()).As(); if (adminSettings.DisplayNewMenu && contentTypes.Any()) { - await builder.AddAsync(S["New"], "-1", async newMenu => - { - newMenu.LinkToFirstChild(false).AddClass("new").Id("new"); - foreach (var contentTypeDefinition in contentTypes) + await builder.AddAsync( + S["New"], + "-1", + async newMenu => { - var ci = await _contentManager.NewAsync(contentTypeDefinition.Name); - var cim = await _contentManager.PopulateAspectAsync(ci); - var createRouteValues = cim.CreateRouteValues; - createRouteValues.Add("returnUrl", _linkGenerator.GetPathByRouteValues(context, string.Empty, _adminListRouteValues)); - - if (createRouteValues.Count > 0) + newMenu.LinkToFirstChild(false).AddClass("new").Id("new"); + foreach (var contentTypeDefinition in contentTypes) { - newMenu.Add(new LocalizedString(contentTypeDefinition.DisplayName, contentTypeDefinition.DisplayName), "5", item => item - .Action(cim.CreateRouteValues["Action"] as string, cim.CreateRouteValues["Controller"] as string, cim.CreateRouteValues) - .Permission(ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditOwnContent.Name], contentTypeDefinition)) + var ci = await _contentManager.NewAsync(contentTypeDefinition.Name); + var cim = await _contentManager.PopulateAspectAsync(ci); + var createRouteValues = cim.CreateRouteValues; + createRouteValues.Add("returnUrl", _linkGenerator.GetPathByRouteValues(context, string.Empty, _adminListRouteValues)); + + if (createRouteValues.Count > 0) + { + newMenu.Add( + new LocalizedString(contentTypeDefinition.DisplayName, contentTypeDefinition.DisplayName), + "5", + item => + item.Action(cim.CreateRouteValues["Action"] as string, cim.CreateRouteValues["Controller"] as string, cim.CreateRouteValues) + .Permission( + ContentTypePermissionsHelper.CreateDynamicPermission( + ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditOwnContent.Name], + contentTypeDefinition + ) + ) ); + } } } - }); + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AdminNodes/ContentTypesAdminNodeDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AdminNodes/ContentTypesAdminNodeDriver.cs index afc1c7e7e0e..83429ae3ad0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AdminNodes/ContentTypesAdminNodeDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AdminNodes/ContentTypesAdminNodeDriver.cs @@ -19,11 +19,7 @@ public class ContentTypesAdminNodeDriver : DisplayDriver("ContentTypesAdminNode_Fields_TreeEdit", async model => - { - var listable = await GetListableContentTypeDefinitionsAsync(); + return Initialize( + "ContentTypesAdminNode_Fields_TreeEdit", + async model => + { + var listable = await GetListableContentTypeDefinitionsAsync(); - model.ShowAll = treeNode.ShowAll; - model.IconClass = treeNode.IconClass; - model.ContentTypes = listable.Select(x => new ContentTypeEntryViewModel - { - ContentTypeId = x.Name, - IsChecked = treeNode.ContentTypes.Any(selected => string.Equals(selected.ContentTypeId, x.Name, StringComparison.OrdinalIgnoreCase)), - IconClass = treeNode.ContentTypes.FirstOrDefault(selected => selected.ContentTypeId == x.Name)?.IconClass ?? string.Empty - }).ToArray(); - }).Location("Content"); + model.ShowAll = treeNode.ShowAll; + model.IconClass = treeNode.IconClass; + model.ContentTypes = listable + .Select(x => new ContentTypeEntryViewModel + { + ContentTypeId = x.Name, + IsChecked = treeNode.ContentTypes.Any(selected => string.Equals(selected.ContentTypeId, x.Name, StringComparison.OrdinalIgnoreCase)), + IconClass = treeNode.ContentTypes.FirstOrDefault(selected => selected.ContentTypeId == x.Name)?.IconClass ?? string.Empty + }) + .ToArray(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypesAdminNode treeNode, IUpdateModel updater) @@ -66,16 +68,12 @@ public override async Task UpdateAsync(ContentTypesAdminNode tre { treeNode.ShowAll = model.ShowAll; treeNode.IconClass = model.IconClass; - treeNode.ContentTypes = model.ContentTypes - .Where(x => x.IsChecked == true) - .Select(x => - new ContentTypeEntry - { - ContentTypeId = x.ContentTypeId, - IconClass = x.IconClass - }) + treeNode.ContentTypes = model + .ContentTypes.Where(x => x.IsChecked == true) + .Select(x => new ContentTypeEntry { ContentTypeId = x.ContentTypeId, IconClass = x.IconClass }) .ToArray(); - }; + } + ; return Edit(treeNode); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AdminNodes/ContentTypesAdminNodeNavigationBuilder.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AdminNodes/ContentTypesAdminNodeNavigationBuilder.cs index 0394ecc5ff6..0d894d007ad 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AdminNodes/ContentTypesAdminNodeNavigationBuilder.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AdminNodes/ContentTypesAdminNodeNavigationBuilder.cs @@ -28,7 +28,8 @@ public ContentTypesAdminNodeNavigationBuilder( LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService, - ILogger logger) + ILogger logger + ) { _contentDefinitionManager = contentDefinitionManager; _linkGenerator = linkGenerator; @@ -52,23 +53,33 @@ public async Task BuildNavigationAsync(MenuItem menuItem, NavigationBuilder buil var typesToShow = await GetListableContentTypeDefinitionsAsync(node); foreach (var ctd in typesToShow) { - builder.Add(new LocalizedString(ctd.DisplayName, ctd.DisplayName), cTypeMenu => - { - cTypeMenu.Url(_linkGenerator.GetPathByRouteValues(_httpContextAccessor.HttpContext, string.Empty, new + builder.Add( + new LocalizedString(ctd.DisplayName, ctd.DisplayName), + cTypeMenu => { - area = "OrchardCore.Contents", - controller = "Admin", - action = "List", - contentTypeId = ctd.Name - })); - - cTypeMenu.Priority(node.Priority); - cTypeMenu.Position(node.Position); - cTypeMenu.Permission( - ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.ViewContent.Name], ctd)); - - GetIconClasses(ctd, node).ToList().ForEach(c => cTypeMenu.AddClass(c)); - }); + cTypeMenu.Url( + _linkGenerator.GetPathByRouteValues( + _httpContextAccessor.HttpContext, + string.Empty, + new + { + area = "OrchardCore.Contents", + controller = "Admin", + action = "List", + contentTypeId = ctd.Name + } + ) + ); + + cTypeMenu.Priority(node.Priority); + cTypeMenu.Position(node.Position); + cTypeMenu.Permission( + ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.ViewContent.Name], ctd) + ); + + GetIconClasses(ctd, node).ToList().ForEach(c => cTypeMenu.AddClass(c)); + } + ); } // Add external children @@ -118,8 +129,7 @@ private static List GetIconClasses(ContentTypeDefinition contentType, Co } else { - var typeEntry = node.ContentTypes - .FirstOrDefault(x => string.Equals(x.ContentTypeId, contentType.Name, StringComparison.OrdinalIgnoreCase)); + var typeEntry = node.ContentTypes.FirstOrDefault(x => string.Equals(x.ContentTypeId, contentType.Name, StringComparison.OrdinalIgnoreCase)); return AddPrefixToClasses(typeEntry.IconClass); } @@ -127,11 +137,7 @@ private static List GetIconClasses(ContentTypeDefinition contentType, Co private static List AddPrefixToClasses(string unprefixed) { - return unprefixed?.Split(' ') - .ToList() - .Select(c => "icon-class-" + c) - .ToList() - ?? []; + return unprefixed?.Split(' ').ToList().Select(c => "icon-class-" + c).ToList() ?? []; } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Controllers/AuditTrailContentController.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Controllers/AuditTrailContentController.cs index 50694720921..978196eeece 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Controllers/AuditTrailContentController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Controllers/AuditTrailContentController.cs @@ -38,7 +38,8 @@ public AuditTrailContentController( IContentItemDisplayManager contentItemDisplayManager, INotifier notifier, IHtmlLocalizer htmlLocalizer, - ILogger logger) + ILogger logger + ) { _session = session; _contentManager = contentManager; @@ -52,10 +53,12 @@ public AuditTrailContentController( public async Task Display(string auditTrailEventId) { - var auditTrailContentEvent = (await _session.Query(collection: AuditTrailEvent.Collection) - .Where(index => index.EventId == auditTrailEventId) - .FirstOrDefaultAsync()) - ?.As(); + var auditTrailContentEvent = ( + await _session + .Query(collection: AuditTrailEvent.Collection) + .Where(index => index.EventId == auditTrailEventId) + .FirstOrDefaultAsync() + )?.As(); if (auditTrailContentEvent == null || auditTrailContentEvent.ContentItem == null) { @@ -92,9 +95,12 @@ public async Task Display(string auditTrailEventId) [HttpPost] public async Task Restore(string auditTrailEventId) { - var contentItem = (await _session.Query(collection: AuditTrailEvent.Collection) - .Where(index => index.EventId == auditTrailEventId) - .FirstOrDefaultAsync()) + var contentItem = ( + await _session + .Query(collection: AuditTrailEvent.Collection) + .Where(index => index.EventId == auditTrailEventId) + .FirstOrDefaultAsync() + ) ?.As() ?.ContentItem; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailContentEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailContentEventDisplayDriver.cs index 4baba6ce656..a34b7f673b7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailContentEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailContentEventDisplayDriver.cs @@ -34,81 +34,111 @@ public override async Task DisplayAsync(AuditTrailEvent auditTra if (!_latestVersionId.TryGetValue(contentItemId, out var latestVersionId)) { - latestVersionId = (await _session.QueryIndex(index => index.ContentItemId == contentItemId && index.Latest) - .FirstOrDefaultAsync()) - ?.ContentItemVersionId; + latestVersionId = ( + await _session.QueryIndex(index => index.ContentItemId == contentItemId && index.Latest).FirstOrDefaultAsync() + )?.ContentItemVersionId; _latestVersionId[contentItemId] = latestVersionId; } - var descriptor = _auditTrailManager.DescribeEvent(auditTrailEvent); return Combine( - Initialize("AuditTrailContentEventData_SummaryAdmin", m => BuildSummaryViewModel(m, auditTrailEvent, contentEvent, descriptor, latestVersionId)) + Initialize( + "AuditTrailContentEventData_SummaryAdmin", + m => BuildSummaryViewModel(m, auditTrailEvent, contentEvent, descriptor, latestVersionId) + ) .Location("SummaryAdmin", "EventData:10"), - Initialize("AuditTrailContentEventContent_SummaryAdmin", m => BuildSummaryViewModel(m, auditTrailEvent, contentEvent, descriptor, latestVersionId)) + Initialize( + "AuditTrailContentEventContent_SummaryAdmin", + m => BuildSummaryViewModel(m, auditTrailEvent, contentEvent, descriptor, latestVersionId) + ) .Location("SummaryAdmin", "Content:10"), - Initialize("AuditTrailContentEventActions_SummaryAdmin", m => BuildSummaryViewModel(m, auditTrailEvent, contentEvent, descriptor, latestVersionId)) + Initialize( + "AuditTrailContentEventActions_SummaryAdmin", + m => BuildSummaryViewModel(m, auditTrailEvent, contentEvent, descriptor, latestVersionId) + ) .Location("SummaryAdmin", "Actions:5"), - Initialize("AuditTrailContentEventDetail_DetailAdmin", async m => - { - BuildSummaryViewModel(m, auditTrailEvent, contentEvent, descriptor, latestVersionId); - var previousContentItem = (await _session.Query(collection: AuditTrailEvent.Collection) - .Where(index => - index.Category == "Content" && - index.CreatedUtc <= auditTrailEvent.CreatedUtc && - index.EventId != auditTrailEvent.EventId && - index.CorrelationId == contentEvent.ContentItem.ContentItemId) - .OrderByDescending(index => index.Id) - .FirstOrDefaultAsync())? - .As() - .ContentItem; + Initialize( + "AuditTrailContentEventDetail_DetailAdmin", + async m => + { + BuildSummaryViewModel(m, auditTrailEvent, contentEvent, descriptor, latestVersionId); + var previousContentItem = ( + await _session + .Query(collection: AuditTrailEvent.Collection) + .Where(index => + index.Category == "Content" + && index.CreatedUtc <= auditTrailEvent.CreatedUtc + && index.EventId != auditTrailEvent.EventId + && index.CorrelationId == contentEvent.ContentItem.ContentItemId + ) + .OrderByDescending(index => index.Id) + .FirstOrDefaultAsync() + ) + ?.As() + .ContentItem; - if (previousContentItem != null) - { - var current = JObject.FromObject(contentEvent.ContentItem); - var previous = JObject.FromObject(previousContentItem); - previous.Remove(nameof(AuditTrailPart)); - current.Remove(nameof(AuditTrailPart)); + if (previousContentItem != null) + { + var current = JObject.FromObject(contentEvent.ContentItem); + var previous = JObject.FromObject(previousContentItem); + previous.Remove(nameof(AuditTrailPart)); + current.Remove(nameof(AuditTrailPart)); - m.PreviousContentItem = previousContentItem; + m.PreviousContentItem = previousContentItem; - m.Previous = previous.ToString(); - m.Current = current.ToString(); - } - }).Location("DetailAdmin", "Content:5"), - Initialize("AuditTrailContentEventDiff_DetailAdmin", async m => - { - BuildSummaryViewModel(m, auditTrailEvent, contentEvent, descriptor, latestVersionId); - var previousContentItem = (await _session.Query(collection: AuditTrailEvent.Collection) - .Where(index => - index.Category == "Content" && - index.CreatedUtc <= auditTrailEvent.CreatedUtc && - index.EventId != auditTrailEvent.EventId && - index.CorrelationId == contentEvent.ContentItem.ContentItemId) - .OrderByDescending(index => index.Id) - .FirstOrDefaultAsync())? - .As() - .ContentItem; + m.Previous = previous.ToString(); + m.Current = current.ToString(); + } + } + ) + .Location("DetailAdmin", "Content:5"), + Initialize( + "AuditTrailContentEventDiff_DetailAdmin", + async m => + { + BuildSummaryViewModel(m, auditTrailEvent, contentEvent, descriptor, latestVersionId); + var previousContentItem = ( + await _session + .Query(collection: AuditTrailEvent.Collection) + .Where(index => + index.Category == "Content" + && index.CreatedUtc <= auditTrailEvent.CreatedUtc + && index.EventId != auditTrailEvent.EventId + && index.CorrelationId == contentEvent.ContentItem.ContentItemId + ) + .OrderByDescending(index => index.Id) + .FirstOrDefaultAsync() + ) + ?.As() + .ContentItem; - if (previousContentItem != null) - { - var current = JObject.FromObject(contentEvent.ContentItem); - var previous = JObject.FromObject(previousContentItem); - previous.Remove(nameof(AuditTrailPart)); - current.Remove(nameof(AuditTrailPart)); + if (previousContentItem != null) + { + var current = JObject.FromObject(contentEvent.ContentItem); + var previous = JObject.FromObject(previousContentItem); + previous.Remove(nameof(AuditTrailPart)); + current.Remove(nameof(AuditTrailPart)); - m.PreviousContentItem = previousContentItem; + m.PreviousContentItem = previousContentItem; - m.Previous = previous.ToString(); - m.Current = current.ToString(); - } - }).Location("DetailAdmin", "Content:5#Diff") + m.Previous = previous.ToString(); + m.Current = current.ToString(); + } + } + ) + .Location("DetailAdmin", "Content:5#Diff") ); } - private static void BuildSummaryViewModel(AuditTrailContentEventViewModel m, AuditTrailEvent model, AuditTrailContentEvent contentEvent, AuditTrailEventDescriptor descriptor, string latestVersionId) + private static void BuildSummaryViewModel( + AuditTrailContentEventViewModel m, + AuditTrailEvent model, + AuditTrailContentEvent contentEvent, + AuditTrailEventDescriptor descriptor, + string latestVersionId + ) { m.AuditTrailEvent = model; m.Descriptor = descriptor; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailPartDisplayDriver.cs index f2ca102e634..e048d9b5af2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailPartDisplayDriver.cs @@ -16,13 +16,16 @@ public override IDisplayResult Edit(AuditTrailPart part, BuildPartEditorContext var settings = context.TypePartDefinition.GetSettings(); if (settings.ShowCommentInput) { - return Initialize(GetEditorShapeType(context), model => - { - if (part.ShowComment) + return Initialize( + GetEditorShapeType(context), + model => { - model.Comment = part.Comment; + if (part.ShowComment) + { + model.Comment = part.Comment; + } } - }); + ); } return null; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailPartSettingsDisplayDriver.cs index b297dd8834c..80379c1879b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/AuditTrailPartSettingsDisplayDriver.cs @@ -13,27 +13,30 @@ public class AuditTrailPartSettingsDisplayDriver : ContentTypePartDefinitionDisp { public override IDisplayResult Edit(ContentTypePartDefinition model, IUpdateModel updater) { - if (!string.Equals(nameof(AuditTrailPart), model.PartDefinition.Name)) return null; + if (!string.Equals(nameof(AuditTrailPart), model.PartDefinition.Name)) + return null; - return Initialize("AuditTrailPartSettings_Edit", viewModel => - { - var settings = model.GetSettings(); - viewModel.ShowCommentInput = settings.ShowCommentInput; - }).Location("Content"); + return Initialize( + "AuditTrailPartSettings_Edit", + viewModel => + { + var settings = model.GetSettings(); + viewModel.ShowCommentInput = settings.ShowCommentInput; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition model, UpdateTypePartEditorContext context) { - if (!string.Equals(nameof(AuditTrailPart), model.PartDefinition.Name)) return null; + if (!string.Equals(nameof(AuditTrailPart), model.PartDefinition.Name)) + return null; var viewModel = new AuditTrailPartSettingsViewModel(); if (await context.Updater.TryUpdateModelAsync(viewModel, Prefix, m => m.ShowCommentInput)) { - context.Builder.WithSettings(new AuditTrailPartSettings - { - ShowCommentInput = viewModel.ShowCommentInput - }); + context.Builder.WithSettings(new AuditTrailPartSettings { ShowCommentInput = viewModel.ShowCommentInput }); } return Edit(model, context.Updater); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/ContentAuditTrailSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/ContentAuditTrailSettingsDisplayDriver.cs index 36e63aa1d6a..dca66471a16 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/ContentAuditTrailSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Drivers/ContentAuditTrailSettingsDisplayDriver.cs @@ -31,10 +31,15 @@ public override async Task EditAsync(ContentAuditTrailSettings s return null; } - return Initialize("ContentAuditTrailSettings_Edit", model => - { - model.AllowedContentTypes = section.AllowedContentTypes; - }).Location("Content:10#Content;5").OnGroup(AuditTrailSettingsGroup.Id); + return Initialize( + "ContentAuditTrailSettings_Edit", + model => + { + model.AllowedContentTypes = section.AllowedContentTypes; + } + ) + .Location("Content:10#Content;5") + .OnGroup(AuditTrailSettingsGroup.Id); } public override async Task UpdateAsync(ContentAuditTrailSettings section, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Handlers/AuditTrailContentHandler.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Handlers/AuditTrailContentHandler.cs index 8d325601599..aece07665ec 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Handlers/AuditTrailContentHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Handlers/AuditTrailContentHandler.cs @@ -25,11 +25,7 @@ public class AuditTrailContentHandler : ContentHandlerBase private readonly HashSet _restoring = []; - public AuditTrailContentHandler( - YesSql.ISession session, - ISiteService siteService, - IAuditTrailManager auditTrailManager, - IHttpContextAccessor httpContextAccessor) + public AuditTrailContentHandler(YesSql.ISession session, ISiteService siteService, IAuditTrailManager auditTrailManager, IHttpContextAccessor httpContextAccessor) { _session = session; _siteService = siteService; @@ -37,23 +33,17 @@ public AuditTrailContentHandler( _httpContextAccessor = httpContextAccessor; } - public override Task DraftSavedAsync(SaveDraftContentContext context) - => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Saved, context.ContentItem); + public override Task DraftSavedAsync(SaveDraftContentContext context) => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Saved, context.ContentItem); - public override Task CreatedAsync(CreateContentContext context) - => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Created, context.ContentItem); + public override Task CreatedAsync(CreateContentContext context) => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Created, context.ContentItem); - public override Task PublishedAsync(PublishContentContext context) - => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Published, context.ContentItem); + public override Task PublishedAsync(PublishContentContext context) => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Published, context.ContentItem); - public override Task UnpublishedAsync(PublishContentContext context) - => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Unpublished, context.ContentItem); + public override Task UnpublishedAsync(PublishContentContext context) => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Unpublished, context.ContentItem); - public override Task RemovedAsync(RemoveContentContext context) - => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Removed, context.ContentItem); + public override Task RemovedAsync(RemoveContentContext context) => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Removed, context.ContentItem); - public override Task ClonedAsync(CloneContentContext context) - => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Cloned, context.ContentItem); + public override Task ClonedAsync(CloneContentContext context) => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Cloned, context.ContentItem); public override Task RestoringAsync(RestoreContentContext context) { @@ -62,8 +52,7 @@ public override Task RestoringAsync(RestoreContentContext context) return Task.CompletedTask; } - public override Task RestoredAsync(RestoreContentContext context) - => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Restored, context.ContentItem); + public override Task RestoredAsync(RestoreContentContext context) => RecordAuditTrailEventAsync(ContentAuditTrailEventConfiguration.Restored, context.ContentItem); private async Task RecordAuditTrailEventAsync(string name, IContent content) { @@ -80,24 +69,18 @@ private async Task RecordAuditTrailEventAsync(string name, IContent content) return; } - var versionNumber = await _session - .QueryIndex(index => index.ContentItemId == content.ContentItem.ContentItemId) - .CountAsync(); + var versionNumber = await _session.QueryIndex(index => index.ContentItemId == content.ContentItem.ContentItemId).CountAsync(); await _auditTrailManager.RecordEventAsync( - new AuditTrailContext - ( + new AuditTrailContext( name, ContentAuditTrailEventConfiguration.Content, content.ContentItem.ContentItemId, _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), _httpContextAccessor.HttpContext.User?.Identity?.Name, - new AuditTrailContentEvent - { - ContentItem = content.ContentItem, - VersionNumber = versionNumber - } - )); + new AuditTrailContentEvent { ContentItem = content.ContentItem, VersionNumber = versionNumber } + ) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Migrations.cs index 3cbcae6204a..1f93d7c7b07 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Migrations.cs @@ -18,9 +18,10 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("AuditTrailPart", part => part - .Attachable() - .WithDescription("Allows editors to enter a comment to be saved into the Audit Trail event when saving a content item.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "AuditTrailPart", + part => part.Attachable().WithDescription("Allows editors to enter a comment to be saved into the Audit Trail event when saving a content item.") + ); return 1; } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Services/ContentAuditTrailEventConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Services/ContentAuditTrailEventConfiguration.cs index 006b5e1a3ff..3512b8def42 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Services/ContentAuditTrailEventConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Services/ContentAuditTrailEventConfiguration.cs @@ -16,7 +16,8 @@ public class ContentAuditTrailEventConfiguration : IConfigureOptions(Content, S => S["Content"]) + options + .For(Content, S => S["Content"]) .WithEvent(Created, S => S["Created"], S => S["A content item was created."], true) .WithEvent(Saved, S => S["Saved"], S => S["A content item was saved."], true) .WithEvent(Published, S => S["Published"], S => S["A content item was published."], true) diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Startup.cs index 9001b4f1302..11410e827de 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/Startup.cs @@ -24,8 +24,7 @@ public class Startup : StartupBase public override void ConfigureServices(IServiceCollection services) { services.AddDataMigration(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddScoped(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/AdminController.cs index 33ffa0dd8f7..3851b531bda 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/AdminController.cs @@ -63,7 +63,8 @@ public AdminController( ILogger logger, IHtmlLocalizer htmlLocalizer, IStringLocalizer stringLocalizer, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _authorizationService = authorizationService; _notifier = notifier; @@ -89,11 +90,10 @@ public async Task List( ContentOptionsViewModel options, PagerParameters pagerParameters, string contentTypeId = "", - string stereotype = "") + string stereotype = "" + ) { - var contentTypeDefinitions = (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .OrderBy(ctd => ctd.DisplayName) - .ToList(); + var contentTypeDefinitions = (await _contentDefinitionManager.ListTypeDefinitionsAsync()).OrderBy(ctd => ctd.DisplayName).ToList(); if (!await _authorizationService.AuthorizeContentTypeDefinitionsAsync(User, CommonPermissions.ListContent, contentTypeDefinitions, _contentManager)) { @@ -145,9 +145,7 @@ public async Task List( if (options.CreatableTypes == null) { // At this point, the creatable types were not yet populated. Populate them using all creatable types. - var creatableContentTypeDefinitions = contentTypeDefinitions - .Where(ctd => ctd.IsCreatable()) - .ToArray(); + var creatableContentTypeDefinitions = contentTypeDefinitions.Where(ctd => ctd.IsCreatable()).ToArray(); options.CreatableTypes = await GetCreatableTypeOptionsAsync(false, creatableContentTypeDefinitions); } @@ -181,8 +179,7 @@ public async Task List( new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), ]; - if (options.ContentTypeOptions == null - && (string.IsNullOrEmpty(options.SelectedContentType) || string.IsNullOrEmpty(contentTypeId))) + if (options.ContentTypeOptions == null && (string.IsNullOrEmpty(options.SelectedContentType) || string.IsNullOrEmpty(contentTypeId))) { options.ContentTypeOptions = await GetListableContentTypeOptionsAsync(contentTypeDefinitions, options.SelectedContentType, true); } @@ -201,7 +198,11 @@ public async Task List( options.RouteValues.TryAdd("q", options.FilterResult.ToString()); var pager = new Pager(pagerParameters, _pagerOptions.GetPageSize()); - dynamic pagerShape = await _shapeFactory.PagerAsync(pager, _pagerOptions.MaxPagedCount > 0 ? _pagerOptions.MaxPagedCount : await query.CountAsync(), options.RouteValues); + dynamic pagerShape = await _shapeFactory.PagerAsync( + pager, + _pagerOptions.MaxPagedCount > 0 ? _pagerOptions.MaxPagedCount : await query.CountAsync(), + options.RouteValues + ); // Load items so that loading handlers are invoked. var pageOfContentItems = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync(_contentManager); @@ -222,13 +223,16 @@ public async Task List( var header = await _contentOptionsDisplayManager.BuildEditorAsync(options, _updateModelAccessor.ModelUpdater, false, string.Empty, string.Empty); - var shapeViewModel = await _shapeFactory.CreateAsync("ContentsAdminList", viewModel => - { - viewModel.ContentItems = contentItemSummaries; - viewModel.Pager = pagerShape; - viewModel.Options = options; - viewModel.Header = header; - }); + var shapeViewModel = await _shapeFactory.CreateAsync( + "ContentsAdminList", + viewModel => + { + viewModel.ContentItems = contentItemSummaries; + viewModel.Pager = pagerShape; + viewModel.Options = options; + viewModel.Header = header; + } + ); return View(shapeViewModel); } @@ -339,16 +343,23 @@ public async Task Create(string id) public Task CreatePOST(string id, [Bind(Prefix = "submit.Save")] string submitSave, string returnUrl) { var stayOnSamePage = submitSave == "submit.SaveAndContinue"; - return CreatePOST(id, returnUrl, stayOnSamePage, async contentItem => - { - await _contentManager.SaveDraftAsync(contentItem); + return CreatePOST( + id, + returnUrl, + stayOnSamePage, + async contentItem => + { + await _contentManager.SaveDraftAsync(contentItem); - var typeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); + var typeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); - await _notifier.SuccessAsync(string.IsNullOrWhiteSpace(typeDefinition?.DisplayName) - ? H["Your content draft has been saved."] - : H["Your {0} draft has been saved.", typeDefinition.DisplayName]); - }); + await _notifier.SuccessAsync( + string.IsNullOrWhiteSpace(typeDefinition?.DisplayName) + ? H["Your content draft has been saved."] + : H["Your {0} draft has been saved.", typeDefinition.DisplayName] + ); + } + ); } [HttpPost, ActionName(nameof(Create))] @@ -367,16 +378,23 @@ public async Task CreateAndPublishPOST(string id, [Bind(Prefix = return Forbid(); } - return await CreatePOST(id, returnUrl, stayOnSamePage, async contentItem => - { - await _contentManager.PublishAsync(contentItem); + return await CreatePOST( + id, + returnUrl, + stayOnSamePage, + async contentItem => + { + await _contentManager.PublishAsync(contentItem); - var typeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); + var typeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); - await _notifier.SuccessAsync(string.IsNullOrWhiteSpace(typeDefinition.DisplayName) - ? H["Your content has been published."] - : H["Your {0} has been published.", typeDefinition.DisplayName]); - }); + await _notifier.SuccessAsync( + string.IsNullOrWhiteSpace(typeDefinition.DisplayName) + ? H["Your content has been published."] + : H["Your {0} has been published.", typeDefinition.DisplayName] + ); + } + ); } [Admin("Contents/ContentItems/{contentItemId}/Display", "AdminContentItem")] @@ -424,16 +442,23 @@ public async Task Edit(string contentItemId) public Task EditPOST(string contentItemId, [Bind(Prefix = "submit.Save")] string submitSave, string returnUrl) { var stayOnSamePage = submitSave == "submit.SaveAndContinue"; - return EditPOST(contentItemId, returnUrl, stayOnSamePage, async contentItem => - { - await _contentManager.SaveDraftAsync(contentItem); + return EditPOST( + contentItemId, + returnUrl, + stayOnSamePage, + async contentItem => + { + await _contentManager.SaveDraftAsync(contentItem); - var typeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); + var typeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); - await _notifier.SuccessAsync(string.IsNullOrWhiteSpace(typeDefinition?.DisplayName) - ? H["Your content draft has been saved."] - : H["Your {0} draft has been saved.", typeDefinition.DisplayName]); - }); + await _notifier.SuccessAsync( + string.IsNullOrWhiteSpace(typeDefinition?.DisplayName) + ? H["Your content draft has been saved."] + : H["Your {0} draft has been saved.", typeDefinition.DisplayName] + ); + } + ); } [HttpPost, ActionName(nameof(Edit))] @@ -454,16 +479,23 @@ public async Task EditAndPublishPOST(string contentItemId, [Bind( return Forbid(); } - return await EditPOST(contentItemId, returnUrl, stayOnSamePage, async contentItem => - { - await _contentManager.PublishAsync(contentItem); + return await EditPOST( + contentItemId, + returnUrl, + stayOnSamePage, + async contentItem => + { + await _contentManager.PublishAsync(contentItem); - var typeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); + var typeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); - await _notifier.SuccessAsync(string.IsNullOrWhiteSpace(typeDefinition?.DisplayName) - ? H["Your content has been published."] - : H["Your {0} has been published.", typeDefinition.DisplayName]); - }); + await _notifier.SuccessAsync( + string.IsNullOrWhiteSpace(typeDefinition?.DisplayName) + ? H["Your content has been published."] + : H["Your {0} has been published.", typeDefinition.DisplayName] + ); + } + ); } [HttpPost] @@ -519,9 +551,9 @@ public async Task DiscardDraft(string contentItemId, string retur var typeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); - await _notifier.SuccessAsync(string.IsNullOrWhiteSpace(typeDefinition?.DisplayName) - ? H["The draft has been removed."] - : H["The {0} draft has been removed.", typeDefinition.DisplayName]); + await _notifier.SuccessAsync( + string.IsNullOrWhiteSpace(typeDefinition?.DisplayName) ? H["The draft has been removed."] : H["The {0} draft has been removed.", typeDefinition.DisplayName] + ); } return Url.IsLocalUrl(returnUrl) ? (IActionResult)this.LocalRedirect(returnUrl, true) : RedirectToAction(nameof(List)); @@ -544,9 +576,9 @@ public async Task Remove(string contentItemId, string returnUrl) var typeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); - await _notifier.SuccessAsync(string.IsNullOrWhiteSpace(typeDefinition?.DisplayName) - ? H["That content has been removed."] - : H["That {0} has been removed.", typeDefinition.DisplayName]); + await _notifier.SuccessAsync( + string.IsNullOrWhiteSpace(typeDefinition?.DisplayName) ? H["That content has been removed."] : H["That {0} has been removed.", typeDefinition.DisplayName] + ); } return Url.IsLocalUrl(returnUrl) ? (IActionResult)this.LocalRedirect(returnUrl, true) : RedirectToAction(nameof(List)); @@ -709,7 +741,11 @@ private async Task> GetCreatableTypeOptionsAsync(bool canCr return options; } - private async Task> GetListableContentTypeOptionsAsync(IEnumerable definitions, string selectedContentType, bool showSelectAll = true) + private async Task> GetListableContentTypeOptionsAsync( + IEnumerable definitions, + string selectedContentType, + bool showSelectAll = true + ) { var currentUserId = CurrentUserId(); @@ -718,12 +754,12 @@ private async Task> GetListableContentTypeOptionsAsync(IEnu if (showSelectAll) { items.Add(new SelectListItem(S["All content types"], string.Empty)); - }; + } + ; foreach (var definition in definitions) { - if (!definition.IsListable() - || !await _authorizationService.AuthorizeContentTypeAsync(User, CommonPermissions.ListContent, definition.Name, currentUserId)) + if (!definition.IsListable() || !await _authorizationService.AuthorizeContentTypeAsync(User, CommonPermissions.ListContent, definition.Name, currentUserId)) { continue; } @@ -744,13 +780,10 @@ private async Task CreateContentItemOwnedByCurrentUserAsync(string private string _currentUserId; - private string CurrentUserId() - => _currentUserId ??= User.FindFirstValue(ClaimTypes.NameIdentifier); + private string CurrentUserId() => _currentUserId ??= User.FindFirstValue(ClaimTypes.NameIdentifier); - private async Task IsAuthorizedAsync(Permission permission) - => await _authorizationService.AuthorizeAsync(User, permission); + private async Task IsAuthorizedAsync(Permission permission) => await _authorizationService.AuthorizeAsync(User, permission); - private async Task IsAuthorizedAsync(Permission permission, object resource) - => await _authorizationService.AuthorizeAsync(User, permission, resource); + private async Task IsAuthorizedAsync(Permission permission, object resource) => await _authorizationService.AuthorizeAsync(User, permission, resource); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/ApiController.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/ApiController.cs index 8b0826f11c1..659ed9bb11a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/ApiController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/ApiController.cs @@ -29,7 +29,8 @@ public ApiController( IContentManager contentManager, IContentDefinitionManager contentDefinitionManager, IAuthorizationService authorizationService, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _contentManager = contentManager; _contentDefinitionManager = contentDefinitionManager; @@ -128,12 +129,14 @@ public async Task Post(ContentItem model, bool draft = false) // intended to add model errors (only drivers), a WF content task may be executed inline and add some model errors. if (!ModelState.IsValid) { - return ValidationProblem(new ValidationProblemDetails(ModelState) - { - Title = S["One or more validation errors occurred."], - Detail = string.Join(", ", ModelState.Values.SelectMany(x => x.Errors.Select(x => x.ErrorMessage))), - Status = (int)HttpStatusCode.BadRequest, - }); + return ValidationProblem( + new ValidationProblemDetails(ModelState) + { + Title = S["One or more validation errors occurred."], + Detail = string.Join(", ", ModelState.Values.SelectMany(x => x.Errors.Select(x => x.ErrorMessage))), + Status = (int)HttpStatusCode.BadRequest, + } + ); } } else @@ -158,12 +161,14 @@ public async Task Post(ContentItem model, bool draft = false) // intended to add model errors (only drivers), a WF content task may be executed inline and add some model errors. if (!ModelState.IsValid) { - return ValidationProblem(new ValidationProblemDetails(ModelState) - { - Title = S["One or more validation errors occurred."], - Detail = string.Join(", ", ModelState.Values.SelectMany(x => x.Errors.Select(x => x.ErrorMessage))), - Status = (int)HttpStatusCode.BadRequest, - }); + return ValidationProblem( + new ValidationProblemDetails(ModelState) + { + Title = S["One or more validation errors occurred."], + Detail = string.Join(", ", ModelState.Values.SelectMany(x => x.Errors.Select(x => x.ErrorMessage))), + Status = (int)HttpStatusCode.BadRequest, + } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/ItemController.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/ItemController.cs index 5f6c9cee5d8..a604286296a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/ItemController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Controllers/ItemController.cs @@ -18,7 +18,8 @@ public ItemController( IContentManager contentManager, IContentItemDisplayManager contentItemDisplayManager, IAuthorizationService authorizationService, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _authorizationService = authorizationService; _contentItemDisplayManager = contentItemDisplayManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/AddToDeploymentPlanContentDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/AddToDeploymentPlanContentDriver.cs index fe66a8bfe54..bb81da4c5d8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/AddToDeploymentPlanContentDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/AddToDeploymentPlanContentDriver.cs @@ -18,13 +18,13 @@ public AddToDeploymentPlanContentDriver(IDeploymentPlanService deploymentPlanSer public override IDisplayResult Display(ContentItem model) { return Combine( - Dynamic("AddToDeploymentPlan_Modal__ActionDeploymentPlan") - .Location("SummaryAdmin", "ActionsMenu:30") - .RenderWhen(async () => await _deploymentPlanService.DoesUserHavePermissionsAsync()), - Shape("AddToDeploymentPlan_SummaryAdmin__Button__Actions", new ContentItemViewModel(model)) - .Location("SummaryAdmin", "ActionsMenu:30") - .RenderWhen(async () => await _deploymentPlanService.DoesUserHavePermissionsAsync()) - ); + Dynamic("AddToDeploymentPlan_Modal__ActionDeploymentPlan") + .Location("SummaryAdmin", "ActionsMenu:30") + .RenderWhen(async () => await _deploymentPlanService.DoesUserHavePermissionsAsync()), + Shape("AddToDeploymentPlan_SummaryAdmin__Button__Actions", new ContentItemViewModel(model)) + .Location("SummaryAdmin", "ActionsMenu:30") + .RenderWhen(async () => await _deploymentPlanService.DoesUserHavePermissionsAsync()) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/AddToDeploymentPlanController.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/AddToDeploymentPlanController.cs index a156987b30e..863254d5882 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/AddToDeploymentPlanController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/AddToDeploymentPlanController.cs @@ -33,7 +33,7 @@ public AddToDeploymentPlanController( IEnumerable factories, INotifier notifier, IHtmlLocalizer htmlLocalizer - ) + ) { _authorizationService = authorizationService; _contentManager = contentManager; @@ -46,9 +46,12 @@ IHtmlLocalizer htmlLocalizer [HttpPost] public async Task AddContentItem(long deploymentPlanId, string returnUrl, string contentItemId) { - if (!(await _authorizationService.AuthorizeAsync(User, OrchardCore.Deployment.CommonPermissions.ManageDeploymentPlan) && - await _authorizationService.AuthorizeAsync(User, OrchardCore.Deployment.CommonPermissions.Export) - )) + if ( + !( + await _authorizationService.AuthorizeAsync(User, OrchardCore.Deployment.CommonPermissions.ManageDeploymentPlan) + && await _authorizationService.AuthorizeAsync(User, OrchardCore.Deployment.CommonPermissions.Export) + ) + ) { return Forbid(); } @@ -102,9 +105,12 @@ public async Task AddContentItems(long deploymentPlanId, string r return this.LocalRedirect(returnUrl, true); } - if (!(await _authorizationService.AuthorizeAsync(User, OrchardCore.Deployment.CommonPermissions.ManageDeploymentPlan) && - await _authorizationService.AuthorizeAsync(User, OrchardCore.Deployment.CommonPermissions.Export) - )) + if ( + !( + await _authorizationService.AuthorizeAsync(User, OrchardCore.Deployment.CommonPermissions.ManageDeploymentPlan) + && await _authorizationService.AuthorizeAsync(User, OrchardCore.Deployment.CommonPermissions.Export) + ) + ) { return Forbid(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/ContentItemDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/ContentItemDeploymentSource.cs index ab433038e8a..d9258abd2ec 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/ContentItemDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/ContentItemDeploymentSource.cs @@ -42,11 +42,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan } else { - result.Steps.Add(new JsonObject - { - ["name"] = "Content", - ["data"] = new JsonArray(jContentItem), - }); + result.Steps.Add(new JsonObject { ["name"] = "Content", ["data"] = new JsonArray(jContentItem), }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/ContentItemDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/ContentItemDeploymentStepDriver.cs index 6d6467296fe..600aa137b89 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/ContentItemDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AddToDeploymentPlan/ContentItemDeploymentStepDriver.cs @@ -14,8 +14,7 @@ public class ContentItemDeploymentStepDriver : DisplayDriver stringLocalizer) + public ContentItemDeploymentStepDriver(IContentManager contentManager, IStringLocalizer stringLocalizer) { _contentManager = contentManager; S = stringLocalizer; @@ -23,19 +22,22 @@ public ContentItemDeploymentStepDriver(IContentManager contentManager, public override IDisplayResult Display(ContentItemDeploymentStep step) { - return - Combine( - View("ContentItemDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("ContentItemDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("ContentItemDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("ContentItemDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(ContentItemDeploymentStep step) { - return Initialize("ContentItemDeploymentStep_Fields_Edit", model => - { - model.ContentItemId = step.ContentItemId; - }).Location("Content"); + return Initialize( + "ContentItemDeploymentStep_Fields_Edit", + model => + { + model.ContentItemId = step.ContentItemId; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentItemDeploymentStep step, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AllContentDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AllContentDeploymentSource.cs index 25c2c8002c1..d20d2c187ba 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AllContentDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AllContentDeploymentSource.cs @@ -26,11 +26,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan } var data = new JsonArray(); - result.Steps.Add(new JsonObject - { - ["name"] = "Content", - ["data"] = data, - }); + result.Steps.Add(new JsonObject { ["name"] = "Content", ["data"] = data, }); foreach (var contentItem in await _session.Query(x => x.Published).ListAsync()) { diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AllContentDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AllContentDeploymentStepDriver.cs index f560dfe1618..421466a72e2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AllContentDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/AllContentDeploymentStepDriver.cs @@ -11,19 +11,22 @@ public class AllContentDeploymentStepDriver : DisplayDriver("AllContentDeploymentStep_Fields_Edit", model => - { - model.ExportAsSetupRecipe = step.ExportAsSetupRecipe; - }).Location("Content"); + return Initialize( + "AllContentDeploymentStep_Fields_Edit", + model => + { + model.ExportAsSetupRecipe = step.ExportAsSetupRecipe; + } + ) + .Location("Content"); } public override async Task UpdateAsync(AllContentDeploymentStep step, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ContentDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ContentDeploymentSource.cs index 02cd18cdad5..0c70c05abe2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ContentDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ContentDeploymentSource.cs @@ -53,11 +53,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan if (data.HasValues()) { - var jobj = new JsonObject - { - ["name"] = "content", - ["data"] = data, - }; + var jobj = new JsonObject { ["name"] = "content", ["data"] = data, }; result.Steps.Add(jobj); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ContentDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ContentDeploymentStepDriver.cs index b31672ecc8b..1211b89180d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ContentDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ContentDeploymentStepDriver.cs @@ -11,20 +11,23 @@ public class ContentDeploymentStepDriver : DisplayDriver("ContentDeploymentStep_Fields_Edit", model => - { - model.ContentTypes = step.ContentTypes; - model.ExportAsSetupRecipe = step.ExportAsSetupRecipe; - }).Location("Content"); + return Initialize( + "ContentDeploymentStep_Fields_Edit", + model => + { + model.ContentTypes = step.ContentTypes; + model.ExportAsSetupRecipe = step.ExportAsSetupRecipe; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentDeploymentStep step, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/Download/DownloadContentDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/Download/DownloadContentDriver.cs index f7cf815f5cb..19d919884d9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/Download/DownloadContentDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/Download/DownloadContentDriver.cs @@ -12,9 +12,7 @@ public class DownloadContentDriver : ContentDisplayDriver private readonly IHttpContextAccessor _httpContextAccessor; private readonly IAuthorizationService _authorizationService; - public DownloadContentDriver( - IHttpContextAccessor httpContextAccessor, - IAuthorizationService authorizationService) + public DownloadContentDriver(IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -24,18 +22,19 @@ public override IDisplayResult Display(ContentItem contentItem) { var context = _httpContextAccessor.HttpContext; - return Shape("Download_SummaryAdmin__Button__Actions", new ContentItemViewModel(contentItem)).Location("SummaryAdmin", "ActionsMenu:20") - .RenderWhen(async () => - { - var hasEditPermission = await _authorizationService.AuthorizeAsync(context.User, OrchardCore.Deployment.CommonPermissions.Export, contentItem); + return Shape("Download_SummaryAdmin__Button__Actions", new ContentItemViewModel(contentItem)) + .Location("SummaryAdmin", "ActionsMenu:20") + .RenderWhen(async () => + { + var hasEditPermission = await _authorizationService.AuthorizeAsync(context.User, OrchardCore.Deployment.CommonPermissions.Export, contentItem); - if (hasEditPermission) - { - return true; - } + if (hasEditPermission) + { + return true; + } - return false; - }); + return false; + }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/Download/DownloadController.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/Download/DownloadController.cs index 376f143cb7a..58e6dce3f89 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/Download/DownloadController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/Download/DownloadController.cs @@ -16,10 +16,7 @@ public class DownloadController : Controller private readonly IAuthorizationService _authorizationService; private readonly IContentManager _contentManager; - public DownloadController( - IAuthorizationService authorizationService, - IContentManager contentManager - ) + public DownloadController(IAuthorizationService authorizationService, IContentManager contentManager) { _authorizationService = authorizationService; _contentManager = contentManager; @@ -47,11 +44,7 @@ public async Task Display(string contentItemId, bool latest = fal return Forbid(); } - var model = new DisplayJsonContentItemViewModel - { - ContentItem = contentItem, - ContentItemJson = JObject.FromObject(contentItem).ToString() - }; + var model = new DisplayJsonContentItemViewModel { ContentItem = contentItem, ContentItemJson = JObject.FromObject(contentItem).ToString() }; return View(model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetAdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetAdminMenu.cs index fd2ddc2d675..e160ce14f75 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetAdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetAdminMenu.cs @@ -7,11 +7,8 @@ namespace OrchardCore.Contents.Deployment.ExportContentToDeploymentTarget { public class ExportContentToDeploymentTargetAdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", ExportContentToDeploymentTargetSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = + new() { { "area", "OrchardCore.Settings" }, { "groupId", ExportContentToDeploymentTargetSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -27,18 +24,28 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Import/Export"], S["Import/Export"].PrefixPosition(), import => import - .Add(S["Settings"], settings => settings - .Add(S["Export Target Settings"], S["Export Target Settings"].PrefixPosition(), targetSettings => targetSettings - .Action("Index", "Admin", _routeValues) - .Permission(OrchardCore.Deployment.CommonPermissions.ManageDeploymentPlan) - .LocalNav() + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Import/Export"], + S["Import/Export"].PrefixPosition(), + import => + import.Add( + S["Settings"], + settings => + settings.Add( + S["Export Target Settings"], + S["Export Target Settings"].PrefixPosition(), + targetSettings => + targetSettings + .Action("Index", "Admin", _routeValues) + .Permission(OrchardCore.Deployment.CommonPermissions.ManageDeploymentPlan) + .LocalNav() + ) ) - ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetContentDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetContentDriver.cs index 92619b9059f..2d31f4a60db 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetContentDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetContentDriver.cs @@ -12,9 +12,7 @@ public class ExportContentToDeploymentTargetContentDriver : ContentDisplayDriver private readonly IDeploymentPlanService _deploymentPlanService; private readonly ISiteService _siteService; - public ExportContentToDeploymentTargetContentDriver( - IDeploymentPlanService deploymentPlanService, - ISiteService siteService) + public ExportContentToDeploymentTargetContentDriver(IDeploymentPlanService deploymentPlanService, ISiteService siteService) { _deploymentPlanService = deploymentPlanService; _siteService = siteService; @@ -55,7 +53,7 @@ public override IDisplayResult Display(ContentItem model) return false; }) - ); + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetContentsAdminListDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetContentsAdminListDisplayDriver.cs index 09874c97824..6c99509ad30 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetContentsAdminListDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetContentsAdminListDisplayDriver.cs @@ -12,9 +12,7 @@ public class ExportContentToDeploymentTargetContentsAdminListDisplayDriver : Dis private readonly IDeploymentPlanService _deploymentPlanService; private readonly ISiteService _siteService; - public ExportContentToDeploymentTargetContentsAdminListDisplayDriver( - IDeploymentPlanService deploymentPlanService, - ISiteService siteService) + public ExportContentToDeploymentTargetContentsAdminListDisplayDriver(IDeploymentPlanService deploymentPlanService, ISiteService siteService) { _deploymentPlanService = deploymentPlanService; _siteService = siteService; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetDeploymentSource.cs index ddc4f0d4748..31633b5cfe2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetDeploymentSource.cs @@ -18,10 +18,7 @@ public class ExportContentToDeploymentTargetDeploymentSource : IDeploymentSource private readonly ISession _session; private readonly IUpdateModelAccessor _updateModelAccessor; - public ExportContentToDeploymentTargetDeploymentSource( - IContentManager contentManager, - ISession session, - IUpdateModelAccessor updateModelAccessor) + public ExportContentToDeploymentTargetDeploymentSource(IContentManager contentManager, ISession session, IUpdateModelAccessor updateModelAccessor) { _contentManager = contentManager; _session = session; @@ -38,11 +35,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan } var data = new JsonArray(); - result.Steps.Add(new JsonObject - { - ["name"] = "Content", - ["data"] = data, - }); + result.Steps.Add(new JsonObject { ["name"] = "Content", ["data"] = data, }); var model = new ExportContentToDeploymentTargetModel(); await _updateModelAccessor.ModelUpdater.TryUpdateModelAsync(model, "ExportContentToDeploymentTarget", m => m.ItemIds, m => m.Latest, m => m.ContentItemId); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetDeploymentStepDriver.cs index 5817b2f92db..63d6bf269c4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class ExportContentToDeploymentTargetDeploymentStepDriver : DisplayDriver { public override IDisplayResult Display(ExportContentToDeploymentTargetDeploymentStep step) { - return - Combine( - View("ExportContentToDeploymentTargetDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("ExportContentToDeploymentTargetDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("ExportContentToDeploymentTargetDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("ExportContentToDeploymentTargetDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(ExportContentToDeploymentTargetDeploymentStep step) diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetMigrations.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetMigrations.cs index 997b545e2d9..81c2fc80c30 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetMigrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetMigrations.cs @@ -17,11 +17,7 @@ public class ExportContentToDeploymentTargetMigrations : DataMigration private readonly IDeploymentPlanService _deploymentPlanService; private readonly ISiteService _siteService; - public ExportContentToDeploymentTargetMigrations( - IRecipeMigrator recipeMigrator, - IDeploymentPlanService deploymentPlanService, - ISiteService siteService - ) + public ExportContentToDeploymentTargetMigrations(IRecipeMigrator recipeMigrator, IDeploymentPlanService deploymentPlanService, ISiteService siteService) { _recipeMigrator = recipeMigrator; _deploymentPlanService = deploymentPlanService; @@ -33,12 +29,17 @@ public async Task CreateAsync() await _recipeMigrator.ExecuteAsync($"exportcontenttodeploymenttarget{RecipesConstants.RecipeExtension}", this); var deploymentPlans = await _deploymentPlanService.GetAllDeploymentPlansAsync(); - var exportContentToDeploymentTargetPlan = deploymentPlans.FirstOrDefault(x => x.DeploymentSteps.Any(x => x.Name == nameof(ExportContentToDeploymentTargetDeploymentStep))); + var exportContentToDeploymentTargetPlan = deploymentPlans.FirstOrDefault(x => + x.DeploymentSteps.Any(x => x.Name == nameof(ExportContentToDeploymentTargetDeploymentStep)) + ); if (exportContentToDeploymentTargetPlan != null) { var siteSettings = await _siteService.LoadSiteSettingsAsync(); - siteSettings.Alter(nameof(ExportContentToDeploymentTargetSettings), aspect => aspect.ExportContentToDeploymentTargetPlanId = exportContentToDeploymentTargetPlan.Id); + siteSettings.Alter( + nameof(ExportContentToDeploymentTargetSettings), + aspect => aspect.ExportContentToDeploymentTargetPlanId = exportContentToDeploymentTargetPlan.Id + ); await _siteService.UpdateSiteSettingsAsync(siteSettings); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetSettingsDisplayDriver.cs index a6eb5199659..be0e1b4645c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetSettingsDisplayDriver.cs @@ -15,9 +15,7 @@ public class ExportContentToDeploymentTargetSettingsDisplayDriver : SectionDispl private readonly IHttpContextAccessor _httpContextAccessor; private readonly IAuthorizationService _authorizationService; - public ExportContentToDeploymentTargetSettingsDisplayDriver( - IHttpContextAccessor httpContextAccessor, - IAuthorizationService authorizationService) + public ExportContentToDeploymentTargetSettingsDisplayDriver(IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -31,10 +29,15 @@ public override async Task EditAsync(ExportContentToDeploymentTa return null; } - return Initialize("ExportContentToDeploymentTargetSettings_Edit", model => - { - model.ExportContentToDeploymentTargetPlanId = settings.ExportContentToDeploymentTargetPlanId; - }).Location("Content:2").OnGroup(GroupId); + return Initialize( + "ExportContentToDeploymentTargetSettings_Edit", + model => + { + model.ExportContentToDeploymentTargetPlanId = settings.ExportContentToDeploymentTargetPlanId; + } + ) + .Location("Content:2") + .OnGroup(GroupId); } public override async Task UpdateAsync(ExportContentToDeploymentTargetSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetStartup.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetStartup.cs index 076f02d8972..362a047a192 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetStartup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetStartup.cs @@ -20,13 +20,20 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped, ExportContentToDeploymentTargetSettingsDisplayDriver>(); - services.AddDeployment(); + services.AddDeployment< + ExportContentToDeploymentTargetDeploymentSource, + ExportContentToDeploymentTargetDeploymentStep, + ExportContentToDeploymentTargetDeploymentStepDriver + >(); services.AddDataMigration(); services.AddScoped(); services.AddScoped, ExportContentToDeploymentTargetContentsAdminListDisplayDriver>(); - services.AddSiteSettingsPropertyDeploymentStep(S => S["Export Content To Deployment Target settings"], S => S["Exports the Export Content To Deployment Target settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Export Content To Deployment Target settings"], + S => S["Exports the Export Content To Deployment Target settings."] + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/ContentOptionsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/ContentOptionsDisplayDriver.cs index 4316c44f399..929eca6b507 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/ContentOptionsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/ContentOptionsDisplayDriver.cs @@ -36,7 +36,6 @@ public override IDisplayResult Edit(ContentOptionsViewModel model) Initialize("ContentsAdminListSummary", m => BuildContentOptionsViewModel(m, model)).Location("Summary:10"), Initialize("ContentsAdminListFilters", m => BuildContentOptionsViewModel(m, model)).Location("Actions:10.1"), Initialize("ContentsAdminList_Fields_BulkActions", m => BuildContentOptionsViewModel(m, model)).Location("Actions:10.1") - ); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/ContentsDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/ContentsDriver.cs index 36bdb9d5d4e..d3632a2e6a0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/ContentsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/ContentsDriver.cs @@ -19,10 +19,7 @@ public class ContentsDriver : ContentDisplayDriver private readonly IHttpContextAccessor _httpContextAccessor; private readonly IAuthorizationService _authorizationService; - public ContentsDriver( - IContentDefinitionManager contentDefinitionManager, - IHttpContextAccessor httpContextAccessor, - IAuthorizationService authorizationService) + public ContentsDriver(IContentDefinitionManager contentDefinitionManager, IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService) { _contentDefinitionManager = contentDefinitionManager; _httpContextAccessor = httpContextAccessor; @@ -37,9 +34,7 @@ public override async Task DisplayAsync(ContentItem contentItem, var context = _httpContextAccessor.HttpContext; var results = new List(); var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType); - var contentsMetadataShape = Shape("ContentsMetadata", - new ContentItemViewModel(contentItem)) - .Location("Detail", "Content:before"); + var contentsMetadataShape = Shape("ContentsMetadata", new ContentItemViewModel(contentItem)).Location("Detail", "Content:before"); if (contentTypeDefinition != null) { @@ -67,21 +62,23 @@ public override async Task DisplayAsync(ContentItem contentItem, results.Add(contentsMetadataShape); results.Add(Shape("ContentsButtonEdit_SummaryAdmin", new ContentItemViewModel(contentItem)).Location("SummaryAdmin", "Actions:10")); - results.Add(Shape("ContentsButtonActions_SummaryAdmin", new ContentItemViewModel(contentItem)).Location("SummaryAdmin", "ActionsMenu:10") - .RenderWhen(async () => - { - var hasPublishPermission = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.PublishContent, contentItem); - var hasDeletePermission = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.DeleteContent, contentItem); - var hasPreviewPermission = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.PreviewContent, contentItem); - var hasClonePermission = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.CloneContent, contentItem); - - if (hasPublishPermission || hasDeletePermission || hasPreviewPermission || hasClonePermission) + results.Add( + Shape("ContentsButtonActions_SummaryAdmin", new ContentItemViewModel(contentItem)) + .Location("SummaryAdmin", "ActionsMenu:10") + .RenderWhen(async () => { - return true; - } - - return false; - }) + var hasPublishPermission = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.PublishContent, contentItem); + var hasDeletePermission = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.DeleteContent, contentItem); + var hasPreviewPermission = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.PreviewContent, contentItem); + var hasClonePermission = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.CloneContent, contentItem); + + if (hasPublishPermission || hasDeletePermission || hasPreviewPermission || hasClonePermission) + { + return true; + } + + return false; + }) ); } @@ -102,20 +99,24 @@ public override async Task EditAsync(ContentItem contentItem, IU return null; } - results.Add(Dynamic("Content_PublishButton").Location("Actions:10") - .RenderWhen(() => _authorizationService.AuthorizeAsync(context.User, CommonPermissions.PublishContent, contentItem))); + results.Add( + Dynamic("Content_PublishButton") + .Location("Actions:10") + .RenderWhen(() => _authorizationService.AuthorizeAsync(context.User, CommonPermissions.PublishContent, contentItem)) + ); - results.Add(Dynamic("Content_SaveDraftButton").Location("Actions:20") - .RenderWhen(async () => - { - if (contentTypeDefinition.IsDraftable() && - await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.EditContent, contentItem)) + results.Add( + Dynamic("Content_SaveDraftButton") + .Location("Actions:20") + .RenderWhen(async () => { - return true; - } + if (contentTypeDefinition.IsDraftable() && await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.EditContent, contentItem)) + { + return true; + } - return false; - }) + return false; + }) ); return Combine(results.ToArray()); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/DateEditorDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/DateEditorDriver.cs index b4c761ee04c..02658bb3e4a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/DateEditorDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/DateEditorDriver.cs @@ -25,12 +25,15 @@ public override IDisplayResult Edit(CommonPart part, BuildPartEditorContext cont if (settings.DisplayDateEditor) { - return Initialize("CommonPart_Edit__Date", async model => - { - model.LocalDateTime = part.ContentItem.CreatedUtc.HasValue - ? (DateTime?)(await _localClock.ConvertToLocalAsync(part.ContentItem.CreatedUtc.Value)).DateTime - : null; - }); + return Initialize( + "CommonPart_Edit__Date", + async model => + { + model.LocalDateTime = part.ContentItem.CreatedUtc.HasValue + ? (DateTime?)(await _localClock.ConvertToLocalAsync(part.ContentItem.CreatedUtc.Value)).DateTime + : null; + } + ); } return null; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/OwnerEditorDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/OwnerEditorDriver.cs index e70f0656f00..b3b99a2be9c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/OwnerEditorDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Drivers/OwnerEditorDriver.cs @@ -20,10 +20,12 @@ public class OwnerEditorDriver : ContentPartDisplayDriver private readonly UserManager _userManager; protected readonly IStringLocalizer S; - public OwnerEditorDriver(IAuthorizationService authorizationService, + public OwnerEditorDriver( + IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor, UserManager userManager, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _authorizationService = authorizationService; _httpContextAccessor = httpContextAccessor; @@ -44,16 +46,19 @@ public override async Task EditAsync(CommonPart part, BuildPartE if (settings.DisplayOwnerEditor) { - return Initialize("CommonPart_Edit__Owner", async model => - { - if (!string.IsNullOrEmpty(part.ContentItem.Owner)) + return Initialize( + "CommonPart_Edit__Owner", + async model => { - // TODO Move this editor to a user picker. - var user = await _userManager.FindByIdAsync(part.ContentItem.Owner); + if (!string.IsNullOrEmpty(part.ContentItem.Owner)) + { + // TODO Move this editor to a user picker. + var user = await _userManager.FindByIdAsync(part.ContentItem.Owner); - model.OwnerName = user?.UserName; + model.OwnerName = user?.UserName; + } } - }); + ); } return null; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Handlers/FullTextAspectContentHandler.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Handlers/FullTextAspectContentHandler.cs index c8e2a15e899..1b8134d67fc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Handlers/FullTextAspectContentHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Handlers/FullTextAspectContentHandler.cs @@ -24,11 +24,7 @@ public class FullTextAspectContentHandler : ContentHandlerBase private readonly ILiquidTemplateManager _liquidTemplateManager; private readonly IServiceProvider _serviceProvider; - public FullTextAspectContentHandler( - IContentDefinitionManager contentDefinitionManager, - ILiquidTemplateManager liquidTemplateManager, - IServiceProvider serviceProvider - ) + public FullTextAspectContentHandler(IContentDefinitionManager contentDefinitionManager, ILiquidTemplateManager liquidTemplateManager, IServiceProvider serviceProvider) { _contentDefinitionManager = contentDefinitionManager; _liquidTemplateManager = liquidTemplateManager; @@ -71,8 +67,12 @@ await context.ForAsync(async fullTextAspect => if (settings.IncludeFullTextTemplate && !string.IsNullOrEmpty(settings.FullTextTemplate)) { - var result = await _liquidTemplateManager.RenderStringAsync(settings.FullTextTemplate, NullEncoder.Default, context.ContentItem, - new Dictionary() { ["ContentItem"] = new ObjectValue(context.ContentItem) }); + var result = await _liquidTemplateManager.RenderStringAsync( + settings.FullTextTemplate, + NullEncoder.Default, + context.ContentItem, + new Dictionary() { ["ContentItem"] = new ObjectValue(context.ContentItem) } + ); fullTextAspect.Segments.Add(result); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/AspectsContentIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/AspectsContentIndexHandler.cs index 375ca1a40a1..90176e7fd04 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/AspectsContentIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/AspectsContentIndexHandler.cs @@ -21,28 +21,24 @@ public async Task BuildIndexAsync(BuildIndexContext context) if (body != null && body.Body != null) { - context.DocumentIndex.Set( - IndexingConstants.BodyAspectBodyKey, - body.Body, - DocumentIndexOptions.Sanitize); + context.DocumentIndex.Set(IndexingConstants.BodyAspectBodyKey, body.Body, DocumentIndexOptions.Sanitize); } - context.DocumentIndex.Set( - IndexingConstants.DisplayTextAnalyzedKey, - context.ContentItem.DisplayText, - DocumentIndexOptions.Sanitize); + context.DocumentIndex.Set(IndexingConstants.DisplayTextAnalyzedKey, context.ContentItem.DisplayText, DocumentIndexOptions.Sanitize); // We need to store because of ContentPickerResultProvider(s) context.DocumentIndex.Set( IndexingConstants.DisplayTextKey + IndexingConstants.KeywordKey, context.ContentItem.DisplayText, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + DocumentIndexOptions.Keyword | DocumentIndexOptions.Store + ); // We need to store because of ContentPickerResultProvider(s) context.DocumentIndex.Set( IndexingConstants.DisplayTextNormalizedKey, context.ContentItem.DisplayText?.ReplaceDiacritics().ToLower(), - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + DocumentIndexOptions.Keyword | DocumentIndexOptions.Store + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/ContentItemIndexCoordinator.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/ContentItemIndexCoordinator.cs index 8ee8123ed7a..23ec77acca3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/ContentItemIndexCoordinator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/ContentItemIndexCoordinator.cs @@ -24,7 +24,8 @@ public ContentItemIndexCoordinator( ITypeActivatorFactory contentPartFactory, IEnumerable partIndexHandlers, IEnumerable fieldIndexHandlers, - ILogger logger) + ILogger logger + ) { _contentDefinitionManager = contentDefinitionManager; _contentPartFactory = contentPartFactory; @@ -59,9 +60,15 @@ public async Task BuildIndexAsync(BuildIndexContext context) continue; } - await _partIndexHandlers.InvokeAsync((handler, part, contentTypePartDefinition, context, typePartIndexSettings) => - handler.BuildIndexAsync(part, contentTypePartDefinition, context, typePartIndexSettings), - part, contentTypePartDefinition, context, typePartIndexSettings, _logger); + await _partIndexHandlers.InvokeAsync( + (handler, part, contentTypePartDefinition, context, typePartIndexSettings) => + handler.BuildIndexAsync(part, contentTypePartDefinition, context, typePartIndexSettings), + part, + contentTypePartDefinition, + context, + typePartIndexSettings, + _logger + ); foreach (var contentPartFieldDefinition in contentTypePartDefinition.PartDefinition.Fields) { @@ -74,9 +81,16 @@ await _partIndexHandlers.InvokeAsync((handler, part, contentTypePartDefinition, continue; } - await _fieldIndexHandlers.InvokeAsync((handler, part, contentTypePartDefinition, contentPartFieldDefinition, context, partFieldIndexSettings) => - handler.BuildIndexAsync(part, contentTypePartDefinition, contentPartFieldDefinition, context, partFieldIndexSettings), - part, contentTypePartDefinition, contentPartFieldDefinition, context, partFieldIndexSettings, _logger); + await _fieldIndexHandlers.InvokeAsync( + (handler, part, contentTypePartDefinition, contentPartFieldDefinition, context, partFieldIndexSettings) => + handler.BuildIndexAsync(part, contentTypePartDefinition, contentPartFieldDefinition, context, partFieldIndexSettings), + part, + contentTypePartDefinition, + contentPartFieldDefinition, + context, + partFieldIndexSettings, + _logger + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/DefaultContentIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/DefaultContentIndexHandler.cs index 4c987038256..3199d7e8afd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/DefaultContentIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/DefaultContentIndexHandler.cs @@ -7,46 +7,22 @@ public class DefaultContentIndexHandler : IContentItemIndexHandler { public Task BuildIndexAsync(BuildIndexContext context) { - context.DocumentIndex.Set( - IndexingConstants.ContentTypeKey, - context.ContentItem.ContentType, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); - - context.DocumentIndex.Set( - IndexingConstants.CreatedUtcKey, - context.ContentItem.CreatedUtc, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); - - context.DocumentIndex.Set( - IndexingConstants.LatestKey, - context.ContentItem.Latest, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); - - context.DocumentIndex.Set( - IndexingConstants.OwnerKey, - context.ContentItem.Owner, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); - - context.DocumentIndex.Set( - IndexingConstants.AuthorKey, - context.ContentItem.Author, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); - - context.DocumentIndex.Set( - IndexingConstants.ModifiedUtcKey, - context.ContentItem.ModifiedUtc, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + context.DocumentIndex.Set(IndexingConstants.ContentTypeKey, context.ContentItem.ContentType, DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + + context.DocumentIndex.Set(IndexingConstants.CreatedUtcKey, context.ContentItem.CreatedUtc, DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + + context.DocumentIndex.Set(IndexingConstants.LatestKey, context.ContentItem.Latest, DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + + context.DocumentIndex.Set(IndexingConstants.OwnerKey, context.ContentItem.Owner, DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + + context.DocumentIndex.Set(IndexingConstants.AuthorKey, context.ContentItem.Author, DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + + context.DocumentIndex.Set(IndexingConstants.ModifiedUtcKey, context.ContentItem.ModifiedUtc, DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); // We need to store because of ContentPickerResultProvider(s) - context.DocumentIndex.Set( - IndexingConstants.PublishedKey, - context.ContentItem.Published, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); - - context.DocumentIndex.Set( - IndexingConstants.PublishedUtcKey, - context.ContentItem.PublishedUtc, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + context.DocumentIndex.Set(IndexingConstants.PublishedKey, context.ContentItem.Published, DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + + context.DocumentIndex.Set(IndexingConstants.PublishedUtcKey, context.ContentItem.PublishedUtc, DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/BuildDisplayFilter.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/BuildDisplayFilter.cs index 2185293499a..177aa8abfbe 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/BuildDisplayFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/BuildDisplayFilter.cs @@ -19,9 +19,11 @@ public class BuildDisplayFilter : ILiquidFilter private readonly IContentItemDisplayManager _contentItemDisplayManager; private readonly IUpdateModelAccessor _updateModelAccessor; - public BuildDisplayFilter(IContentItemRecursionHelper buildDisplayRecursionHelper, + public BuildDisplayFilter( + IContentItemRecursionHelper buildDisplayRecursionHelper, IContentItemDisplayManager contentItemDisplayManager, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _buildDisplayRecursionHelper = buildDisplayRecursionHelper; _contentItemDisplayManager = contentItemDisplayManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/ContentAnchorTag.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/ContentAnchorTag.cs index da91435a87c..ea5b69c6066 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/ContentAnchorTag.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/ContentAnchorTag.cs @@ -30,14 +30,21 @@ public bool Match(List argumentsList) case "display_for": case "edit_for": case "remove_for": - case "create_for": return true; + case "create_for": + return true; } } return false; } - public async ValueTask WriteToAsync(List argumentsList, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, LiquidTemplateContext context) + public async ValueTask WriteToAsync( + List argumentsList, + IReadOnlyList statements, + TextWriter writer, + TextEncoder encoder, + LiquidTemplateContext context + ) { var services = context.Services; var viewContext = context.ViewContext; @@ -57,11 +64,21 @@ public async ValueTask WriteToAsync(List argumentsLi { switch (argument.Name) { - case "admin_for": adminFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; break; - case "display_for": displayFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; break; - case "edit_for": editFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; break; - case "remove_for": removeFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; break; - case "create_for": createFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; break; + case "admin_for": + adminFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; + break; + case "display_for": + displayFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; + break; + case "edit_for": + editFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; + break; + case "remove_for": + removeFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; + break; + case "create_for": + createFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; + break; default: diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/DisplayUrlFilter.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/DisplayUrlFilter.cs index 12cc5a14ab5..4e3a32bf68f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/DisplayUrlFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/DisplayUrlFilter.cs @@ -36,10 +36,7 @@ public async ValueTask ProcessAsync(FluidValue input, FilterArgument return StringValue.Empty; } - routeValues = new RouteValueDictionary(_autorouteOptions.GlobalRouteValues) - { - [_autorouteOptions.ContentItemIdKey] = input.ToStringValue(), - }; + routeValues = new RouteValueDictionary(_autorouteOptions.GlobalRouteValues) { [_autorouteOptions.ContentItemIdKey] = input.ToStringValue(), }; } else { diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Manifest.cs index 0fa1e57bcc9..abddace8037 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Manifest.cs @@ -1,21 +1,12 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Contents", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Contents", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Contents", Name = "Contents", Description = "The contents module enables the edition and rendering of content items.", - Dependencies = - [ - "OrchardCore.Settings", - "OrchardCore.Liquid" - ], + Dependencies = ["OrchardCore.Settings", "OrchardCore.Liquid"], Category = "Content Management" )] @@ -31,12 +22,7 @@ Id = "OrchardCore.Contents.Deployment.ExportContentToDeploymentTarget", Name = "Export Content To Deployment Target", Description = "Adds an export to deployment target action to the content items list.", - Dependencies = - [ - "OrchardCore.Contents", - "OrchardCore.Deployment", - "OrchardCore.Recipes.Core", - ], + Dependencies = ["OrchardCore.Contents", "OrchardCore.Deployment", "OrchardCore.Recipes.Core",], Category = "Content Management" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Migrations.cs index acaa816438b..0dd5a81b836 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Migrations.cs @@ -16,9 +16,10 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("CommonPart", builder => builder - .Attachable() - .WithDescription("Provides an editor for the common properties of a content item.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "CommonPart", + builder => builder.Attachable().WithDescription("Provides an editor for the common properties of a content item.") + ); return 1; } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Models/CommonPart.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Models/CommonPart.cs index 511a6669d2b..b9b72991b3f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Models/CommonPart.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Models/CommonPart.cs @@ -6,7 +6,5 @@ namespace OrchardCore.Contents.Models /// When attached to a content type, provides a way to edit the common /// properties of a content item like CreatedUtc and Owner. /// - public class CommonPart : ContentPart - { - } + public class CommonPart : ContentPart { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Permissions.cs index 304edb53fc8..372ebec8cab 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Permissions.cs @@ -27,10 +27,7 @@ public class Permissions : IPermissionProvider public static readonly Permission EditContentOwner = CommonPermissions.EditContentOwner; public static readonly Permission AccessContentApi = new("AccessContentApi", "Access content via the api"); - private readonly IEnumerable _readerPermissions = - [ - ViewContent, - ]; + private readonly IEnumerable _readerPermissions = [ViewContent,]; private readonly IEnumerable _allPermissions = [ @@ -51,70 +48,19 @@ public class Permissions : IPermissionProvider EditContentOwner, ]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = - [ - PublishContent, - EditContent, - DeleteContent, - PreviewContent, - CloneContent, - AccessContentApi, - ListContent, - EditContentOwner, - ], - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = - [ - PublishContent, - EditContent, - DeleteContent, - PreviewContent, - CloneContent, - ListContent, - ], - }, - new PermissionStereotype - { - Name = "Author", - Permissions = - [ - PublishOwnContent, - EditOwnContent, - DeleteOwnContent, - PreviewOwnContent, - CloneOwnContent, - ], - }, - new PermissionStereotype - { - Name = "Contributor", - Permissions = - [ - EditOwnContent, - PreviewOwnContent, - CloneOwnContent, - ], - }, - new PermissionStereotype - { - Name = "Authenticated", - Permissions = _readerPermissions, - }, - new PermissionStereotype - { - Name = "Anonymous", - Permissions = _readerPermissions, - }, - ]; + [ + new PermissionStereotype + { + Name = "Administrator", + Permissions = [PublishContent, EditContent, DeleteContent, PreviewContent, CloneContent, AccessContentApi, ListContent, EditContentOwner,], + }, + new PermissionStereotype { Name = "Editor", Permissions = [PublishContent, EditContent, DeleteContent, PreviewContent, CloneContent, ListContent,], }, + new PermissionStereotype { Name = "Author", Permissions = [PublishOwnContent, EditOwnContent, DeleteOwnContent, PreviewOwnContent, CloneOwnContent,], }, + new PermissionStereotype { Name = "Contributor", Permissions = [EditOwnContent, PreviewOwnContent, CloneOwnContent,], }, + new PermissionStereotype { Name = "Authenticated", Permissions = _readerPermissions, }, + new PermissionStereotype { Name = "Anonymous", Permissions = _readerPermissions, }, + ]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Razor/ContentRazorHelperExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Razor/ContentRazorHelperExtensions.cs index c5e3925e28d..a1ec0de622b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Razor/ContentRazorHelperExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Razor/ContentRazorHelperExtensions.cs @@ -84,7 +84,10 @@ public static Task GetContentItemByVersionIdAsync(this IOrchardHelp /// /// Query content items. /// - public static async Task> QueryContentItemsAsync(this IOrchardHelper orchardHelper, Func, IQuery> query) + public static async Task> QueryContentItemsAsync( + this IOrchardHelper orchardHelper, + Func, IQuery> query + ) { var contentManager = orchardHelper.HttpContext.RequestServices.GetService(); var session = orchardHelper.HttpContext.RequestServices.GetService(); @@ -102,6 +105,8 @@ public static async Task> QueryContentItemsAsync(this I /// The maximum content items to return. public static Task> GetRecentContentItemsByContentTypeAsync(this IOrchardHelper orchardHelper, string contentType, int maxContentItems = 10) { - return orchardHelper.QueryContentItemsAsync(query => query.Where(x => x.ContentType == contentType && x.Published == true).OrderByDescending(x => x.CreatedUtc).Take(maxContentItems)); + return orchardHelper.QueryContentItemsAsync(query => + query.Where(x => x.ContentType == contentType && x.Published == true).OrderByDescending(x => x.CreatedUtc).Take(maxContentItems) + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Scripting/ContentMethodsProvider.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Scripting/ContentMethodsProvider.cs index 90043ffb71b..8b73cee3155 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Scripting/ContentMethodsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Scripting/ContentMethodsProvider.cs @@ -21,59 +21,74 @@ public ContentMethodsProvider() _newContentItemMethod = new GlobalMethod { Name = "newContentItem", - Method = serviceProvider => (Func)((contentType) => - { - var contentManager = serviceProvider.GetRequiredService(); - var contentItem = contentManager.NewAsync(contentType).GetAwaiter().GetResult(); + Method = serviceProvider => + (Func)( + (contentType) => + { + var contentManager = serviceProvider.GetRequiredService(); + var contentItem = contentManager.NewAsync(contentType).GetAwaiter().GetResult(); - return contentItem; - }), + return contentItem; + } + ), }; _createContentItemMethod = new GlobalMethod { Name = "createContentItem", - Method = serviceProvider => (Func)((contentType, publish, properties) => - { - var contentManager = serviceProvider.GetRequiredService(); - var contentItem = contentManager.NewAsync(contentType).GetAwaiter().GetResult(); - contentItem.Merge(properties); - var result = contentManager.UpdateValidateAndCreateAsync(contentItem, publish == true ? VersionOptions.Published : VersionOptions.Draft).GetAwaiter().GetResult(); - if (result.Succeeded) - { - return contentItem; - } - else - { - throw new ValidationException(string.Join(", ", result.Errors)); - } - }), + Method = serviceProvider => + (Func)( + (contentType, publish, properties) => + { + var contentManager = serviceProvider.GetRequiredService(); + var contentItem = contentManager.NewAsync(contentType).GetAwaiter().GetResult(); + contentItem.Merge(properties); + var result = contentManager + .UpdateValidateAndCreateAsync(contentItem, publish == true ? VersionOptions.Published : VersionOptions.Draft) + .GetAwaiter() + .GetResult(); + if (result.Succeeded) + { + return contentItem; + } + else + { + throw new ValidationException(string.Join(", ", result.Errors)); + } + } + ), }; _updateContentItemMethod = new GlobalMethod { Name = "updateContentItem", - Method = serviceProvider => (Action)((contentItem, properties) => - { - var contentManager = serviceProvider.GetRequiredService(); - contentItem.Merge(properties, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace }); - contentManager.UpdateAsync(contentItem).GetAwaiter().GetResult(); - var result = contentManager.ValidateAsync(contentItem).GetAwaiter().GetResult(); - if (!result.Succeeded) - { - throw new ValidationException(string.Join(", ", result.Errors)); - } - }), + Method = serviceProvider => + (Action)( + (contentItem, properties) => + { + var contentManager = serviceProvider.GetRequiredService(); + contentItem.Merge(properties, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace }); + contentManager.UpdateAsync(contentItem).GetAwaiter().GetResult(); + var result = contentManager.ValidateAsync(contentItem).GetAwaiter().GetResult(); + if (!result.Succeeded) + { + throw new ValidationException(string.Join(", ", result.Errors)); + } + } + ), }; _deleteContentItemMethod = new GlobalMethod { Name = "deleteContentItem", - Method = serviceProvider => (Action)((contentItem, properties) => - { - var contentManager = serviceProvider.GetRequiredService(); - contentManager.RemoveAsync(contentItem).GetAwaiter().GetResult(); - }), + Method = serviceProvider => + (Action)( + (contentItem, properties) => + { + var contentManager = serviceProvider.GetRequiredService(); + contentManager.RemoveAsync(contentItem).GetAwaiter().GetResult(); + } + ), }; } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Scripting/UrlMethodsProvider.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Scripting/UrlMethodsProvider.cs index aeff13830c7..f542f8d082e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Scripting/UrlMethodsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Scripting/UrlMethodsProvider.cs @@ -14,29 +14,30 @@ public UrlMethodsProvider() _getUrlPrefix = new GlobalMethod { Name = "getUrlPrefix", - Method = serviceProvider => (string path, bool? escaped) => - { - var httpContextAccessor = serviceProvider.GetRequiredService(); - - var pathBase = httpContextAccessor.HttpContext?.Request.PathBase ?? PathString.Empty; - if (!pathBase.HasValue) + Method = serviceProvider => + (string path, bool? escaped) => { - pathBase = "/"; - } + var httpContextAccessor = serviceProvider.GetRequiredService(); - path = path?.Trim(' ', '/') ?? string.Empty; - if (path.Length > 0) - { - pathBase = pathBase.Add($"/{path}"); - } + var pathBase = httpContextAccessor.HttpContext?.Request.PathBase ?? PathString.Empty; + if (!pathBase.HasValue) + { + pathBase = "/"; + } - if (escaped.HasValue && escaped.Value) - { - return pathBase.ToString(); - } + path = path?.Trim(' ', '/') ?? string.Empty; + if (path.Length > 0) + { + pathBase = pathBase.Add($"/{path}"); + } + + if (escaped.HasValue && escaped.Value) + { + return pathBase.ToString(); + } - return pathBase.Value; - }, + return pathBase.Value; + }, }; } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Security/ContentTypeAuthorizationHandler.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Security/ContentTypeAuthorizationHandler.cs index 0a597199109..d928505b99f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Security/ContentTypeAuthorizationHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Security/ContentTypeAuthorizationHandler.cs @@ -52,10 +52,7 @@ protected override async Task HandleRequirementAsync(AuthorizationHandlerContext if (contentTypePermission != null) { // The resource can be a content type name - var contentType = contentItem != null - ? contentItem.ContentType - : context.Resource.ToString() - ; + var contentType = contentItem != null ? contentItem.ContentType : context.Resource.ToString(); if (!string.IsNullOrEmpty(contentType)) { diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Security/ContentTypePermissions.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Security/ContentTypePermissions.cs index 1d5c74008f1..82546579f39 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Security/ContentTypePermissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Security/ContentTypePermissions.cs @@ -19,8 +19,7 @@ public ContentTypePermissions(IContentDefinitionManager contentDefinitionManager public async Task> GetPermissionsAsync() { // Manage rights only for Securable types. - var securableTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(ctd => ctd.IsSecurable()); + var securableTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(ctd => ctd.IsSecurable()); var result = new List(); @@ -35,6 +34,5 @@ public async Task> GetPermissionsAsync() return result; } - public IEnumerable GetDefaultStereotypes() - => []; + public IEnumerable GetDefaultStereotypes() => []; } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Services/ContentTypeFilterNode.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Services/ContentTypeFilterNode.cs index b649aaa00c6..ab99e213fdf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Services/ContentTypeFilterNode.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Services/ContentTypeFilterNode.cs @@ -7,14 +7,11 @@ namespace OrchardCore.Contents.Services /// public class ContentTypeFilterNode : TermOperationNode { - public ContentTypeFilterNode(string selectedContentType) : base("type", new UnaryNode(selectedContentType, OperateNodeQuotes.None)) - { - } + public ContentTypeFilterNode(string selectedContentType) + : base("type", new UnaryNode(selectedContentType, OperateNodeQuotes.None)) { } - public override string ToNormalizedString() - => string.Empty; + public override string ToNormalizedString() => string.Empty; - public override string ToString() - => string.Empty; + public override string ToString() => string.Empty; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListFilterParser.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListFilterParser.cs index daab0845412..136b782704a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListFilterParser.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListFilterParser.cs @@ -12,7 +12,6 @@ public DefaultContentsAdminListFilterParser(IQueryParser parser) _parser = parser; } - public QueryFilterResult Parse(string text) - => _parser.Parse(text); + public QueryFilterResult Parse(string text) => _parser.Parse(text); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListFilterProvider.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListFilterProvider.cs index 3ff5c6a02cc..22d5cd4fbd6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListFilterProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListFilterProvider.cs @@ -22,238 +22,274 @@ public class DefaultContentsAdminListFilterProvider : IContentsAdminListFilterPr public void Build(QueryEngineBuilder builder) { builder - .WithNamedTerm("status", builder => builder - .OneCondition((val, query, ctx) => - { - var context = (ContentQueryContext)ctx; - if (Enum.TryParse(val, true, out var contentsStatus)) - { - switch (contentsStatus) - { - case ContentsStatus.Draft: - query.With(x => x.Latest && !x.Published); - break; - case ContentsStatus.Published: - query.With(x => x.Published); - break; - case ContentsStatus.Owner: - var httpContextAccessor = context.ServiceProvider.GetRequiredService(); - var userNameIdentifier = httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier); - query.With(x => x.Owner == userNameIdentifier && x.Latest); - break; - case ContentsStatus.AllVersions: - query.With(x => x.Latest); - break; - default: - query.With(x => x.Latest); - break; - } - } - else - { - // Draft is the default value. - query.With(x => x.Latest); - } + .WithNamedTerm( + "status", + builder => + builder + .OneCondition( + (val, query, ctx) => + { + var context = (ContentQueryContext)ctx; + if (Enum.TryParse(val, true, out var contentsStatus)) + { + switch (contentsStatus) + { + case ContentsStatus.Draft: + query.With(x => x.Latest && !x.Published); + break; + case ContentsStatus.Published: + query.With(x => x.Published); + break; + case ContentsStatus.Owner: + var httpContextAccessor = context.ServiceProvider.GetRequiredService(); + var userNameIdentifier = httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier); + query.With(x => x.Owner == userNameIdentifier && x.Latest); + break; + case ContentsStatus.AllVersions: + query.With(x => x.Latest); + break; + default: + query.With(x => x.Latest); + break; + } + } + else + { + // Draft is the default value. + query.With(x => x.Latest); + } - return new ValueTask>(query); - }) - .MapTo((val, model) => - { - if (Enum.TryParse(val, true, out var contentsStatus)) - { - model.ContentsStatus = contentsStatus; - } - }) - .MapFrom((model) => - { - if (model.ContentsStatus != ContentsStatus.Latest) - { - return (true, model.ContentsStatus.ToString()); - } + return new ValueTask>(query); + } + ) + .MapTo( + (val, model) => + { + if (Enum.TryParse(val, true, out var contentsStatus)) + { + model.ContentsStatus = contentsStatus; + } + } + ) + .MapFrom( + (model) => + { + if (model.ContentsStatus != ContentsStatus.Latest) + { + return (true, model.ContentsStatus.ToString()); + } - return (false, string.Empty); - }) - .AlwaysRun() + return (false, string.Empty); + } + ) + .AlwaysRun() ) - .WithNamedTerm("sort", builder => builder - .OneCondition((val, query) => - { - if (Enum.TryParse(val, true, out var contentsOrder)) - { - switch (contentsOrder) - { - case ContentsOrder.Modified: - query.With().OrderByDescending(cr => cr.ModifiedUtc).ThenBy(cr => cr.Id); - break; - case ContentsOrder.Published: - query.With().OrderByDescending(cr => cr.PublishedUtc).ThenBy(cr => cr.Id); - break; - case ContentsOrder.Created: - query.With().OrderByDescending(cr => cr.CreatedUtc).ThenBy(cr => cr.Id); - break; - case ContentsOrder.Title: - query.With().OrderBy(cr => cr.DisplayText).ThenBy(cr => cr.Id); - break; - }; - } - else - { - // Modified is a default value and applied when there is no filter. - query.With().OrderByDescending(cr => cr.ModifiedUtc).ThenBy(cr => cr.Id); - } + .WithNamedTerm( + "sort", + builder => + builder + .OneCondition( + (val, query) => + { + if (Enum.TryParse(val, true, out var contentsOrder)) + { + switch (contentsOrder) + { + case ContentsOrder.Modified: + query.With().OrderByDescending(cr => cr.ModifiedUtc).ThenBy(cr => cr.Id); + break; + case ContentsOrder.Published: + query.With().OrderByDescending(cr => cr.PublishedUtc).ThenBy(cr => cr.Id); + break; + case ContentsOrder.Created: + query.With().OrderByDescending(cr => cr.CreatedUtc).ThenBy(cr => cr.Id); + break; + case ContentsOrder.Title: + query.With().OrderBy(cr => cr.DisplayText).ThenBy(cr => cr.Id); + break; + } + ; + } + else + { + // Modified is a default value and applied when there is no filter. + query.With().OrderByDescending(cr => cr.ModifiedUtc).ThenBy(cr => cr.Id); + } - return query; - }) - .MapTo((val, model) => - { - if (Enum.TryParse(val, true, out var contentsOrder)) - { - model.OrderBy = contentsOrder; - } - }) - .MapFrom((model) => - { - if (model.OrderBy != ContentsOrder.Modified) - { - return (true, model.OrderBy.ToString()); - } + return query; + } + ) + .MapTo( + (val, model) => + { + if (Enum.TryParse(val, true, out var contentsOrder)) + { + model.OrderBy = contentsOrder; + } + } + ) + .MapFrom( + (model) => + { + if (model.OrderBy != ContentsOrder.Modified) + { + return (true, model.OrderBy.ToString()); + } - return (false, string.Empty); - }) - .AlwaysRun() + return (false, string.Empty); + } + ) + .AlwaysRun() ) - .WithNamedTerm("type", builder => builder - .OneCondition(async (contentType, query, ctx) => - { - var context = (ContentQueryContext)ctx; - var httpContextAccessor = context.ServiceProvider.GetRequiredService(); - var authorizationService = context.ServiceProvider.GetRequiredService(); - var contentDefinitionManager = context.ServiceProvider.GetRequiredService(); - var user = httpContextAccessor.HttpContext.User; - var userNameIdentifier = user?.FindFirstValue(ClaimTypes.NameIdentifier); + .WithNamedTerm( + "type", + builder => + builder + .OneCondition( + async (contentType, query, ctx) => + { + var context = (ContentQueryContext)ctx; + var httpContextAccessor = context.ServiceProvider.GetRequiredService(); + var authorizationService = context.ServiceProvider.GetRequiredService(); + var contentDefinitionManager = context.ServiceProvider.GetRequiredService(); + var user = httpContextAccessor.HttpContext.User; + var userNameIdentifier = user?.FindFirstValue(ClaimTypes.NameIdentifier); - // Filter for a specific type. - if (!string.IsNullOrEmpty(contentType)) - { - var contentTypeDefinition = await contentDefinitionManager.GetTypeDefinitionAsync(contentType); - if (contentTypeDefinition != null) - { - // We display a specific type even if it's not listable so that admin pages - // can reuse the Content list page for specific types. + // Filter for a specific type. + if (!string.IsNullOrEmpty(contentType)) + { + var contentTypeDefinition = await contentDefinitionManager.GetTypeDefinitionAsync(contentType); + if (contentTypeDefinition != null) + { + // We display a specific type even if it's not listable so that admin pages + // can reuse the Content list page for specific types. - // It is important to pass null to the owner parameter. This will check if the user can view content that belongs to others. - if (await authorizationService.AuthorizeContentTypeAsync(user, CommonPermissions.ViewContent, contentTypeDefinition.Name, owner: null)) - { - return query.With(x => x.ContentType == contentType); - } + // It is important to pass null to the owner parameter. This will check if the user can view content that belongs to others. + if (await authorizationService.AuthorizeContentTypeAsync(user, CommonPermissions.ViewContent, contentTypeDefinition.Name, owner: null)) + { + return query.With(x => x.ContentType == contentType); + } - return query.With(x => x.ContentType == contentType && x.Owner == userNameIdentifier); - } + return query.With(x => x.ContentType == contentType && x.Owner == userNameIdentifier); + } - // At this point, the given contentType is invalid. Ignore it. - } + // At this point, the given contentType is invalid. Ignore it. + } - var listAnyContentTypes = new List(); - var listOwnContentTypes = new List(); + var listAnyContentTypes = new List(); + var listOwnContentTypes = new List(); - foreach (var ctd in await contentDefinitionManager.ListTypeDefinitionsAsync()) - { - if (!ctd.IsListable()) - { - continue; - } + foreach (var ctd in await contentDefinitionManager.ListTypeDefinitionsAsync()) + { + if (!ctd.IsListable()) + { + continue; + } - // It is important to pass null to the owner parameter. This will check if the user can view content that belongs to others. - if (await authorizationService.AuthorizeContentTypeAsync(user, CommonPermissions.ViewContent, ctd.Name, owner: null)) - { - listAnyContentTypes.Add(ctd.Name); + // It is important to pass null to the owner parameter. This will check if the user can view content that belongs to others. + if (await authorizationService.AuthorizeContentTypeAsync(user, CommonPermissions.ViewContent, ctd.Name, owner: null)) + { + listAnyContentTypes.Add(ctd.Name); - continue; - } + continue; + } - // It is important to pass the current user ID to the owner parameter. This will check if the user can view their own content. - if (await authorizationService.AuthorizeContentTypeAsync(user, CommonPermissions.ViewContent, ctd.Name, userNameIdentifier)) - { - listOwnContentTypes.Add(ctd.Name); + // It is important to pass the current user ID to the owner parameter. This will check if the user can view their own content. + if (await authorizationService.AuthorizeContentTypeAsync(user, CommonPermissions.ViewContent, ctd.Name, userNameIdentifier)) + { + listOwnContentTypes.Add(ctd.Name); - continue; - } - } + continue; + } + } - return query.With().Where(x => x.ContentType.IsIn(listAnyContentTypes) || (x.ContentType.IsIn(listOwnContentTypes) && x.Owner == userNameIdentifier)); - }) - .MapTo((val, model) => - { - if (!string.IsNullOrEmpty(val)) - { - model.SelectedContentType = val; - } - }) - .MapFrom((model) => - { - if (!string.IsNullOrEmpty(model.SelectedContentType)) - { - return (true, model.SelectedContentType); - } + return query + .With() + .Where(x => x.ContentType.IsIn(listAnyContentTypes) || (x.ContentType.IsIn(listOwnContentTypes) && x.Owner == userNameIdentifier)); + } + ) + .MapTo( + (val, model) => + { + if (!string.IsNullOrEmpty(val)) + { + model.SelectedContentType = val; + } + } + ) + .MapFrom( + (model) => + { + if (!string.IsNullOrEmpty(model.SelectedContentType)) + { + return (true, model.SelectedContentType); + } - return (false, string.Empty); - }) - .AlwaysRun() + return (false, string.Empty); + } + ) + .AlwaysRun() ) - .WithNamedTerm("stereotype", builder => builder - .OneCondition(async (stereotype, query, ctx) => - { - var context = (ContentQueryContext)ctx; - var httpContextAccessor = context.ServiceProvider.GetRequiredService(); - var authorizationService = context.ServiceProvider.GetRequiredService(); - var contentDefinitionManager = context.ServiceProvider.GetRequiredService(); + .WithNamedTerm( + "stereotype", + builder => + builder.OneCondition( + async (stereotype, query, ctx) => + { + var context = (ContentQueryContext)ctx; + var httpContextAccessor = context.ServiceProvider.GetRequiredService(); + var authorizationService = context.ServiceProvider.GetRequiredService(); + var contentDefinitionManager = context.ServiceProvider.GetRequiredService(); + + // Filter for a specific stereotype. + if (!string.IsNullOrEmpty(stereotype)) + { + var contentTypeDefinitionNames = (await contentDefinitionManager.ListTypeDefinitionsAsync()) + .Where(definition => definition.StereotypeEquals(stereotype, StringComparison.OrdinalIgnoreCase)) + .Select(definition => definition.Name) + .ToList(); - // Filter for a specific stereotype. - if (!string.IsNullOrEmpty(stereotype)) - { - var contentTypeDefinitionNames = (await contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(definition => definition.StereotypeEquals(stereotype, StringComparison.OrdinalIgnoreCase)) - .Select(definition => definition.Name) - .ToList(); + // We display a specific type even if it's not listable so that admin pages + // can reuse the content list page for specific types. - // We display a specific type even if it's not listable so that admin pages - // can reuse the content list page for specific types. + if (contentTypeDefinitionNames.Count > 0) + { + var user = httpContextAccessor.HttpContext.User; + var userNameIdentifier = user?.FindFirstValue(ClaimTypes.NameIdentifier); - if (contentTypeDefinitionNames.Count > 0) - { - var user = httpContextAccessor.HttpContext.User; - var userNameIdentifier = user?.FindFirstValue(ClaimTypes.NameIdentifier); + var viewAll = new List(); + var viewOwn = new List(); - var viewAll = new List(); - var viewOwn = new List(); + foreach (var contentTypeDefinitionName in contentTypeDefinitionNames) + { + // It is important to pass null to the owner parameter. This will check if the user can view content that belongs to others. + if (await authorizationService.AuthorizeContentTypeAsync(user, CommonPermissions.ViewContent, contentTypeDefinitionName, owner: null)) + { + viewAll.Add(contentTypeDefinitionName); - foreach (var contentTypeDefinitionName in contentTypeDefinitionNames) - { - // It is important to pass null to the owner parameter. This will check if the user can view content that belongs to others. - if (await authorizationService.AuthorizeContentTypeAsync(user, CommonPermissions.ViewContent, contentTypeDefinitionName, owner: null)) - { - viewAll.Add(contentTypeDefinitionName); + continue; + } + + viewOwn.Add(contentTypeDefinitionName); + } - continue; + return query.With(x => x.ContentType.IsIn(viewAll) || (x.ContentType.IsIn(viewOwn) && x.Owner == userNameIdentifier)); } - viewOwn.Add(contentTypeDefinitionName); + // At this point, the given stereotype is invalid. Ignore it. } - return query.With(x => x.ContentType.IsIn(viewAll) || (x.ContentType.IsIn(viewOwn) && x.Owner == userNameIdentifier)); + return query; } - - // At this point, the given stereotype is invalid. Ignore it. - } - - return query; - }) + ) ) - .WithDefaultTerm(ContentsAdminListFilterOptions.DefaultTermName, builder => builder - .ManyCondition( - (val, query) => query.With(x => x.DisplayText.Contains(val)), - (val, query) => query.With(x => x.DisplayText.NotContains(val)) - ) + .WithDefaultTerm( + ContentsAdminListFilterOptions.DefaultTermName, + builder => + builder.ManyCondition( + (val, query) => query.With(x => x.DisplayText.Contains(val)), + (val, query) => query.With(x => x.DisplayText.NotContains(val)) + ) ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListQueryService.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListQueryService.cs index a79d6cda3da..4cac11171fc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListQueryService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Services/DefaultContentsAdminListQueryService.cs @@ -15,7 +15,7 @@ namespace OrchardCore.Contents.Services; public class DefaultContentsAdminListQueryService : IContentsAdminListQueryService { - private readonly static string[] _operators = ["OR", "AND", "||", "&&"]; + private static readonly string[] _operators = ["OR", "AND", "||", "&&"]; private readonly ISession _session; private readonly IServiceProvider _serviceProvider; @@ -28,7 +28,8 @@ public DefaultContentsAdminListQueryService( IServiceProvider serviceProvider, IEnumerable contentsAdminListFilters, IOptions contentsAdminListFilterOptions, - ILogger logger) + ILogger logger + ) { _session = session; _serviceProvider = serviceProvider; @@ -46,8 +47,7 @@ public async Task> QueryAsync(ContentOptionsViewModel model, if (defaultTermNode is not null) { var value = defaultTermNode.ToString(); - if (_contentsAdminListFilterOptions.UseExactMatch - && !_operators.Any(op => value.Contains(op, StringComparison.Ordinal))) + if (_contentsAdminListFilterOptions.UseExactMatch && !_operators.Any(op => value.Contains(op, StringComparison.Ordinal))) { // Use an unary operator based on a full quoted string. defaultOperator = new UnaryNode(value.Trim('"'), OperateNodeQuotes.Double); @@ -72,8 +72,7 @@ public async Task> QueryAsync(ContentOptionsViewModel model, query = await model.FilterResult.ExecuteAsync(new ContentQueryContext(_serviceProvider, query)); // After the 'q=xx' filters have been applied, allow the secondary filter providers to also parse other values for filtering. - await _contentsAdminListFilters - .InvokeAsync((filter, model, query, updater) => filter.FilterAsync(model, query, updater), model, query, updater, _logger); + await _contentsAdminListFilters.InvokeAsync((filter, model, query, updater) => filter.FilterAsync(model, query, updater), model, query, updater, _logger); if (defaultOperator != defaultTermNode?.Operation) { diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Services/StereotypeFilterNode.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Services/StereotypeFilterNode.cs index ecb7841e2cd..6e4184668d4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Services/StereotypeFilterNode.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Services/StereotypeFilterNode.cs @@ -5,13 +5,9 @@ namespace OrchardCore.Contents.Services; public class StereotypeFilterNode : TermOperationNode { public StereotypeFilterNode(string stereotype) - : base("stereotype", new UnaryNode(stereotype, OperateNodeQuotes.None)) - { - } + : base("stereotype", new UnaryNode(stereotype, OperateNodeQuotes.None)) { } - public override string ToNormalizedString() - => string.Empty; + public override string ToNormalizedString() => string.Empty; - public override string ToString() - => string.Empty; + public override string ToString() => string.Empty; } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Settings/CommonPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Settings/CommonPartSettingsDisplayDriver.cs index a79a3382284..b99b3f82841 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Settings/CommonPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Settings/CommonPartSettingsDisplayDriver.cs @@ -12,12 +12,16 @@ public class CommonPartSettingsDisplayDriver : ContentTypePartDefinitionDisplayD { public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("CommonPartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); - model.DisplayDateEditor = settings.DisplayDateEditor; - model.DisplayOwnerEditor = settings.DisplayOwnerEditor; - }).Location("Content"); + return Initialize( + "CommonPartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); + model.DisplayDateEditor = settings.DisplayDateEditor; + model.DisplayOwnerEditor = settings.DisplayOwnerEditor; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Settings/FullTextAspectSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Settings/FullTextAspectSettingsDisplayDriver.cs index c41bb30d335..737c2142e6c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Settings/FullTextAspectSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Settings/FullTextAspectSettingsDisplayDriver.cs @@ -14,9 +14,7 @@ public class FullTextAspectSettingsDisplayDriver : ContentTypeDefinitionDisplayD private readonly ILiquidTemplateManager _templateManager; protected readonly IStringLocalizer S; - public FullTextAspectSettingsDisplayDriver( - ILiquidTemplateManager templateManager, - IStringLocalizer localizer) + public FullTextAspectSettingsDisplayDriver(ILiquidTemplateManager templateManager, IStringLocalizer localizer) { _templateManager = templateManager; S = localizer; @@ -24,43 +22,45 @@ public FullTextAspectSettingsDisplayDriver( public override IDisplayResult Edit(ContentTypeDefinition contentTypeDefinition) { - return Initialize("FullTextAspectSettings_Edit", model => - { - var settings = contentTypeDefinition.GetSettings(); + return Initialize( + "FullTextAspectSettings_Edit", + model => + { + var settings = contentTypeDefinition.GetSettings(); - model.IncludeFullTextTemplate = settings.IncludeFullTextTemplate; - model.FullTextTemplate = settings.FullTextTemplate; - model.IncludeDisplayText = settings.IncludeDisplayText; - model.IncludeBodyAspect = settings.IncludeBodyAspect; - }).Location("Content:6"); + model.IncludeFullTextTemplate = settings.IncludeFullTextTemplate; + model.FullTextTemplate = settings.FullTextTemplate; + model.IncludeDisplayText = settings.IncludeDisplayText; + model.IncludeBodyAspect = settings.IncludeBodyAspect; + } + ) + .Location("Content:6"); } public override async Task UpdateAsync(ContentTypeDefinition contentTypeDefinition, UpdateTypeEditorContext context) { var model = new FullTextAspectSettingsViewModel(); - await context.Updater.TryUpdateModelAsync(model, Prefix, - m => m.IncludeFullTextTemplate, - m => m.FullTextTemplate, - m => m.IncludeDisplayText, - m => m.IncludeBodyAspect); + await context.Updater.TryUpdateModelAsync(model, Prefix, m => m.IncludeFullTextTemplate, m => m.FullTextTemplate, m => m.IncludeDisplayText, m => m.IncludeBodyAspect); if (!string.IsNullOrEmpty(model.FullTextTemplate) && !_templateManager.Validate(model.FullTextTemplate, out var errors)) { context.Updater.ModelState.AddModelError( nameof(model.FullTextTemplate), - S["Full-text doesn't contain a valid Liquid expression. Details: {0}", - string.Join(' ', errors)]); + S["Full-text doesn't contain a valid Liquid expression. Details: {0}", string.Join(' ', errors)] + ); } else { - context.Builder.WithSettings(new FullTextAspectSettings - { - IncludeFullTextTemplate = model.IncludeFullTextTemplate, - FullTextTemplate = model.FullTextTemplate, - IncludeDisplayText = model.IncludeDisplayText, - IncludeBodyAspect = model.IncludeBodyAspect - }); + context.Builder.WithSettings( + new FullTextAspectSettings + { + IncludeFullTextTemplate = model.IncludeFullTextTemplate, + FullTextTemplate = model.FullTextTemplate, + IncludeDisplayText = model.IncludeDisplayText, + IncludeBodyAspect = model.IncludeBodyAspect + } + ); } return Edit(contentTypeDefinition); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Shapes.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Shapes.cs index de392d1385b..f7393c8bca6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Shapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Shapes.cs @@ -13,7 +13,8 @@ public class Shapes : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("Content") + builder + .Describe("Content") .OnDisplaying(displaying => { var shape = displaying.Shape; @@ -45,7 +46,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) }); // This shapes provides a way to lazily load a content item render it in any display type. - builder.Describe("ContentItem") + builder + .Describe("ContentItem") .OnProcessing(async context => { var content = context.Shape; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceBuilder.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceBuilder.cs index 142587e5e05..0b398b621f3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceBuilder.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceBuilder.cs @@ -25,7 +25,7 @@ public ContentTypesSitemapSourceBuilder( IContentManager contentManager, IContentItemsQueryProvider contentItemsQueryProvider, IEnumerable sitemapContentItemExtendedMetadataProviders - ) + ) { _routeableContentTypeCoordinator = routeableContentTypeCoordinator; _contentManager = contentManager; @@ -54,7 +54,13 @@ public override async Task BuildSourceAsync(ContentTypesSitemapSource source, Si } } - private async Task BuildUrlsetMetadataAsync(ContentTypesSitemapSource source, SitemapBuilderContext context, ContentItemsQueryContext queryContext, ContentItem contentItem, XElement url) + private async Task BuildUrlsetMetadataAsync( + ContentTypesSitemapSource source, + SitemapBuilderContext context, + ContentItemsQueryContext queryContext, + ContentItem contentItem, + XElement url + ) { if (await BuildUrlAsync(context, contentItem, url)) { @@ -66,7 +72,8 @@ private async Task BuildUrlsetMetadataAsync(ContentTypesSitemapSource sour } return false; - }; + } + ; return false; } @@ -117,8 +124,7 @@ private async Task PopulateChangeFrequencyPriority(ContentTypesSitemapSource sou } else { - var sitemapEntry = source.ContentTypes - .FirstOrDefault(ct => string.Equals(ct.ContentTypeName, contentItem.ContentType)); + var sitemapEntry = source.ContentTypes.FirstOrDefault(ct => string.Equals(ct.ContentTypeName, contentItem.ContentType)); changeFrequencyValue = sitemapEntry.ChangeFrequency.ToString(); } @@ -137,8 +143,7 @@ private async Task PopulateChangeFrequencyPriority(ContentTypesSitemapSource sou } else { - var sitemapEntry = source.ContentTypes - .FirstOrDefault(ct => string.Equals(ct.ContentTypeName, contentItem.ContentType)); + var sitemapEntry = source.ContentTypes.FirstOrDefault(ct => string.Equals(ct.ContentTypeName, contentItem.ContentType)); priorityIntValue = sitemapEntry.Priority; } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceDriver.cs index c168a46710f..ddfecf3a850 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceDriver.cs @@ -12,9 +12,7 @@ public class ContentTypesSitemapSourceDriver : DisplayDriver EditAsync(ContentTypesSitemapSource s .ToArray(); var limitedEntries = contentTypeDefinitions - .Select(ctd => new ContentTypeLimitedSitemapEntryViewModel - { - ContentTypeName = ctd.Name, - ContentTypeDisplayName = ctd.DisplayName - }) + .Select(ctd => new ContentTypeLimitedSitemapEntryViewModel { ContentTypeName = ctd.Name, ContentTypeDisplayName = ctd.DisplayName }) .OrderBy(ctd => ctd.ContentTypeDisplayName) .ToArray(); - var limitedCtd = contentTypeDefinitions - .FirstOrDefault(ctd => string.Equals(sitemapSource.LimitedContentType.ContentTypeName, ctd.Name)); + var limitedCtd = contentTypeDefinitions.FirstOrDefault(ctd => string.Equals(sitemapSource.LimitedContentType.ContentTypeName, ctd.Name)); if (limitedCtd != null) { @@ -64,24 +57,30 @@ public override async Task EditAsync(ContentTypesSitemapSource s limitedEntry.Take = sitemapSource.LimitedContentType.Take; } - return Initialize("ContentTypesSitemapSource_Edit", model => - { - model.IndexAll = sitemapSource.IndexAll; - model.LimitItems = sitemapSource.LimitItems; - model.Priority = sitemapSource.Priority; - model.ChangeFrequency = sitemapSource.ChangeFrequency; - model.ContentTypes = entries; - model.LimitedContentTypes = limitedEntries; - model.LimitedContentType = limitedCtd != null ? limitedCtd.Name : contentTypeDefinitions.FirstOrDefault().Name; - model.SitemapSource = sitemapSource; - }).Location("Content"); + return Initialize( + "ContentTypesSitemapSource_Edit", + model => + { + model.IndexAll = sitemapSource.IndexAll; + model.LimitItems = sitemapSource.LimitItems; + model.Priority = sitemapSource.Priority; + model.ChangeFrequency = sitemapSource.ChangeFrequency; + model.ContentTypes = entries; + model.LimitedContentTypes = limitedEntries; + model.LimitedContentType = limitedCtd != null ? limitedCtd.Name : contentTypeDefinitions.FirstOrDefault().Name; + model.SitemapSource = sitemapSource; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypesSitemapSource sitemap, UpdateEditorContext context) { var model = new ContentTypesSitemapSourceViewModel(); - if (await context.Updater.TryUpdateModelAsync(model, + if ( + await context.Updater.TryUpdateModelAsync( + model, Prefix, m => m.IndexAll, m => m.LimitItems, @@ -90,14 +89,15 @@ public override async Task UpdateAsync(ContentTypesSitemapSource m => m.ContentTypes, m => m.LimitedContentTypes, m => m.LimitedContentType - )) + ) + ) { sitemap.IndexAll = model.IndexAll; sitemap.LimitItems = model.LimitItems; sitemap.Priority = model.Priority; sitemap.ChangeFrequency = model.ChangeFrequency; - sitemap.ContentTypes = model.ContentTypes - .Where(x => x.IsChecked == true) + sitemap.ContentTypes = model + .ContentTypes.Where(x => x.IsChecked == true) .Select(x => new ContentTypeSitemapEntry { ContentTypeName = x.ContentTypeName, @@ -119,7 +119,8 @@ public override async Task UpdateAsync(ContentTypesSitemapSource { sitemap.LimitedContentType = new LimitedContentTypeSitemapEntry(); } - }; + } + ; return Edit(sitemap, context.Updater); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceModifiedDateProvider.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceModifiedDateProvider.cs index df230bde0f3..cf5fa2ce134 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceModifiedDateProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceModifiedDateProvider.cs @@ -16,10 +16,7 @@ public class ContentTypesSitemapSourceModifiedDateProvider : SitemapSourceModifi private readonly IRouteableContentTypeCoordinator _routeableContentTypeCoordinator; private readonly ISession _session; - public ContentTypesSitemapSourceModifiedDateProvider( - IRouteableContentTypeCoordinator routeableContentTypeCoordinator, - ISession session - ) + public ContentTypesSitemapSourceModifiedDateProvider(IRouteableContentTypeCoordinator routeableContentTypeCoordinator, ISession session) { _routeableContentTypeCoordinator = routeableContentTypeCoordinator; _session = session; @@ -31,18 +28,16 @@ ISession session if (source.IndexAll) { - var typesToIndex = (await _routeableContentTypeCoordinator.ListRoutableTypeDefinitionsAsync()) - .Select(ctd => ctd.Name); + var typesToIndex = (await _routeableContentTypeCoordinator.ListRoutableTypeDefinitionsAsync()).Select(ctd => ctd.Name); - var query = _session.Query() - .With(x => x.Published && x.ContentType.IsIn(typesToIndex)) - .OrderByDescending(x => x.ModifiedUtc); + var query = _session.Query().With(x => x.Published && x.ContentType.IsIn(typesToIndex)).OrderByDescending(x => x.ModifiedUtc); lastModifiedContentItem = await query.FirstOrDefaultAsync(); } else if (source.LimitItems) { - var query = _session.Query() + var query = _session + .Query() .With(x => x.Published && x.ContentType == source.LimitedContentType.ContentTypeName) .OrderByDescending(x => x.ModifiedUtc); @@ -55,9 +50,7 @@ ISession session .Select(ctd => ctd.Name); // This is an estimate, so doesn't take into account Take/Skip values. - var query = _session.Query() - .With(x => x.Published && x.ContentType.IsIn(typesToIndex)) - .OrderByDescending(x => x.ModifiedUtc); + var query = _session.Query().With(x => x.Published && x.ContentType.IsIn(typesToIndex)).OrderByDescending(x => x.ModifiedUtc); lastModifiedContentItem = await query.FirstOrDefaultAsync(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceUpdateHandler.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceUpdateHandler.cs index d1deabfce75..93b4776c865 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceUpdateHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapSourceUpdateHandler.cs @@ -25,8 +25,7 @@ public async Task UpdateSitemapAsync(SitemapUpdateContext context) return; } - var sitemaps = (await _sitemapManager.LoadSitemapsAsync()) - .Where(s => s.GetType() == typeof(Sitemap)); + var sitemaps = (await _sitemapManager.LoadSitemapsAsync()).Where(s => s.GetType() == typeof(Sitemap)); if (!sitemaps.Any()) { @@ -38,8 +37,7 @@ public async Task UpdateSitemapAsync(SitemapUpdateContext context) foreach (var sitemap in sitemaps) { // Do not break out of this loop, as it must check each sitemap. - foreach (var source in sitemap.SitemapSources - .Select(s => s as ContentTypesSitemapSource)) + foreach (var source in sitemap.SitemapSources.Select(s => s as ContentTypesSitemapSource)) { if (source == null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapUpdateHandler.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapUpdateHandler.cs index 64b7a9c7aae..0146096bde8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapUpdateHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/ContentTypesSitemapUpdateHandler.cs @@ -15,20 +15,14 @@ public ContentTypesSitemapUpdateHandler(ISitemapUpdateHandler sitemapUpdateHandl public override Task PublishedAsync(PublishContentContext context) { - var updateContext = new SitemapUpdateContext - { - UpdateObject = context.ContentItem, - }; + var updateContext = new SitemapUpdateContext { UpdateObject = context.ContentItem, }; return _sitemapUpdateHandler.UpdateSitemapAsync(updateContext); } public override Task UnpublishedAsync(PublishContentContext context) { - var updateContext = new SitemapUpdateContext - { - UpdateObject = context.ContentItem, - }; + var updateContext = new SitemapUpdateContext { UpdateObject = context.ContentItem, }; return _sitemapUpdateHandler.UpdateSitemapAsync(updateContext); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/DefaultContentItemsQueryProvider.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/DefaultContentItemsQueryProvider.cs index e47ece9634e..7d7ad5620c9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/DefaultContentItemsQueryProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Sitemaps/DefaultContentItemsQueryProvider.cs @@ -15,10 +15,7 @@ public class DefaultContentItemsQueryProvider : IContentItemsQueryProvider private readonly ISession _session; private readonly IRouteableContentTypeCoordinator _routeableContentTypeCoordinator; - public DefaultContentItemsQueryProvider( - ISession session, - IRouteableContentTypeCoordinator routeableContentTypeCoordinator - ) + public DefaultContentItemsQueryProvider(ISession session, IRouteableContentTypeCoordinator routeableContentTypeCoordinator) { _session = session; _routeableContentTypeCoordinator = routeableContentTypeCoordinator; @@ -32,7 +29,8 @@ public async Task GetContentItemsAsync(ContentTypesSitemapSource source, Content { var rctdNames = routeableContentTypeDefinitions.Select(rctd => rctd.Name); - var queryResults = await _session.Query() + var queryResults = await _session + .Query() .With(x => x.Published && x.ContentType.IsIn(rctdNames)) .OrderBy(x => x.CreatedUtc) .ListAsync(); @@ -42,12 +40,12 @@ public async Task GetContentItemsAsync(ContentTypesSitemapSource source, Content else if (source.LimitItems) { // Test that content type is still valid to include in sitemap. - var typeIsValid = routeableContentTypeDefinitions - .Any(ctd => string.Equals(source.LimitedContentType.ContentTypeName, ctd.Name)); + var typeIsValid = routeableContentTypeDefinitions.Any(ctd => string.Equals(source.LimitedContentType.ContentTypeName, ctd.Name)); if (typeIsValid) { - var queryResults = await _session.Query() + var queryResults = await _session + .Query() .With(x => x.ContentType == source.LimitedContentType.ContentTypeName && x.Published) .OrderBy(x => x.CreatedUtc) .Skip(source.LimitedContentType.Skip) @@ -60,11 +58,10 @@ public async Task GetContentItemsAsync(ContentTypesSitemapSource source, Content else { // Test that content types are still valid to include in sitemap. - var typesToIndex = routeableContentTypeDefinitions - .Where(ctd => source.ContentTypes.Any(s => string.Equals(ctd.Name, s.ContentTypeName))) - .Select(x => x.Name); + var typesToIndex = routeableContentTypeDefinitions.Where(ctd => source.ContentTypes.Any(s => string.Equals(ctd.Name, s.ContentTypeName))).Select(x => x.Name); - var queryResults = await _session.Query() + var queryResults = await _session + .Query() .With(x => x.ContentType.IsIn(typesToIndex) && x.Published) .OrderBy(x => x.CreatedUtc) .ListAsync(); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Startup.cs index cf2abe2e624..eb15ed334c5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Startup.cs @@ -1,3 +1,5 @@ +using System; +using System.Threading.Tasks; using Fluid; using Fluid.Values; using Microsoft.AspNetCore.Authorization; @@ -50,8 +52,6 @@ using OrchardCore.Sitemaps.Handlers; using OrchardCore.Sitemaps.Models; using OrchardCore.Sitemaps.Services; -using System; -using System.Threading.Tasks; using YesSql.Filters.Query; namespace OrchardCore.Contents @@ -67,76 +67,95 @@ public override void ConfigureServices(IServiceCollection services) o.LiquidViewParserConfiguration.Add(parser => parser.RegisterParserTag("contentitem", parser.ArgumentsListParser, ContentItemTag.WriteToAsync)); }); - services.Configure(o => - { - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register>(); - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - - o.Filters.AddFilter("display_text", DisplayTextFilter.DisplayText); - - o.Scope.SetValue("Content", new ObjectValue(new LiquidContentAccessor())); - o.MemberAccessStrategy.Register("ContentItemId", (obj, context) => + services + .Configure(o => { - var liquidTemplateContext = (LiquidTemplateContext)context; - - return new LiquidPropertyAccessor(liquidTemplateContext, async (contentItemId, context) => + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register>(); + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); + + o.Filters.AddFilter("display_text", DisplayTextFilter.DisplayText); + + o.Scope.SetValue("Content", new ObjectValue(new LiquidContentAccessor())); + o.MemberAccessStrategy.Register( + "ContentItemId", + (obj, context) => + { + var liquidTemplateContext = (LiquidTemplateContext)context; + + return new LiquidPropertyAccessor( + liquidTemplateContext, + async (contentItemId, context) => + { + var contentManager = context.Services.GetRequiredService(); + + return FluidValue.Create(await contentManager.GetAsync(contentItemId), context.Options); + } + ); + } + ); + + o.MemberAccessStrategy.Register( + "ContentItemVersionId", + (obj, context) => + { + var liquidTemplateContext = (LiquidTemplateContext)context; + + return new LiquidPropertyAccessor( + liquidTemplateContext, + async (contentItemVersionId, context) => + { + var contentManager = context.Services.GetRequiredService(); + + return FluidValue.Create(await contentManager.GetVersionAsync(contentItemVersionId), context.Options); + } + ); + } + ); + + o.MemberAccessStrategy.Register( + "Latest", + (obj, context) => + { + var liquidTemplateContext = (LiquidTemplateContext)context; + + return new LiquidPropertyAccessor( + liquidTemplateContext, + (name, context) => + { + return GetContentByHandleAsync(context, name, true); + } + ); + } + ); + + o.MemberAccessStrategy.Register((obj, name, context) => GetContentByHandleAsync((LiquidTemplateContext)context, name)); + + static async Task GetContentByHandleAsync(LiquidTemplateContext context, string handle, bool latest = false) { - var contentManager = context.Services.GetRequiredService(); + var contentHandleManager = context.Services.GetRequiredService(); - return FluidValue.Create(await contentManager.GetAsync(contentItemId), context.Options); - }); - }); + var contentItemId = await contentHandleManager.GetContentItemIdAsync(handle); - o.MemberAccessStrategy.Register("ContentItemVersionId", (obj, context) => - { - var liquidTemplateContext = (LiquidTemplateContext)context; + if (contentItemId == null) + { + return NilValue.Instance; + } - return new LiquidPropertyAccessor(liquidTemplateContext, async (contentItemVersionId, context) => - { var contentManager = context.Services.GetRequiredService(); - return FluidValue.Create(await contentManager.GetVersionAsync(contentItemVersionId), context.Options); - }); - }); - - o.MemberAccessStrategy.Register("Latest", (obj, context) => - { - var liquidTemplateContext = (LiquidTemplateContext)context; - - return new LiquidPropertyAccessor(liquidTemplateContext, (name, context) => - { - return GetContentByHandleAsync(context, name, true); - }); - }); - - o.MemberAccessStrategy.Register((obj, name, context) => GetContentByHandleAsync((LiquidTemplateContext)context, name)); - - static async Task GetContentByHandleAsync(LiquidTemplateContext context, string handle, bool latest = false) - { - var contentHandleManager = context.Services.GetRequiredService(); - - var contentItemId = await contentHandleManager.GetContentItemIdAsync(handle); - - if (contentItemId == null) - { - return NilValue.Instance; + var contentItem = await contentManager.GetAsync(contentItemId, latest ? VersionOptions.Latest : VersionOptions.Published); + return FluidValue.Create(contentItem, context.Options); } - - var contentManager = context.Services.GetRequiredService(); - - var contentItem = await contentManager.GetAsync(contentItemId, latest ? VersionOptions.Latest : VersionOptions.Published); - return FluidValue.Create(contentItem, context.Options); - } - }) - .AddLiquidFilter("display_url") - .AddLiquidFilter("shape_build_display") - .AddLiquidFilter("content_item_id") - .AddLiquidFilter("full_text"); + }) + .AddLiquidFilter("display_url") + .AddLiquidFilter("shape_build_display") + .AddLiquidFilter("content_item_id") + .AddLiquidFilter("full_text"); services.AddContentManagement(); services.AddContentManagementDisplay(); @@ -158,9 +177,7 @@ static async Task GetContentByHandleAsync(LiquidTemplateContext cont services.AddDataMigration(); // Common Part - services.AddContentPart() - .UseDisplayDriver() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver().UseDisplayDriver(); services.AddScoped(); @@ -176,9 +193,9 @@ static async Task GetContentByHandleAsync(LiquidTemplateContext cont { options.GlobalRouteValues = new RouteValueDictionary { - {"Area", "OrchardCore.Contents"}, - {"Controller", "Item"}, - {"Action", "Display"} + { "Area", "OrchardCore.Contents" }, + { "Controller", "Item" }, + { "Action", "Display" } }; options.ContentItemIdKey = "contentItemId"; @@ -244,7 +261,10 @@ public override void ConfigureServices(IServiceCollection services) { services.AddDeployment(); services.AddDeployment(); - services.AddSiteSettingsPropertyDeploymentStep(S => S["Content Audit Trail settings"], S => S["Exports the content audit trail settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Content Audit Trail settings"], + S => S["Exports the content audit trail settings."] + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/ViewComponents/DisplayContentItemViewComponent.cs b/src/OrchardCore.Modules/OrchardCore.Contents/ViewComponents/DisplayContentItemViewComponent.cs index d2559ecd39a..b0ffe239070 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/ViewComponents/DisplayContentItemViewComponent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/ViewComponents/DisplayContentItemViewComponent.cs @@ -13,10 +13,7 @@ public class DisplayContentItemViewComponent : ViewComponent private readonly IContentItemDisplayManager _contentItemDisplayManager; private readonly IUpdateModelAccessor _modelUpdaterAccessor; - public DisplayContentItemViewComponent( - IContentManager contentManager, - IContentItemDisplayManager contentItemDisplayManager, - IUpdateModelAccessor modelUpdaterAccessor) + public DisplayContentItemViewComponent(IContentManager contentManager, IContentItemDisplayManager contentItemDisplayManager, IUpdateModelAccessor modelUpdaterAccessor) { _contentItemDisplayManager = contentItemDisplayManager; _contentManager = contentManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/ViewComponents/SelectContentTypesViewComponent.cs b/src/OrchardCore.Modules/OrchardCore.Contents/ViewComponents/SelectContentTypesViewComponent.cs index 026715d0f4d..ff0f630ca59 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/ViewComponents/SelectContentTypesViewComponent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/ViewComponents/SelectContentTypesViewComponent.cs @@ -26,16 +26,10 @@ public async Task InvokeAsync(IEnumerable selected if (!string.IsNullOrEmpty(stereotype)) { - contentTypes = contentTypes - .Where(x => x.ContentTypeDefinition.GetStereotype() == stereotype) - .ToArray(); + contentTypes = contentTypes.Where(x => x.ContentTypeDefinition.GetStereotype() == stereotype).ToArray(); } - var model = new SelectContentTypesViewModel - { - HtmlName = htmlName, - ContentTypeSelections = contentTypes - }; + var model = new SelectContentTypesViewModel { HtmlName = htmlName, ContentTypeSelections = contentTypes }; return View(model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/ViewModels/SelectContentTypesViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/ViewModels/SelectContentTypesViewModel.cs index 1a4ff7d0f39..16eceda9eda 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/ViewModels/SelectContentTypesViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/ViewModels/SelectContentTypesViewModel.cs @@ -19,18 +19,13 @@ public class ContentTypeSelection public ContentTypeDefinition ContentTypeDefinition { get; set; } [Obsolete($"Instead, utilize the {nameof(BuildAsync)} method. This current method is slated for removal in upcoming releases.")] - public static ContentTypeSelection[] Build(IContentDefinitionManager contentDefinitionManager, IEnumerable selectedContentTypes) - => BuildAsync(contentDefinitionManager, selectedContentTypes).GetAwaiter().GetResult(); + public static ContentTypeSelection[] Build(IContentDefinitionManager contentDefinitionManager, IEnumerable selectedContentTypes) => + BuildAsync(contentDefinitionManager, selectedContentTypes).GetAwaiter().GetResult(); public static async Task BuildAsync(IContentDefinitionManager contentDefinitionManager, IEnumerable selectedContentTypes) { var contentTypes = (await contentDefinitionManager.ListTypeDefinitionsAsync()) - .Select(x => - new ContentTypeSelection - { - IsSelected = selectedContentTypes.Contains(x.Name), - ContentTypeDefinition = x - }) + .Select(x => new ContentTypeSelection { IsSelected = selectedContentTypes.Contains(x.Name), ContentTypeDefinition = x }) .OrderBy(type => type.ContentTypeDefinition.DisplayName) .ToArray(); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentActivity.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentActivity.cs index ce7900fa5ce..786993f086e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentActivity.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentActivity.cs @@ -18,10 +18,7 @@ public abstract class ContentActivity : Activity { protected readonly IStringLocalizer S; - protected ContentActivity( - IContentManager contentManager, - IWorkflowScriptEvaluator scriptEvaluator, - IStringLocalizer localizer) + protected ContentActivity(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) { ContentManager = contentManager; ScriptEvaluator = scriptEvaluator; @@ -134,7 +131,8 @@ protected virtual async Task GetContentAsync(WorkflowExecutionContext else { // If no expression was provided, see if the content item was provided as an input or as a property. - content = workflowContext.Input.GetValue(ContentEventConstants.ContentItemInputKey) + content = + workflowContext.Input.GetValue(ContentEventConstants.ContentItemInputKey) ?? workflowContext.Properties.GetValue(ContentEventConstants.ContentItemInputKey); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentCreatedEvent.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentCreatedEvent.cs index 289783fe5a2..08b356813f2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentCreatedEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentCreatedEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class ContentCreatedEvent : ContentEvent { - public ContentCreatedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public ContentCreatedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(ContentCreatedEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentDeletedEvent.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentDeletedEvent.cs index fd3e6662b7c..2ae7a964ac1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentDeletedEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentDeletedEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class ContentDeletedEvent : ContentEvent { - public ContentDeletedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public ContentDeletedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(ContentDeletedEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentDraftSavedEvent.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentDraftSavedEvent.cs index 21b93d631e6..72fe52f2d8d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentDraftSavedEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentDraftSavedEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class ContentDraftSavedEvent : ContentEvent { - public ContentDraftSavedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public ContentDraftSavedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(ContentDraftSavedEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentEvent.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentEvent.cs index d2e3c401a7d..01d0f0470c5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentEvent.cs @@ -11,9 +11,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public abstract class ContentEvent : ContentActivity, IEvent { - protected ContentEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + protected ContentEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public IList ContentTypeFilter { diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentPublishedEvent.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentPublishedEvent.cs index 9e37381ed4f..1bf564f84ce 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentPublishedEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentPublishedEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class ContentPublishedEvent : ContentEvent { - public ContentPublishedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public ContentPublishedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(ContentPublishedEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentTask.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentTask.cs index b261683acab..b6ef28b3aa0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentTask.cs @@ -8,8 +8,6 @@ namespace OrchardCore.Contents.Workflows.Activities public abstract class ContentTask : ContentActivity, ITask { protected ContentTask(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) - : base(contentManager, scriptEvaluator, localizer) - { - } + : base(contentManager, scriptEvaluator, localizer) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentUnpublishedEvent.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentUnpublishedEvent.cs index 64938986b15..e1a9a36d048 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentUnpublishedEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentUnpublishedEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class ContentUnpublishedEvent : ContentEvent { - public ContentUnpublishedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public ContentUnpublishedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(ContentUnpublishedEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentUpdatedEvent.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentUpdatedEvent.cs index 8ecc1238f3d..db23fa5bcae 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentUpdatedEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentUpdatedEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class ContentUpdatedEvent : ContentEvent { - public ContentUpdatedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public ContentUpdatedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(ContentUpdatedEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentVersionedEvent.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentVersionedEvent.cs index 51322519090..e8edc9de93f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentVersionedEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/ContentVersionedEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class ContentVersionedEvent : ContentEvent { - public ContentVersionedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public ContentVersionedEvent(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(ContentVersionedEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/CreateContentTask.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/CreateContentTask.cs index 27c2ede4d60..8e9a4aabeae 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/CreateContentTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/CreateContentTask.cs @@ -24,7 +24,8 @@ public CreateContentTask( IWorkflowExpressionEvaluator expressionEvaluator, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer, - JavaScriptEncoder javaScriptEncoder) + JavaScriptEncoder javaScriptEncoder + ) : base(contentManager, scriptEvaluator, localizer) { _expressionEvaluator = expressionEvaluator; @@ -65,28 +66,36 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex return Outcomes(S["Done"], S["Failed"]); } - public async override Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) + public override async Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { if (InlineEvent.IsStart && InlineEvent.ContentType == ContentType) { if (InlineEvent.Name == nameof(ContentUpdatedEvent)) { - throw new InvalidOperationException($"The '{nameof(CreateContentTask)}' can't update the content item as it is executed inline from a starting '{nameof(ContentUpdatedEvent)}' of the same content type, which would result in an infinitive loop."); + throw new InvalidOperationException( + $"The '{nameof(CreateContentTask)}' can't update the content item as it is executed inline from a starting '{nameof(ContentUpdatedEvent)}' of the same content type, which would result in an infinitive loop." + ); } if (InlineEvent.Name == nameof(ContentCreatedEvent)) { - throw new InvalidOperationException($"The '{nameof(CreateContentTask)}' can't create the content item as it is executed inline from a starting '{nameof(ContentCreatedEvent)}' of the same content type, which would result in an infinitive loop."); + throw new InvalidOperationException( + $"The '{nameof(CreateContentTask)}' can't create the content item as it is executed inline from a starting '{nameof(ContentCreatedEvent)}' of the same content type, which would result in an infinitive loop." + ); } if (Publish && InlineEvent.Name == nameof(ContentPublishedEvent)) { - throw new InvalidOperationException($"The '{nameof(CreateContentTask)}' can't publish the content item as it is executed inline from a starting '{nameof(ContentPublishedEvent)}' of the same content type, which would result in an infinitive loop."); + throw new InvalidOperationException( + $"The '{nameof(CreateContentTask)}' can't publish the content item as it is executed inline from a starting '{nameof(ContentPublishedEvent)}' of the same content type, which would result in an infinitive loop." + ); } if (!Publish && InlineEvent.Name == nameof(ContentDraftSavedEvent)) { - throw new InvalidOperationException($"The '{nameof(CreateContentTask)}' can't create the content item as it is executed inline from a starting '{nameof(ContentDraftSavedEvent)}' of the same content type, which would result in an infinitive loop."); + throw new InvalidOperationException( + $"The '{nameof(CreateContentTask)}' can't create the content item as it is executed inline from a starting '{nameof(ContentDraftSavedEvent)}' of the same content type, which would result in an infinitive loop." + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/DeleteContentTask.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/DeleteContentTask.cs index 7022ebc6185..31f57cb2946 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/DeleteContentTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/DeleteContentTask.cs @@ -12,9 +12,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class DeleteContentTask : ContentTask { - public DeleteContentTask(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public DeleteContentTask(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(DeleteContentTask); @@ -29,8 +28,8 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex public override async Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - var content = (await GetContentAsync(workflowContext)) - ?? throw new InvalidOperationException($"The '{nameof(DeleteContentTask)}' failed to retrieve the content item."); + var content = + (await GetContentAsync(workflowContext)) ?? throw new InvalidOperationException($"The '{nameof(DeleteContentTask)}' failed to retrieve the content item."); if (string.Equals(InlineEvent.ContentItemId, content.ContentItem.ContentItemId, StringComparison.OrdinalIgnoreCase)) { @@ -51,7 +50,9 @@ public override async Task ExecuteAsync(WorkflowExecuti if (InlineEvent.IsStart && InlineEvent.ContentType == contentItem.ContentType && InlineEvent.Name == nameof(ContentDeletedEvent)) { - throw new InvalidOperationException($"The '{nameof(DeleteContentTask)}' can't delete the content item as it is executed inline from a starting '{nameof(ContentDeletedEvent)}' of the same content type, which would result in an infinitive loop."); + throw new InvalidOperationException( + $"The '{nameof(DeleteContentTask)}' can't delete the content item as it is executed inline from a starting '{nameof(ContentDeletedEvent)}' of the same content type, which would result in an infinitive loop." + ); } await ContentManager.RemoveAsync(contentItem); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/PublishContentTask.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/PublishContentTask.cs index f6919242a23..2e1f7d6bfaf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/PublishContentTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/PublishContentTask.cs @@ -12,9 +12,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class PublishContentTask : ContentTask { - public PublishContentTask(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public PublishContentTask(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(PublishContentTask); @@ -29,8 +28,8 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex public override async Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - var content = (await GetContentAsync(workflowContext)) - ?? throw new InvalidOperationException($"The '{nameof(PublishContentTask)}' failed to retrieve the content item."); + var content = + (await GetContentAsync(workflowContext)) ?? throw new InvalidOperationException($"The '{nameof(PublishContentTask)}' failed to retrieve the content item."); if (string.Equals(InlineEvent.ContentItemId, content.ContentItem.ContentItemId, StringComparison.OrdinalIgnoreCase)) { @@ -51,7 +50,9 @@ public override async Task ExecuteAsync(WorkflowExecuti if (InlineEvent.IsStart && InlineEvent.ContentType == contentItem.ContentType && InlineEvent.Name == nameof(ContentPublishedEvent)) { - throw new InvalidOperationException($"The '{nameof(PublishContentTask)}' can't publish the content item as it is executed inline from a starting '{nameof(ContentPublishedEvent)}' of the same content type, which would result in an infinitive loop."); + throw new InvalidOperationException( + $"The '{nameof(PublishContentTask)}' can't publish the content item as it is executed inline from a starting '{nameof(ContentPublishedEvent)}' of the same content type, which would result in an infinitive loop." + ); } await ContentManager.PublishAsync(contentItem); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/RetrieveContentTask.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/RetrieveContentTask.cs index b5475c5debb..eb4c5ffd18d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/RetrieveContentTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/RetrieveContentTask.cs @@ -13,9 +13,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class RetrieveContentTask : ContentTask { - public RetrieveContentTask(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public RetrieveContentTask(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(RetrieveContentTask); @@ -30,10 +29,12 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex public override async Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - var contentItemId = (await GetContentItemIdAsync(workflowContext)) + var contentItemId = + (await GetContentItemIdAsync(workflowContext)) ?? throw new InvalidOperationException($"The '{nameof(RetrieveContentTask)}' failed to evaluate the 'ContentItemId'."); - var contentItem = (await ContentManager.GetAsync(contentItemId, VersionOptions.Latest)) + var contentItem = + (await ContentManager.GetAsync(contentItemId, VersionOptions.Latest)) ?? throw new InvalidOperationException($"The '{nameof(RetrieveContentTask)}' failed to retrieve the content item."); workflowContext.CorrelationId = contentItem.ContentItemId; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/UnpublishContentTask.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/UnpublishContentTask.cs index af2b8a4a3af..9b7e638f3ce 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/UnpublishContentTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/UnpublishContentTask.cs @@ -12,9 +12,8 @@ namespace OrchardCore.Contents.Workflows.Activities { public class UnpublishContentTask : ContentTask { - public UnpublishContentTask(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(contentManager, scriptEvaluator, localizer) - { - } + public UnpublishContentTask(IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(UnpublishContentTask); @@ -29,8 +28,8 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex public override async Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - var content = (await GetContentAsync(workflowContext)) - ?? throw new InvalidOperationException($"The '{nameof(UnpublishContentTask)}' failed to retrieve the content item."); + var content = + (await GetContentAsync(workflowContext)) ?? throw new InvalidOperationException($"The '{nameof(UnpublishContentTask)}' failed to retrieve the content item."); if (string.Equals(InlineEvent.ContentItemId, content.ContentItem.ContentItemId, StringComparison.OrdinalIgnoreCase)) { @@ -51,7 +50,9 @@ public override async Task ExecuteAsync(WorkflowExecuti if (InlineEvent.IsStart && InlineEvent.ContentType == contentItem.ContentType && InlineEvent.Name == nameof(ContentUnpublishedEvent)) { - throw new InvalidOperationException($"The '{nameof(UnpublishContentTask)}' can't unpublish the content item as it is executed inline from a starting '{nameof(ContentUnpublishedEvent)}' of the same content type, which would result in an infinitive loop."); + throw new InvalidOperationException( + $"The '{nameof(UnpublishContentTask)}' can't unpublish the content item as it is executed inline from a starting '{nameof(ContentUnpublishedEvent)}' of the same content type, which would result in an infinitive loop." + ); } await ContentManager.UnpublishAsync(contentItem); diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/UpdateContentTask.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/UpdateContentTask.cs index 77c0061be1b..107f6e6b1cb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/UpdateContentTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/UpdateContentTask.cs @@ -29,7 +29,8 @@ public UpdateContentTask( IWorkflowExpressionEvaluator expressionEvaluator, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer, - JavaScriptEncoder javaScriptEncoder) + JavaScriptEncoder javaScriptEncoder + ) : base(contentManager, scriptEvaluator, localizer) { _updateModelAccessor = updateModelAccessor; @@ -57,11 +58,12 @@ public WorkflowExpression ContentItemIdExpression public WorkflowExpression ContentProperties { - get => GetProperty(() => - // new WorkflowExpression(JsonConvert.SerializeObject(new { DisplayText = S["Enter a title"].Value }, Formatting.Indented))); - new WorkflowExpression(JConvert.SerializeObject(new { DisplayText = S["Enter a title"].Value }))); - - + get => + GetProperty( + () => + // new WorkflowExpression(JsonConvert.SerializeObject(new { DisplayText = S["Enter a title"].Value }, Formatting.Indented))); + new WorkflowExpression(JConvert.SerializeObject(new { DisplayText = S["Enter a title"].Value })) + ); set => SetProperty(value); } @@ -70,10 +72,10 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex return Outcomes(S["Done"], S["Failed"]); } - public async override Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) + public override async Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - var contentItemId = (await GetContentItemIdAsync(workflowContext)) - ?? throw new InvalidOperationException($"The {nameof(UpdateContentTask)} failed to evaluate the 'ContentItemId'."); + var contentItemId = + (await GetContentItemIdAsync(workflowContext)) ?? throw new InvalidOperationException($"The {nameof(UpdateContentTask)} failed to evaluate the 'ContentItemId'."); var inlineEventOfSameContentItemId = string.Equals(InlineEvent.ContentItemId, contentItemId, StringComparison.OrdinalIgnoreCase); @@ -81,12 +83,16 @@ public async override Task ExecuteAsync(WorkflowExecuti { if (InlineEvent.Name == nameof(ContentPublishedEvent)) { - throw new InvalidOperationException($"The '{nameof(UpdateContentTask)}' can't update the content item as it is executed inline from a '{nameof(ContentPublishedEvent)}' of the same content item, please use an event that is triggered earlier."); + throw new InvalidOperationException( + $"The '{nameof(UpdateContentTask)}' can't update the content item as it is executed inline from a '{nameof(ContentPublishedEvent)}' of the same content item, please use an event that is triggered earlier." + ); } if (InlineEvent.Name == nameof(ContentDraftSavedEvent)) { - throw new InvalidOperationException($"The '{nameof(UpdateContentTask)}' can't update the content item as it is executed inline from a '{nameof(ContentDraftSavedEvent)}' of the same content item, please use an event that is triggered earlier."); + throw new InvalidOperationException( + $"The '{nameof(UpdateContentTask)}' can't update the content item as it is executed inline from a '{nameof(ContentDraftSavedEvent)}' of the same content item, please use an event that is triggered earlier." + ); } } @@ -110,17 +116,23 @@ public async override Task ExecuteAsync(WorkflowExecuti { if (InlineEvent.Name == nameof(ContentUpdatedEvent)) { - throw new InvalidOperationException($"The '{nameof(UpdateContentTask)}' can't update the content item as it is executed inline from a starting '{nameof(ContentUpdatedEvent)}' of the same content type, which would result in an infinitive loop."); + throw new InvalidOperationException( + $"The '{nameof(UpdateContentTask)}' can't update the content item as it is executed inline from a starting '{nameof(ContentUpdatedEvent)}' of the same content type, which would result in an infinitive loop." + ); } if (Publish && InlineEvent.Name == nameof(ContentPublishedEvent)) { - throw new InvalidOperationException($"The '{nameof(UpdateContentTask)}' can't publish the content item as it is executed inline from a starting '{nameof(ContentPublishedEvent)}' of the same content type, which would result in an infinitive loop."); + throw new InvalidOperationException( + $"The '{nameof(UpdateContentTask)}' can't publish the content item as it is executed inline from a starting '{nameof(ContentPublishedEvent)}' of the same content type, which would result in an infinitive loop." + ); } if (!Publish && InlineEvent.Name == nameof(ContentDraftSavedEvent)) { - throw new InvalidOperationException($"The '{nameof(UpdateContentTask)}' can't update the content item as it is executed inline from a starting '{nameof(ContentDraftSavedEvent)}' of the same content type, which would result in an infinitive loop."); + throw new InvalidOperationException( + $"The '{nameof(UpdateContentTask)}' can't update the content item as it is executed inline from a starting '{nameof(ContentDraftSavedEvent)}' of the same content type, which would result in an infinitive loop." + ); } } @@ -160,9 +172,10 @@ public async override Task ExecuteAsync(WorkflowExecuti if (inlineEventOfSameContentItemId) { - _updateModelAccessor.ModelUpdater.ModelState.AddModelError(nameof(UpdateContentTask), - $"The '{workflowContext.WorkflowType.Name}:{nameof(UpdateContentTask)}' failed to update the content item: " - + string.Join(", ", result.Errors)); + _updateModelAccessor.ModelUpdater.ModelState.AddModelError( + nameof(UpdateContentTask), + $"The '{workflowContext.WorkflowType.Name}:{nameof(UpdateContentTask)}' failed to update the content item: " + string.Join(", ", result.Errors) + ); } workflowContext.LastResult = result; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentCreatedEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentCreatedEventDisplayDriver.cs index 7b727e7c9de..74c3ec9cbc2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentCreatedEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentCreatedEventDisplayDriver.cs @@ -6,8 +6,7 @@ namespace OrchardCore.Contents.Workflows.Drivers { public class ContentCreatedEventDisplayDriver : ContentEventDisplayDriver { - public ContentCreatedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) : base(contentDefinitionManager) - { - } + public ContentCreatedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) + : base(contentDefinitionManager) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentDeletedEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentDeletedEventDisplayDriver.cs index c79dd7db80d..a11e18ec73c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentDeletedEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentDeletedEventDisplayDriver.cs @@ -6,8 +6,7 @@ namespace OrchardCore.Contents.Workflows.Drivers { public class ContentDeletedEventDisplayDriver : ContentEventDisplayDriver { - public ContentDeletedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) : base(contentDefinitionManager) - { - } + public ContentDeletedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) + : base(contentDefinitionManager) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentDraftSavedEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentDraftSavedEventDisplayDriver.cs index 8d46fab9da7..73af6d99883 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentDraftSavedEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentDraftSavedEventDisplayDriver.cs @@ -6,8 +6,7 @@ namespace OrchardCore.Contents.Workflows.Drivers { public class ContentDraftSavedEventDisplayDriver : ContentEventDisplayDriver { - public ContentDraftSavedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) : base(contentDefinitionManager) - { - } + public ContentDraftSavedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) + : base(contentDefinitionManager) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentEventDisplayDriver.cs index 74b8883a45f..7883475c19a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentEventDisplayDriver.cs @@ -11,7 +11,9 @@ namespace OrchardCore.Contents.Workflows.Drivers { - public abstract class ContentEventDisplayDriver : ActivityDisplayDriver where TActivity : ContentEvent where TViewModel : ContentEventViewModel, new() + public abstract class ContentEventDisplayDriver : ActivityDisplayDriver + where TActivity : ContentEvent + where TViewModel : ContentEventViewModel, new() { protected ContentEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) { @@ -25,7 +27,7 @@ protected override void EditActivity(TActivity source, TViewModel target) target.SelectedContentTypeNames = source.ContentTypeFilter; } - public async override Task UpdateAsync(TActivity model, IUpdateModel updater) + public override async Task UpdateAsync(TActivity model, IUpdateModel updater) { var viewModel = new TViewModel(); if (await updater.TryUpdateModelAsync(viewModel, Prefix, x => x.SelectedContentTypeNames)) @@ -39,19 +41,19 @@ public override IDisplayResult Display(TActivity activity) { return Combine( Shape($"{typeof(TActivity).Name}_Fields_Thumbnail", new ContentEventViewModel(activity)).Location("Thumbnail", "Content"), - Factory($"{typeof(TActivity).Name}_Fields_Design", async ctx => - { - var contentTypeDefinitions = (await ContentDefinitionManager.ListTypeDefinitionsAsync()).ToDictionary(x => x.Name); - var selectedContentTypeDefinitions = activity.ContentTypeFilter.Select(x => contentTypeDefinitions[x]).ToList(); + Factory( + $"{typeof(TActivity).Name}_Fields_Design", + async ctx => + { + var contentTypeDefinitions = (await ContentDefinitionManager.ListTypeDefinitionsAsync()).ToDictionary(x => x.Name); + var selectedContentTypeDefinitions = activity.ContentTypeFilter.Select(x => contentTypeDefinitions[x]).ToList(); - var shape = new ContentEventViewModel - { - ContentTypeFilter = selectedContentTypeDefinitions, - Activity = activity, - }; + var shape = new ContentEventViewModel { ContentTypeFilter = selectedContentTypeDefinitions, Activity = activity, }; - return shape; - }).Location("Design", "Content") + return shape; + } + ) + .Location("Design", "Content") ); } @@ -59,8 +61,7 @@ public override IDisplayResult Display(TActivity activity) /// Filters out any content type that doesn't exist. /// [Obsolete($"Instead, utilize the {nameof(FilterContentTypesQueryAsync)} method. This current method is slated for removal in upcoming releases.")] - protected IEnumerable FilterContentTypesQuery(IEnumerable contentTypeNames) - => FilterContentTypesQueryAsync(contentTypeNames).GetAwaiter().GetResult(); + protected IEnumerable FilterContentTypesQuery(IEnumerable contentTypeNames) => FilterContentTypesQueryAsync(contentTypeNames).GetAwaiter().GetResult(); protected async Task> FilterContentTypesQueryAsync(IEnumerable contentTypeNames) { diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentPublishedEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentPublishedEventDisplayDriver.cs index c25d3c2ecee..77cd5e8d1ed 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentPublishedEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentPublishedEventDisplayDriver.cs @@ -6,8 +6,7 @@ namespace OrchardCore.Contents.Workflows.Drivers { public class ContentPublishedEventDisplayDriver : ContentEventDisplayDriver { - public ContentPublishedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) : base(contentDefinitionManager) - { - } + public ContentPublishedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) + : base(contentDefinitionManager) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentTaskDisplayDriver.cs index e4717018d71..e4bd728bc53 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentTaskDisplayDriver.cs @@ -5,7 +5,9 @@ namespace OrchardCore.Contents.Workflows.Drivers { - public abstract class ContentTaskDisplayDriver : ActivityDisplayDriver where TActivity : ContentTask where TViewModel : ContentTaskViewModel, new() + public abstract class ContentTaskDisplayDriver : ActivityDisplayDriver + where TActivity : ContentTask + where TViewModel : ContentTaskViewModel, new() { public override IDisplayResult Display(TActivity activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentUnpublishedEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentUnpublishedEventDisplayDriver.cs index ee5e1088864..5bdc3c2b64e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentUnpublishedEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentUnpublishedEventDisplayDriver.cs @@ -6,8 +6,7 @@ namespace OrchardCore.Contents.Workflows.Drivers { public class ContentUnpublishedEventDisplayDriver : ContentEventDisplayDriver { - public ContentUnpublishedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) : base(contentDefinitionManager) - { - } + public ContentUnpublishedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) + : base(contentDefinitionManager) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentUpdatedEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentUpdatedEventDisplayDriver.cs index ffece3aa36c..be8bbe19d74 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentUpdatedEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentUpdatedEventDisplayDriver.cs @@ -6,8 +6,7 @@ namespace OrchardCore.Contents.Workflows.Drivers { public class ContentUpdatedEventDisplayDriver : ContentEventDisplayDriver { - public ContentUpdatedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) : base(contentDefinitionManager) - { - } + public ContentUpdatedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) + : base(contentDefinitionManager) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentVersionedEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentVersionedEventDisplayDriver.cs index 17d1f0f0e2d..67938297eac 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentVersionedEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Drivers/ContentVersionedEventDisplayDriver.cs @@ -6,8 +6,7 @@ namespace OrchardCore.Contents.Workflows.Drivers { public class ContentVersionedEventDisplayDriver : ContentEventDisplayDriver { - public ContentVersionedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) : base(contentDefinitionManager) - { - } + public ContentVersionedEventDisplayDriver(IContentDefinitionManager contentDefinitionManager) + : base(contentDefinitionManager) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Handlers/ContentItemSerializer.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Handlers/ContentItemSerializer.cs index 19088dd534b..b1024564059 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Handlers/ContentItemSerializer.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Handlers/ContentItemSerializer.cs @@ -32,11 +32,7 @@ public Task SerializeValueAsync(SerializeWorkflowValueContext context) { if (context.Input is IContent content) { - context.Output = JObject.FromObject(new - { - Type = "Content", - ContentId = content.ContentItem.ContentItemId - }); + context.Output = JObject.FromObject(new { Type = "Content", ContentId = content.ContentItem.ContentItemId }); } return Task.CompletedTask; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Handlers/ContentsHandler.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Handlers/ContentsHandler.cs index 8b7f8d7e3fb..e1585392e5f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Handlers/ContentsHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Handlers/ContentsHandler.cs @@ -63,11 +63,7 @@ private Task> TriggerWorkflowEventAsync(st ContentItemVersionId = contentItem.ContentItemVersionId, }; - var input = new Dictionary - { - { ContentEventConstants.ContentItemInputKey, contentItem }, - { ContentEventConstants.ContentEventInputKey, contentEvent } - }; + var input = new Dictionary { { ContentEventConstants.ContentItemInputKey, contentItem }, { ContentEventConstants.ContentEventInputKey, contentEvent } }; return _workflowManager.TriggerEventAsync(name, input, correlationId: contentItem.ContentItemId); } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentCreatedEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentCreatedEventViewModel.cs index a956ba1d36a..7e442da2e05 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentCreatedEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentCreatedEventViewModel.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Contents.Workflows.ViewModels { - public class ContentCreatedEventViewModel : ContentEventViewModel - { - } + public class ContentCreatedEventViewModel : ContentEventViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentDeletedEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentDeletedEventViewModel.cs index bbb5f02173d..6205e36544a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentDeletedEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentDeletedEventViewModel.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Contents.Workflows.ViewModels { - public class ContentDeletedEventViewModel : ContentEventViewModel - { - } + public class ContentDeletedEventViewModel : ContentEventViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentDraftSavedEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentDraftSavedEventViewModel.cs index 5dee5e7870e..4a046ac845a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentDraftSavedEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentDraftSavedEventViewModel.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Contents.Workflows.ViewModels { - public class ContentDraftSavedEventViewModel : ContentEventViewModel - { - } + public class ContentDraftSavedEventViewModel : ContentEventViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentEventViewModel.cs index e37774ca6cf..70ef4c2cf53 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentEventViewModel.cs @@ -5,11 +5,10 @@ namespace OrchardCore.Contents.Workflows.ViewModels { - public class ContentEventViewModel : ActivityViewModel where T : ContentEvent + public class ContentEventViewModel : ActivityViewModel + where T : ContentEvent { - public ContentEventViewModel() - { - } + public ContentEventViewModel() { } public ContentEventViewModel(T activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentPublishedEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentPublishedEventViewModel.cs index b3c557c06f6..b817f163648 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentPublishedEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentPublishedEventViewModel.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Contents.Workflows.ViewModels { - public class ContentPublishedEventViewModel : ContentEventViewModel - { - } + public class ContentPublishedEventViewModel : ContentEventViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentTaskViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentTaskViewModel.cs index 747fb4fd6ff..ab80ad8a56b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentTaskViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentTaskViewModel.cs @@ -3,11 +3,10 @@ namespace OrchardCore.Contents.Workflows.ViewModels { - public class ContentTaskViewModel : ActivityViewModel where T : ContentTask + public class ContentTaskViewModel : ActivityViewModel + where T : ContentTask { - public ContentTaskViewModel() - { - } + public ContentTaskViewModel() { } public ContentTaskViewModel(T activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentUnpublishedEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentUnpublishedEventViewModel.cs index cb308a2e45d..cb2f08dd2d4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentUnpublishedEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentUnpublishedEventViewModel.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Contents.Workflows.ViewModels { - public class ContentUnpublishedEventViewModel : ContentEventViewModel - { - } + public class ContentUnpublishedEventViewModel : ContentEventViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentUpdatedEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentUpdatedEventViewModel.cs index 7ddd6c7d325..a38d99d11b0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentUpdatedEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentUpdatedEventViewModel.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Contents.Workflows.ViewModels { - public class ContentUpdatedEventViewModel : ContentEventViewModel - { - } + public class ContentUpdatedEventViewModel : ContentEventViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentVersionedEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentVersionedEventViewModel.cs index 252568de282..c6d39037272 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentVersionedEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Workflows/ViewModels/ContentVersionedEventViewModel.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Contents.Workflows.ViewModels { - public class ContentVersionedEventViewModel : ContentEventViewModel - { - } + public class ContentVersionedEventViewModel : ContentEventViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Cors/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Cors/AdminMenu.cs index 42c87f5c944..d5358337692 100644 --- a/src/OrchardCore.Modules/OrchardCore.Cors/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Cors/AdminMenu.cs @@ -20,18 +20,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["CORS"], S["CORS"].PrefixPosition(), entry => entry - .AddClass("cors") - .Id("cors") - .Action("Index", "Admin", "OrchardCore.Cors") - .Permission(Permissions.ManageCorsSettings) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["CORS"], + S["CORS"].PrefixPosition(), + entry => entry.AddClass("cors").Id("cors").Action("Index", "Admin", "OrchardCore.Cors").Permission(Permissions.ManageCorsSettings).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Cors/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Cors/Controllers/AdminController.cs index 629ee0e7d6d..4711937a9bb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Cors/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Cors/Controllers/AdminController.cs @@ -31,7 +31,7 @@ public AdminController( CorsService corsService, INotifier notifier, IHtmlLocalizer htmlLocalizer - ) + ) { _shellHost = shellHost; _shellSettings = shellSettings; @@ -75,10 +75,7 @@ public async Task Index() } } - var viewModel = new CorsSettingsViewModel - { - Policies = list.ToArray() - }; + var viewModel = new CorsSettingsViewModel { Policies = list.ToArray() }; return View(viewModel); } @@ -103,28 +100,27 @@ public async Task IndexPOST() foreach (var settingViewModel in model.Policies) { - corsPolicies.Add(new CorsPolicySetting - { - Name = settingViewModel.Name, - AllowAnyHeader = settingViewModel.AllowAnyHeader, - AllowAnyMethod = settingViewModel.AllowAnyMethod, - AllowAnyOrigin = settingViewModel.AllowAnyOrigin, - AllowCredentials = settingViewModel.AllowCredentials, - AllowedHeaders = settingViewModel.AllowedHeaders, - AllowedMethods = settingViewModel.AllowedMethods, - AllowedOrigins = settingViewModel.AllowedOrigins, - IsDefaultPolicy = settingViewModel.IsDefaultPolicy - }); - + corsPolicies.Add( + new CorsPolicySetting + { + Name = settingViewModel.Name, + AllowAnyHeader = settingViewModel.AllowAnyHeader, + AllowAnyMethod = settingViewModel.AllowAnyMethod, + AllowAnyOrigin = settingViewModel.AllowAnyOrigin, + AllowCredentials = settingViewModel.AllowCredentials, + AllowedHeaders = settingViewModel.AllowedHeaders, + AllowedMethods = settingViewModel.AllowedMethods, + AllowedOrigins = settingViewModel.AllowedOrigins, + IsDefaultPolicy = settingViewModel.IsDefaultPolicy + } + ); + if (settingViewModel.AllowAnyOrigin && settingViewModel.AllowCredentials) { policyWarnings.Add(settingViewModel.Name); } } - var corsSettings = new CorsSettings() - { - Policies = corsPolicies - }; + var corsSettings = new CorsSettings() { Policies = corsPolicies }; await _corsService.UpdateSettingsAsync(corsSettings); @@ -134,7 +130,14 @@ public async Task IndexPOST() if (policyWarnings.Count > 0) { - await _notifier.WarningAsync(H["Specifying {0} and {1} is an insecure configuration and can result in cross-site request forgery. The CORS service returns an invalid CORS response when an app is configured with both methods.
Affected policies: {2}
Refer to docs:https://learn.microsoft.com/en-us/aspnet/core/security/cors", "AllowAnyOrigin", "AllowCredentias", string.Join(", ", policyWarnings) ]); + await _notifier.WarningAsync( + H[ + "Specifying {0} and {1} is an insecure configuration and can result in cross-site request forgery. The CORS service returns an invalid CORS response when an app is configured with both methods.
Affected policies: {2}
Refer to docs:https://learn.microsoft.com/en-us/aspnet/core/security/cors", + "AllowAnyOrigin", + "AllowCredentias", + string.Join(", ", policyWarnings) + ] + ); } return View(model); diff --git a/src/OrchardCore.Modules/OrchardCore.Cors/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Cors/Manifest.cs index 4b9396bd77a..40c09e4834c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Cors/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Cors/Manifest.cs @@ -6,4 +6,5 @@ Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion, Description = "Enables configuration of CORS settings.", - Category = "Security")] + Category = "Security" +)] diff --git a/src/OrchardCore.Modules/OrchardCore.Cors/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Cors/Permissions.cs index b95ed88605b..4e70ca3f5a0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Cors/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Cors/Permissions.cs @@ -8,21 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageCorsSettings = new("ManageCorsSettings", "Managing Cors Settings", isSecurityCritical: true); + private readonly IEnumerable _allPermissions = [ManageCorsSettings,]; - private readonly IEnumerable _allPermissions = - [ - ManageCorsSettings, - ]; + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); - - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Cors/Services/CorsOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Cors/Services/CorsOptionsConfiguration.cs index 73979cd1367..715a2e3b47c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Cors/Services/CorsOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Cors/Services/CorsOptionsConfiguration.cs @@ -28,48 +28,54 @@ public void Configure(CorsOptions options) { if (corsPolicy.AllowCredentials && corsPolicy.AllowAnyOrigin) { - _logger.LogWarning("Using AllowCredentials and AllowAnyOrigin at the same time is considered a security risk, the {PolicyName} policy will not be loaded.", corsPolicy.Name); + _logger.LogWarning( + "Using AllowCredentials and AllowAnyOrigin at the same time is considered a security risk, the {PolicyName} policy will not be loaded.", + corsPolicy.Name + ); continue; } - options.AddPolicy(corsPolicy.Name, configurePolicy => - { - if (corsPolicy.AllowAnyHeader) - { - configurePolicy.AllowAnyHeader(); - } - else + options.AddPolicy( + corsPolicy.Name, + configurePolicy => { - configurePolicy.WithHeaders(corsPolicy.AllowedHeaders); - } + if (corsPolicy.AllowAnyHeader) + { + configurePolicy.AllowAnyHeader(); + } + else + { + configurePolicy.WithHeaders(corsPolicy.AllowedHeaders); + } - if (corsPolicy.AllowAnyMethod) - { - configurePolicy.AllowAnyMethod(); - } - else - { - configurePolicy.WithMethods(corsPolicy.AllowedMethods); - } + if (corsPolicy.AllowAnyMethod) + { + configurePolicy.AllowAnyMethod(); + } + else + { + configurePolicy.WithMethods(corsPolicy.AllowedMethods); + } - if (corsPolicy.AllowAnyOrigin) - { - configurePolicy.AllowAnyOrigin(); - } - else - { - configurePolicy.WithOrigins(corsPolicy.AllowedOrigins); - } + if (corsPolicy.AllowAnyOrigin) + { + configurePolicy.AllowAnyOrigin(); + } + else + { + configurePolicy.WithOrigins(corsPolicy.AllowedOrigins); + } - if (corsPolicy.AllowCredentials) - { - configurePolicy.AllowCredentials(); - } - else - { - configurePolicy.DisallowCredentials(); + if (corsPolicy.AllowCredentials) + { + configurePolicy.AllowCredentials(); + } + else + { + configurePolicy.DisallowCredentials(); + } } - }); + ); if (corsPolicy.IsDefaultPolicy) { diff --git a/src/OrchardCore.Modules/OrchardCore.Cors/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Cors/Startup.cs index 43d74afe38a..98b262aa0bf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Cors/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Cors/Startup.cs @@ -1,3 +1,4 @@ +using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.Routing; @@ -8,7 +9,6 @@ using OrchardCore.Modules; using OrchardCore.Navigation; using OrchardCore.Security.Permissions; -using System; using CorsService = OrchardCore.Cors.Services.CorsService; namespace OrchardCore.Cors @@ -28,8 +28,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddSingleton(); - services.TryAddEnumerable(ServiceDescriptor - .Transient, CorsOptionsConfiguration>()); + services.TryAddEnumerable(ServiceDescriptor.Transient, CorsOptionsConfiguration>()); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.CustomSettings/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.CustomSettings/AdminMenu.cs index beff6af04e2..5dadbc0a8bb 100644 --- a/src/OrchardCore.Modules/OrchardCore.CustomSettings/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.CustomSettings/AdminMenu.cs @@ -14,9 +14,7 @@ public class AdminMenu : INavigationProvider protected readonly IStringLocalizer S; private static readonly ConcurrentDictionary _routeValues = []; - public AdminMenu( - IStringLocalizer localizer, - CustomSettingsService customSettingsService) + public AdminMenu(IStringLocalizer localizer, CustomSettingsService customSettingsService) { S = localizer; _customSettingsService = customSettingsService; @@ -33,30 +31,33 @@ public async Task BuildNavigationAsync(string name, NavigationBuilder builder) { if (!_routeValues.TryGetValue(type.Name, out var routeValues)) { - routeValues = new RouteValueDictionary() - { - { "area", "OrchardCore.Settings" }, - { "groupId", type.Name }, - }; + routeValues = new RouteValueDictionary() { { "area", "OrchardCore.Settings" }, { "groupId", type.Name }, }; _routeValues[type.Name] = routeValues; } var htmlName = type.Name.HtmlClassify(); - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(new LocalizedString(type.DisplayName, type.DisplayName), type.DisplayName.PrefixPosition(), layers => layers - .Action("Index", "Admin", routeValues) - .AddClass(htmlName) - .Id(htmlName) - .Permission(Permissions.CreatePermissionForType(type)) - .Resource(type.Name) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + new LocalizedString(type.DisplayName, type.DisplayName), + type.DisplayName.PrefixPosition(), + layers => + layers + .Action("Index", "Admin", routeValues) + .AddClass(htmlName) + .Id(htmlName) + .Permission(Permissions.CreatePermissionForType(type)) + .Resource(type.Name) + .LocalNav() + ) ) - ); + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.CustomSettings/Deployment/CustomSettingsDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.CustomSettings/Deployment/CustomSettingsDeploymentSource.cs index 73382cf61d8..b67b764dfa1 100644 --- a/src/OrchardCore.Modules/OrchardCore.CustomSettings/Deployment/CustomSettingsDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.CustomSettings/Deployment/CustomSettingsDeploymentSource.cs @@ -24,10 +24,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan return; } - var settingsList = new List> - { - new("name", "custom-settings"), - }; + var settingsList = new List> { new("name", "custom-settings"), }; var settingsTypes = customSettingsStep.IncludeAll ? (await _customSettingsService.GetAllSettingsTypesAsync()).ToArray() diff --git a/src/OrchardCore.Modules/OrchardCore.CustomSettings/Deployment/CustomSettingsDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.CustomSettings/Deployment/CustomSettingsDeploymentStepDriver.cs index c7324d080a9..0c357d3ae6a 100644 --- a/src/OrchardCore.Modules/OrchardCore.CustomSettings/Deployment/CustomSettingsDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.CustomSettings/Deployment/CustomSettingsDeploymentStepDriver.cs @@ -20,31 +20,31 @@ public CustomSettingsDeploymentStepDriver(CustomSettingsService customSettingsSe public override IDisplayResult Display(CustomSettingsDeploymentStep step) { - return - Combine( - View("CustomSettingsDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("CustomSettingsDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("CustomSettingsDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("CustomSettingsDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(CustomSettingsDeploymentStep step) { - return Initialize("CustomSettingsDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.SettingsTypeNames = step.SettingsTypeNames; - model.AllSettingsTypeNames = (await _customSettingsService.GetAllSettingsTypeNamesAsync()).ToArray(); - }).Location("Content"); + return Initialize( + "CustomSettingsDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.SettingsTypeNames = step.SettingsTypeNames; + model.AllSettingsTypeNames = (await _customSettingsService.GetAllSettingsTypeNamesAsync()).ToArray(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(CustomSettingsDeploymentStep step, IUpdateModel updater) { step.SettingsTypeNames = []; - await updater.TryUpdateModelAsync(step, - Prefix, - x => x.SettingsTypeNames, - x => x.IncludeAll); + await updater.TryUpdateModelAsync(step, Prefix, x => x.SettingsTypeNames, x => x.IncludeAll); // don't have the selected option if include all if (step.IncludeAll) diff --git a/src/OrchardCore.Modules/OrchardCore.CustomSettings/Drivers/CustomSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.CustomSettings/Drivers/CustomSettingsDisplayDriver.cs index 8abe868dc48..5b1ff0733ed 100644 --- a/src/OrchardCore.Modules/OrchardCore.CustomSettings/Drivers/CustomSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.CustomSettings/Drivers/CustomSettingsDisplayDriver.cs @@ -18,9 +18,7 @@ public class CustomSettingsDisplayDriver : DisplayDriver private readonly CustomSettingsService _customSettingsService; private readonly IContentItemDisplayManager _contentItemDisplayManager; - public CustomSettingsDisplayDriver( - CustomSettingsService customSettingsService, - IContentItemDisplayManager contentItemDisplayManager) + public CustomSettingsDisplayDriver(CustomSettingsService customSettingsService, IContentItemDisplayManager contentItemDisplayManager) { _customSettingsService = customSettingsService; _contentItemDisplayManager = contentItemDisplayManager; @@ -42,10 +40,15 @@ public override async Task EditAsync(ISite site, BuildEditorCont var isNew = false; var contentItem = await _customSettingsService.GetSettingsAsync(site, contentTypeDefinition, () => isNew = true); - var shape = Initialize(CustomSettingsConstants.Stereotype, async ctx => - { - ctx.Editor = await _contentItemDisplayManager.BuildEditorAsync(contentItem, context.Updater, isNew); - }).Location("Content:3").OnGroup(contentTypeDefinition.Name); + var shape = Initialize( + CustomSettingsConstants.Stereotype, + async ctx => + { + ctx.Editor = await _contentItemDisplayManager.BuildEditorAsync(contentItem, context.Updater, isNew); + } + ) + .Location("Content:3") + .OnGroup(contentTypeDefinition.Name); return shape; } diff --git a/src/OrchardCore.Modules/OrchardCore.CustomSettings/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.CustomSettings/Permissions.cs index 91ba18df9b9..17b38123cbb 100644 --- a/src/OrchardCore.Modules/OrchardCore.CustomSettings/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.CustomSettings/Permissions.cs @@ -29,18 +29,12 @@ public async Task> GetPermissionsAsync() return list; } - public static string CreatePermissionName(string name) - => string.Format(_manageCustomSettings.Name, name); + public static string CreatePermissionName(string name) => string.Format(_manageCustomSettings.Name, name); public static Permission CreatePermissionForType(ContentTypeDefinition type) { - return new Permission( - CreatePermissionName(type.Name), - string.Format(_manageCustomSettings.Description, type.DisplayName), - _manageCustomSettings.ImpliedBy - ); + return new Permission(CreatePermissionName(type.Name), string.Format(_manageCustomSettings.Description, type.DisplayName), _manageCustomSettings.ImpliedBy); } - public IEnumerable GetDefaultStereotypes() - => []; + public IEnumerable GetDefaultStereotypes() => []; } diff --git a/src/OrchardCore.Modules/OrchardCore.CustomSettings/Services/CustomSettingsService.cs b/src/OrchardCore.Modules/OrchardCore.CustomSettings/Services/CustomSettingsService.cs index 6d57abc5c9c..ca326b2c5f1 100644 --- a/src/OrchardCore.Modules/OrchardCore.CustomSettings/Services/CustomSettingsService.cs +++ b/src/OrchardCore.Modules/OrchardCore.CustomSettings/Services/CustomSettingsService.cs @@ -26,7 +26,8 @@ public CustomSettingsService( IContentManager contentManager, IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService, - IContentDefinitionManager contentDefinitionManager) + IContentDefinitionManager contentDefinitionManager + ) { _siteService = siteService; _contentManager = contentManager; @@ -36,11 +37,9 @@ public CustomSettingsService( _settingsTypes = new Lazy>>(async () => await GetContentTypeAsync()); } - public async Task> GetAllSettingsTypeNamesAsync() - => (await _settingsTypes.Value).Keys; + public async Task> GetAllSettingsTypeNamesAsync() => (await _settingsTypes.Value).Keys; - public async Task> GetAllSettingsTypesAsync() - => (await _settingsTypes.Value).Values; + public async Task> GetAllSettingsTypesAsync() => (await _settingsTypes.Value).Values; public async Task> GetSettingsTypesAsync(params string[] settingsTypeNames) { @@ -59,8 +58,7 @@ public async Task> GetSettingsTypesAsync(para return definitions; } - public ContentTypeDefinition GetSettingsType(string settingsTypeName) - => GetSettingsTypeAsync(settingsTypeName).Result; + public ContentTypeDefinition GetSettingsType(string settingsTypeName) => GetSettingsTypeAsync(settingsTypeName).Result; public async Task GetSettingsTypeAsync(string settingsTypeName) { @@ -120,8 +118,7 @@ private async Task> GetContentTypeAsy { var contentTypes = await _contentDefinitionManager.ListTypeDefinitionsAsync(); - var result = contentTypes.Where(x => x.StereotypeEquals(CustomSettingsConstants.Stereotype)) - .ToDictionary(x => x.Name); + var result = contentTypes.Where(x => x.StereotypeEquals(CustomSettingsConstants.Stereotype)).ToDictionary(x => x.Name); return result; } diff --git a/src/OrchardCore.Modules/OrchardCore.DataProtection.Azure/BlobOptionsSetup.cs b/src/OrchardCore.Modules/OrchardCore.DataProtection.Azure/BlobOptionsSetup.cs index 71de539389f..7d0645c99f6 100644 --- a/src/OrchardCore.Modules/OrchardCore.DataProtection.Azure/BlobOptionsSetup.cs +++ b/src/OrchardCore.Modules/OrchardCore.DataProtection.Azure/BlobOptionsSetup.cs @@ -20,11 +20,7 @@ public class BlobOptionsSetup : IAsyncConfigureOptions private readonly ShellSettings _shellSettings; private readonly ILogger _logger; - public BlobOptionsSetup( - IShellConfiguration configuration, - IOptions shellOptions, - ShellSettings shellSettings, - ILogger logger) + public BlobOptionsSetup(IShellConfiguration configuration, IOptions shellOptions, ShellSettings shellSettings, ILogger logger) { _configuration = configuration; _shellOptions = shellOptions.Value; @@ -72,7 +68,10 @@ private async ValueTask ConfigureContainerNameAsync(BlobOptions options) } catch (Exception e) { - _logger.LogCritical(e, "Unable to connect to Azure Storage to configure data protection storage. Ensure that an application setting containing a valid Azure Storage connection string is available at `Modules:OrchardCore.DataProtection.Azure:ConnectionString`."); + _logger.LogCritical( + e, + "Unable to connect to Azure Storage to configure data protection storage. Ensure that an application setting containing a valid Azure Storage connection string is available at `Modules:OrchardCore.DataProtection.Azure:ConnectionString`." + ); throw; } } diff --git a/src/OrchardCore.Modules/OrchardCore.DataProtection.Azure/Startup.cs b/src/OrchardCore.Modules/OrchardCore.DataProtection.Azure/Startup.cs index 084236042b2..55de5b4e708 100644 --- a/src/OrchardCore.Modules/OrchardCore.DataProtection.Azure/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.DataProtection.Azure/Startup.cs @@ -34,15 +34,14 @@ public override void ConfigureServices(IServiceCollection services) .PersistKeysToAzureBlobStorage(sp => { var options = sp.GetRequiredService(); - return new BlobClient( - options.ConnectionString, - options.ContainerName, - options.BlobName); + return new BlobClient(options.ConnectionString, options.ContainerName, options.BlobName); }); } else { - _logger.LogCritical("No connection string was supplied for OrchardCore.DataProtection.Azure. Ensure that an application setting containing a valid Azure Storage connection string is available at `Modules:OrchardCore.DataProtection.Azure:ConnectionString`."); + _logger.LogCritical( + "No connection string was supplied for OrchardCore.DataProtection.Azure. Ensure that an application setting containing a valid Azure Storage connection string is available at `Modules:OrchardCore.DataProtection.Azure:ConnectionString`." + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Demo/AdminMenu.cs index 993f99fe401..7b6de1a9da7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/AdminMenu.cs @@ -20,36 +20,37 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Demo"], "10", demo => demo - .AddClass("demo").Id("demo") - .Add(S["This Menu Item 1"], "0", item => item - .Add(S["This is Menu Item 1.1"], subItem => subItem - .Action("Index", "Admin", "OrchardCore.Demo")) - .Add(S["This is Menu Item 1.2"], subItem => subItem - .Action("Index", "Admin", "OrchardCore.Demo")) - .Add(S["This is Menu Item 1.2"], subItem => subItem - .Action("Index", "Admin", "OrchardCore.Demo")) - ) - .Add(S["This Menu Item 2"], "0", item => item - .Add(S["This is Menu Item 2.1"], subItem => subItem - .Action("Index", "Admin", "OrchardCore.Demo")) - .Add(S["This is Menu Item 2.2"], subItem => subItem - .Action("Index", "Admin", "OrchardCore.Demo")) - .Add(S["This is Menu Item 3.2"], subItem => subItem - .Action("Index", "Admin", "OrchardCore.Demo")) - ) - .Add(S["This Menu Item 3"], "0", item => item - .Add(S["This is Menu Item 3.1"], subItem => subItem - .Action("Index", "Admin", "OrchardCore.Demo")) - .Add(S["This is Menu Item 3.2"], subItem => subItem - .Action("Index", "Admin", "OrchardCore.Demo")) - - ) - .Add(S["Todo (Liquid - Frontend)"], "0", item => item - .Action("Index", "Todo", "OrchardCore.Demo") - ) - ); + builder.Add( + S["Demo"], + "10", + demo => + demo.AddClass("demo") + .Id("demo") + .Add( + S["This Menu Item 1"], + "0", + item => + item.Add(S["This is Menu Item 1.1"], subItem => subItem.Action("Index", "Admin", "OrchardCore.Demo")) + .Add(S["This is Menu Item 1.2"], subItem => subItem.Action("Index", "Admin", "OrchardCore.Demo")) + .Add(S["This is Menu Item 1.2"], subItem => subItem.Action("Index", "Admin", "OrchardCore.Demo")) + ) + .Add( + S["This Menu Item 2"], + "0", + item => + item.Add(S["This is Menu Item 2.1"], subItem => subItem.Action("Index", "Admin", "OrchardCore.Demo")) + .Add(S["This is Menu Item 2.2"], subItem => subItem.Action("Index", "Admin", "OrchardCore.Demo")) + .Add(S["This is Menu Item 3.2"], subItem => subItem.Action("Index", "Admin", "OrchardCore.Demo")) + ) + .Add( + S["This Menu Item 3"], + "0", + item => + item.Add(S["This is Menu Item 3.1"], subItem => subItem.Action("Index", "Admin", "OrchardCore.Demo")) + .Add(S["This is Menu Item 3.2"], subItem => subItem.Action("Index", "Admin", "OrchardCore.Demo")) + ) + .Add(S["Todo (Liquid - Frontend)"], "0", item => item.Action("Index", "Todo", "OrchardCore.Demo")) + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Commands/DemoCommands.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Commands/DemoCommands.cs index d21a3f03584..59c86c8f492 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Commands/DemoCommands.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Commands/DemoCommands.cs @@ -8,8 +8,8 @@ public class DemoCommands : DefaultCommandHandler { private readonly ILogger _logger; - public DemoCommands(ILogger logger, - IStringLocalizer localizer) : base(localizer) + public DemoCommands(ILogger logger, IStringLocalizer localizer) + : base(localizer) { _logger = logger; } diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/ContentElementDisplays/TestContentElementDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Demo/ContentElementDisplays/TestContentElementDisplayDriver.cs index 0f2e1c7164b..04d2a9e1d4e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/ContentElementDisplays/TestContentElementDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/ContentElementDisplays/TestContentElementDisplayDriver.cs @@ -28,23 +28,26 @@ public override IDisplayResult Display(ContentItem contentItem, IUpdateModel upd // New shape, no initialization, custom location Dynamic("LowerDoll").Location("Detail", "Footer"), // New shape - Factory("TestContentPartA", - async ctx => (await ctx.New.TestContentPartA()).Creating(_creating++), - shape => - { - ((dynamic)shape).Processing = _processing++; - return Task.CompletedTask; - }) + Factory( + "TestContentPartA", + async ctx => (await ctx.New.TestContentPartA()).Creating(_creating++), + shape => + { + ((dynamic)shape).Processing = _processing++; + return Task.CompletedTask; + } + ) .Location("Detail", "Content") .Cache("lowerdoll2", cache => cache.WithExpiryAfter(TimeSpan.FromSeconds(5))), // A strongly typed shape model is used and initialized when rendered - Initialize(shape => { shape.Line = "Strongly typed shape"; }) + Initialize(shape => + { + shape.Line = "Strongly typed shape"; + }) .Location("Detail", "Content:2"), // Cached shape - Dynamic("LowerDoll") - .Location("Detail", "/Footer") - .Cache("lowerdoll", cache => cache.WithExpiryAfter(TimeSpan.FromSeconds(5))) - ); + Dynamic("LowerDoll").Location("Detail", "/Footer").Cache("lowerdoll", cache => cache.WithExpiryAfter(TimeSpan.FromSeconds(5))) + ); } public override IDisplayResult Edit(ContentItem contentItem, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/ContentController.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/ContentController.cs index d51165bdfb8..2dfe8d4109a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/ContentController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/ContentController.cs @@ -26,7 +26,8 @@ public ContentController( ISession session, IUpdateModelAccessor updateModelAccessor, IAuthorizationService authorizationService, - IHttpContextAccessor httpContextAccessor) + IHttpContextAccessor httpContextAccessor + ) { _contentManager = contentManager; _contentDisplay = contentDisplay; diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/DemoController.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/DemoController.cs index ed9290f6745..75ea7288f7c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/DemoController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/DemoController.cs @@ -10,11 +10,13 @@ public IActionResult Index() { return Content("Index content"); } + [Route("Demo/About")] public IActionResult About() { return Content("About content"); } + [Route("Demo/Contact")] public IActionResult Contact() { diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/HomeController.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/HomeController.cs index 00e2a17fc1b..c0d196ef9f5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/HomeController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/HomeController.cs @@ -30,7 +30,8 @@ public HomeController( ISession session, ILogger logger, ITagCache tagCache, - IContentItemDisplayManager contentDisplay) + IContentItemDisplayManager contentDisplay + ) { _session = session; _testDependency = testDependency; @@ -104,9 +105,7 @@ public async Task DisplayShape(string contentItemId) return NotFound(); } - var shape = Shape - .Foo() - .Line(contentItem.As().Line); + var shape = Shape.Foo().Line(contentItem.As().Line); return View(shape); } diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/TodoController.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/TodoController.cs index 33f7c16652f..4161b444293 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/TodoController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Controllers/TodoController.cs @@ -35,19 +35,14 @@ public async Task Index() public IActionResult Create() { - var viewModel = new TodoViewModel - { - TodoId = _idGenerator.GenerateUniqueId(), - DisplayMode = "Edit", - }; + var viewModel = new TodoViewModel { TodoId = _idGenerator.GenerateUniqueId(), DisplayMode = "Edit", }; return View(nameof(Edit), viewModel); } public async Task Edit(string todoId) { - var model = (await _session.Query().ListAsync()) - .FirstOrDefault(m => m.TodoId == todoId); + var model = (await _session.Query().ListAsync()).FirstOrDefault(m => m.TodoId == todoId); if (model == null) { @@ -71,8 +66,7 @@ public async Task Update(TodoViewModel viewModel, string returnUr { if (ModelState.IsValid) { - var model = (await _session.Query().ListAsync()) - .FirstOrDefault(m => m.TodoId == viewModel.TodoId); + var model = (await _session.Query().ListAsync()).FirstOrDefault(m => m.TodoId == viewModel.TodoId); model ??= new TodoModel() { TodoId = viewModel.TodoId }; @@ -96,8 +90,7 @@ public async Task Update(TodoViewModel viewModel, string returnUr public async Task Delete(string todoId) { - var model = (await _session.Query().ListAsync()) - .FirstOrDefault(m => m.TodoId == todoId); + var model = (await _session.Query().ListAsync()).FirstOrDefault(m => m.TodoId == todoId); if (model == null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Drivers/UserProfileDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Drivers/UserProfileDisplayDriver.cs index 2365a6f0a3f..93de5b0495d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Drivers/UserProfileDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Drivers/UserProfileDisplayDriver.cs @@ -24,14 +24,17 @@ public UserProfileDisplayDriver(IHttpContextAccessor httpContextAccessor, IAutho public override IDisplayResult Edit(UserProfile profile, BuildEditorContext context) { - return Initialize("UserProfile_Edit", model => - { - model.Age = profile.Age; - model.FirstName = profile.FirstName; - model.LastName = profile.LastName; - }) - .Location("Content:2") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, Permissions.ManageOwnUserProfile)); + return Initialize( + "UserProfile_Edit", + model => + { + model.Age = profile.Age; + model.FirstName = profile.FirstName; + model.LastName = profile.LastName; + } + ) + .Location("Content:2") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, Permissions.ManageOwnUserProfile)); } public override async Task UpdateAsync(UserProfile profile, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/GraphQL/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Demo/GraphQL/Startup.cs index 449f6c2a746..da5ed659083 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/GraphQL/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/GraphQL/Startup.cs @@ -14,81 +14,81 @@ public override void ConfigureServices(IServiceCollection services) services.Configure(options => { // Top Level Content Type options - options.ContentTypeOptions = options.ContentTypeOptions.Union(new[] { + options.ContentTypeOptions = options.ContentTypeOptions.Union( + new[] + { new GraphQLContentTypeOption("Blog") { Collapse = false, Hidden = false, - PartOptions = new GraphQLContentPartOption[] { + PartOptions = new GraphQLContentPartOption[] + { // Content Part options attached to Content Type - new("TestContentPartA") - { - Collapse = false, - Hidden = false - }, - new GraphQLContentPartOption - { - Collapse = false, - Hidden = false - } + new("TestContentPartA") { Collapse = false, Hidden = false }, + new GraphQLContentPartOption { Collapse = false, Hidden = false } } } } ); - options.ConfigureContentType("Blog", (typeConfig) => - { - typeConfig.Collapse = false; - typeConfig.Hidden = false; + options.ConfigureContentType( + "Blog", + (typeConfig) => + { + typeConfig.Collapse = false; + typeConfig.Hidden = false; - typeConfig - .ConfigurePart("TestContentPartA", (partConfig) => - { - partConfig.Collapse = false; - partConfig.Hidden = false; - }) - .ConfigurePart((partConfig) => - { - partConfig.Collapse = false; - partConfig.Hidden = false; - }); - }); + typeConfig + .ConfigurePart( + "TestContentPartA", + (partConfig) => + { + partConfig.Collapse = false; + partConfig.Hidden = false; + } + ) + .ConfigurePart( + (partConfig) => + { + partConfig.Collapse = false; + partConfig.Hidden = false; + } + ); + } + ); // Ignore Fields on GraphQL Objects - options.HiddenFields = options.HiddenFields.Union(new[] { - new GraphQLField(typeof(TestQueryObjectType), "lineIgnored"), - new GraphQLField("lineOtherIgnored") - }); + options.HiddenFields = options.HiddenFields.Union( + new[] { new GraphQLField(typeof(TestQueryObjectType), "lineIgnored"), new GraphQLField("lineOtherIgnored") } + ); - options - .IgnoreField(typeof(TestQueryObjectType), "lineIgnored") - .IgnoreField("lineIgnored"); + options.IgnoreField(typeof(TestQueryObjectType), "lineIgnored").IgnoreField("lineIgnored"); // Top level Part Options - options.PartOptions = options.PartOptions.Union(new[] { - new GraphQLContentPartOption("TestContentPartA") - { - Collapse = false, - Hidden = false - }, - new GraphQLContentPartOption + options.PartOptions = options.PartOptions.Union( + new[] { - Collapse = false, - Hidden = false + new GraphQLContentPartOption("TestContentPartA") { Collapse = false, Hidden = false }, + new GraphQLContentPartOption { Collapse = false, Hidden = false } } - }); + ); options - .ConfigurePart("TestContentPartA", (partConfig) => - { - partConfig.Collapse = false; - partConfig.Hidden = false; - }) - .ConfigurePart((partConfig) => - { - partConfig.Collapse = false; - partConfig.Hidden = false; - }); + .ConfigurePart( + "TestContentPartA", + (partConfig) => + { + partConfig.Collapse = false; + partConfig.Hidden = false; + } + ) + .ConfigurePart( + (partConfig) => + { + partConfig.Collapse = false; + partConfig.Hidden = false; + } + ); }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Manifest.cs index 9aa156334b6..732c6c8b9d5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Manifest.cs @@ -7,17 +7,6 @@ Version = ManifestConstants.OrchardCoreVersion )] -[assembly: Feature( - Name = "Orchard Demo", - Id = "OrchardCore.Demo", - Description = "Test", - Category = "Samples", - Dependencies = ["OrchardCore.Users", "OrchardCore.Contents"] -)] +[assembly: Feature(Name = "Orchard Demo", Id = "OrchardCore.Demo", Description = "Test", Category = "Samples", Dependencies = ["OrchardCore.Users", "OrchardCore.Contents"])] -[assembly: Feature( - Id = "OrchardCore.Demo.Foo", - Name = "Orchard Foo Demo", - Description = "Foo feature sample.", - Category = "Samples" -)] +[assembly: Feature(Id = "OrchardCore.Demo.Foo", Name = "Orchard Foo Demo", Description = "Foo feature sample.", Category = "Samples")] diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Migrations.cs index 15aace2e8fa..ad77ba11c66 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Migrations.cs @@ -15,10 +15,7 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterTypeDefinitionAsync("Foo", builder => builder - .WithPart("TestContentPartA") - .WithPart("TestContentPartB") - ); + await _contentDefinitionManager.AlterTypeDefinitionAsync("Foo", builder => builder.WithPart("TestContentPartA").WithPart("TestContentPartB")); return 1; } diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Pages/Foo/Admin/Edit.cshtml.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Pages/Foo/Admin/Edit.cshtml.cs index 0df7687364c..e16a1900d3f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Pages/Foo/Admin/Edit.cshtml.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Pages/Foo/Admin/Edit.cshtml.cs @@ -18,11 +18,7 @@ public class EditModel : PageModel private readonly IUpdateModelAccessor _updateModelAccessor; private readonly ISession _session; - public EditModel( - IContentManager contentManager, - IContentItemDisplayManager contentDisplay, - IUpdateModelAccessor updateModelAccessor, - ISession session) + public EditModel(IContentManager contentManager, IContentItemDisplayManager contentDisplay, IUpdateModelAccessor updateModelAccessor, ISession session) { _contentManager = contentManager; _contentDisplay = contentDisplay; diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Pages/Foo/List.cshtml.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Pages/Foo/List.cshtml.cs index f0ea70635d6..bf2f72ef309 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Pages/Foo/List.cshtml.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Pages/Foo/List.cshtml.cs @@ -26,11 +26,7 @@ public class ListModel : PageModel [BindProperty] public string Text { get; set; } - public ListModel( - IContentManager contentManager, - IContentItemDisplayManager contentDisplay, - IUpdateModelAccessor updateModelAccessor, - ISession session) + public ListModel(IContentManager contentManager, IContentItemDisplayManager contentDisplay, IUpdateModelAccessor updateModelAccessor, ISession session) { _contentManager = contentManager; _contentDisplay = contentDisplay; @@ -40,8 +36,7 @@ public ListModel( public async Task OnGetAsync(string _) { - var query = _session.Query() - .With(x => x.ContentType == "Foo" && x.Published); + var query = _session.Query().With(x => x.ContentType == "Foo" && x.Published); var contentItems = await query.ListAsync(); var updater = _updateModelAccessor.ModelUpdater; diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Permissions.cs index ca32b869b2a..28a53909f12 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Permissions.cs @@ -10,49 +10,18 @@ public class Permissions : IPermissionProvider public static readonly Permission DemoAPIAccess = new("DemoAPIAccess", "Access to Demo API "); public static readonly Permission ManageOwnUserProfile = new("ManageOwnUserProfile", "Manage own user profile", new Permission[] { CommonPermissions.ManageUsers }); - private static readonly IEnumerable _allPermissions = - [ - DemoAPIAccess, - ManageOwnUserProfile, - ]; + private static readonly IEnumerable _allPermissions = [DemoAPIAccess, ManageOwnUserProfile,]; - private readonly IEnumerable _generalPermissions = - [ - ManageOwnUserProfile, - ]; + private readonly IEnumerable _generalPermissions = [ManageOwnUserProfile,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Authenticated", - Permissions = - [ - DemoAPIAccess, - ], - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Moderator", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Contributor", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Author", - Permissions = _generalPermissions, - }, - ]; + [ + new PermissionStereotype { Name = "Authenticated", Permissions = [DemoAPIAccess,], }, + new PermissionStereotype { Name = "Editor", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Moderator", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Contributor", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Author", Permissions = _generalPermissions, }, + ]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Services/TestDependency.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Services/TestDependency.cs index 0bb8408a71f..b4ad7788423 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Services/TestDependency.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Services/TestDependency.cs @@ -10,6 +10,7 @@ public interface ITestDependency public class ClassFoo : ITestDependency { private readonly ShellSettings _shellSettings; + public ClassFoo(ShellSettings shellSettings) { _shellSettings = shellSettings; diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Shapes/DemoShapeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Shapes/DemoShapeProvider.cs index 9604d50603a..62109d66e9f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Shapes/DemoShapeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Shapes/DemoShapeProvider.cs @@ -8,10 +8,7 @@ public class DemoShapeProvider : ShapeTableProvider, IShapeAttributeProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("Foo") - .OnDisplaying(displaying => - displaying.ChildContent = new HtmlString("

Hi

") - ); + builder.Describe("Foo").OnDisplaying(displaying => displaying.ChildContent = new HtmlString("

Hi

")); return ValueTask.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Startup.cs index 2e00a116558..84f3f0b64b7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Startup.cs @@ -41,12 +41,7 @@ public Startup(IOptions adminOptions) public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { - routes.MapAreaControllerRoute( - name: "Demo.Home.Index", - areaName: "OrchardCore.Demo", - pattern: "Home/Index", - defaults: new { controller = "Home", action = "Index" } - ); + routes.MapAreaControllerRoute(name: "Demo.Home.Index", areaName: "OrchardCore.Demo", pattern: "Home/Index", defaults: new { controller = "Home", action = "Index" }); routes.MapAreaControllerRoute( name: "Demo.Home.Display", diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/ViewModels/TodoViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Demo/ViewModels/TodoViewModel.cs index 32d71c7eb93..3c6f0e56a15 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/ViewModels/TodoViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/ViewModels/TodoViewModel.cs @@ -7,9 +7,7 @@ namespace OrchardCore.Demo.ViewModels public class TodoViewModel : ShapeViewModel { public TodoViewModel() - : base("Todo") - { - } + : base("Todo") { } public string TodoId { get; set; } @@ -23,10 +21,7 @@ public TodoViewModel() public string DisplayMode { - get - { - return Metadata.DisplayType; - } + get { return Metadata.DisplayType; } set { var alternate = $"Todo_{value}"; diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/AdminMenu.cs index 2d2b9cce254..763a1457e6c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/AdminMenu.cs @@ -20,21 +20,25 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Import/Export"], import => import - .Add(S["Remote Instances"], S["Remote Instances"].PrefixPosition(), remote => remote - .Action("Index", "RemoteInstance", "OrchardCore.Deployment.Remote") - .Permission(Permissions.ManageRemoteInstances) - .LocalNav() - ) - .Add(S["Remote Clients"], S["Remote Clients"].PrefixPosition(), remote => remote - .Action("Index", "RemoteClient", "OrchardCore.Deployment.Remote") - .Permission(Permissions.ManageRemoteClients) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Import/Export"], + import => + import + .Add( + S["Remote Instances"], + S["Remote Instances"].PrefixPosition(), + remote => remote.Action("Index", "RemoteInstance", "OrchardCore.Deployment.Remote").Permission(Permissions.ManageRemoteInstances).LocalNav() + ) + .Add( + S["Remote Clients"], + S["Remote Clients"].PrefixPosition(), + remote => remote.Action("Index", "RemoteClient", "OrchardCore.Deployment.Remote").Permission(Permissions.ManageRemoteClients).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/ExportRemoteInstanceController.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/ExportRemoteInstanceController.cs index 750c2912e1c..620da9745cb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/ExportRemoteInstanceController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/ExportRemoteInstanceController.cs @@ -35,7 +35,8 @@ public ExportRemoteInstanceController( IDeploymentManager deploymentManager, INotifier notifier, IHttpClientFactory httpClientFactory, - IHtmlLocalizer localizer) + IHtmlLocalizer localizer + ) { _authorizationService = authorizationService; _deploymentManager = deploymentManager; @@ -92,11 +93,13 @@ public async Task Execute(long id, string remoteInstanceId, strin { using (var requestContent = new MultipartFormDataContent()) { - requestContent.Add(new StreamContent( - new FileStream(archiveFileName, - FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1, FileOptions.Asynchronous | FileOptions.SequentialScan) - ), - nameof(ImportViewModel.Content), Path.GetFileName(archiveFileName)); + requestContent.Add( + new StreamContent( + new FileStream(archiveFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1, FileOptions.Asynchronous | FileOptions.SequentialScan) + ), + nameof(ImportViewModel.Content), + Path.GetFileName(archiveFileName) + ); requestContent.Add(new StringContent(remoteInstance.ClientName), nameof(ImportViewModel.ClientName)); requestContent.Add(new StringContent(remoteInstance.ApiKey), nameof(ImportViewModel.ApiKey)); @@ -111,7 +114,9 @@ public async Task Execute(long id, string remoteInstanceId, strin } else { - await _notifier.ErrorAsync(H["An error occurred while sending the deployment to the remote instance: \"{0} ({1})\"", response.ReasonPhrase, (int)response.StatusCode]); + await _notifier.ErrorAsync( + H["An error occurred while sending the deployment to the remote instance: \"{0} ({1})\"", response.ReasonPhrase, (int)response.StatusCode] + ); } } finally diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/ImportRemoteInstanceController.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/ImportRemoteInstanceController.cs index f042dc4f3ff..8b1c6e80bac 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/ImportRemoteInstanceController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/ImportRemoteInstanceController.cs @@ -19,10 +19,7 @@ public class ImportRemoteInstanceController : Controller private readonly IDeploymentManager _deploymentManager; private readonly IDataProtector _dataProtector; - public ImportRemoteInstanceController( - IDataProtectionProvider dataProtectionProvider, - RemoteClientService remoteClientService, - IDeploymentManager deploymentManager) + public ImportRemoteInstanceController(IDataProtectionProvider dataProtectionProvider, RemoteClientService remoteClientService, IDeploymentManager deploymentManager) { _deploymentManager = deploymentManager; _remoteClientService = remoteClientService; diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteClientController.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteClientController.cs index 98893f63274..6145e489a6f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteClientController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteClientController.cs @@ -45,7 +45,7 @@ public RemoteClientController( IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer, INotifier notifier - ) + ) { _authorizationService = authorizationService; _pagerOptions = pagerOptions.Value; @@ -95,21 +95,15 @@ public async Task Index(ContentOptions options, PagerParameters p Options = options }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(RemoteClientIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(RemoteClientIndexViewModel model) => + RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Create() { diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteInstanceController.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteInstanceController.cs index 4009ae9dfdf..cec43f78bba 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteInstanceController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteInstanceController.cs @@ -41,7 +41,7 @@ public RemoteInstanceController( IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer, INotifier notifier - ) + ) { _authorizationService = authorizationService; _pagerOptions = pagerOptions.Value; @@ -88,21 +88,15 @@ public async Task Index(ContentOptions options, PagerParameters p Options = options }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(RemoteInstanceIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(RemoteInstanceIndexViewModel model) => + RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Create() { diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Permissions.cs index 21e25dc13bc..eb47395876d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Permissions.cs @@ -10,22 +10,9 @@ public class Permissions : IPermissionProvider public static readonly Permission ManageRemoteClients = new("ManageRemoteClients", "Manage remote clients"); public static readonly Permission Export = new("ExportRemoteInstances", "Export to remote instances"); - private readonly IEnumerable _allPermissions = - [ - ManageRemoteInstances, - ManageRemoteClients, - Export, - ]; + private readonly IEnumerable _allPermissions = [ManageRemoteInstances, ManageRemoteClients, Export,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteClientService.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteClientService.cs index a3ecfc562f0..3c7e075a7de 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteClientService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteClientService.cs @@ -15,10 +15,7 @@ public class RemoteClientService private RemoteClientList _remoteClientList; - public RemoteClientService( - ISession session, - IDataProtectionProvider dataProtectionProvider - ) + public RemoteClientService(ISession session, IDataProtectionProvider dataProtectionProvider) { _dataProtector = dataProtectionProvider.CreateProtector("OrchardCore.Deployment").ToTimeLimitedDataProtector(); _session = session; diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteInstanceDeploymentTargetProvider.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteInstanceDeploymentTargetProvider.cs index 24d5d0bd9b9..a4e661203b3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteInstanceDeploymentTargetProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteInstanceDeploymentTargetProvider.cs @@ -12,9 +12,7 @@ public class RemoteInstanceDeploymentTargetProvider : IDeploymentTargetProvider private readonly RemoteInstanceService _service; protected readonly IStringLocalizer S; - public RemoteInstanceDeploymentTargetProvider( - IStringLocalizer stringLocalizer, - RemoteInstanceService service) + public RemoteInstanceDeploymentTargetProvider(IStringLocalizer stringLocalizer, RemoteInstanceService service) { _service = service; S = stringLocalizer; @@ -24,19 +22,21 @@ public async Task> GetDeploymentTargetsAsync() { var remoteInstanceList = await _service.GetRemoteInstanceListAsync(); - return remoteInstanceList.RemoteInstances.Select(x => - new DeploymentTarget( - name: new LocalizedString(x.Name, x.Name, false), - description: S["Sends the deployment plan to a remote instance."], - route: new RouteValueDictionary(new + return remoteInstanceList + .RemoteInstances.Select(x => new DeploymentTarget( + name: new LocalizedString(x.Name, x.Name, false), + description: S["Sends the deployment plan to a remote instance."], + route: new RouteValueDictionary( + new { area = "OrchardCore.Deployment.Remote", controller = "ExportRemoteInstance", action = "Execute", remoteInstanceId = x.Id - }) + } ) - ).ToArray(); + )) + .ToArray(); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteInstanceService.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteInstanceService.cs index d81c968dd18..3efafac9aa9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteInstanceService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Services/RemoteInstanceService.cs @@ -50,14 +50,16 @@ public async Task CreateRemoteInstanceAsync(string name, string url, string clie { var remoteInstanceList = await LoadRemoteInstanceListAsync(); - remoteInstanceList.RemoteInstances.Add(new RemoteInstance - { - Id = Guid.NewGuid().ToString("n"), - Name = name, - Url = url, - ClientName = clientName, - ApiKey = apiKey, - }); + remoteInstanceList.RemoteInstances.Add( + new RemoteInstance + { + Id = Guid.NewGuid().ToString("n"), + Name = name, + Url = url, + ClientName = clientName, + ApiKey = apiKey, + } + ); await _documentManager.UpdateAsync(remoteInstanceList); } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/AdminMenu.cs index 0fec8dc7bf5..ff135fd801a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/AdminMenu.cs @@ -20,26 +20,31 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Import/Export"], S["Import/Export"].PrefixPosition(), import => import - .Add(S["Deployment Plans"], S["Deployment Plans"].PrefixPosition(), deployment => deployment - .Action("Index", "DeploymentPlan", "OrchardCore.Deployment") - .Permission(Permissions.Export) - .LocalNav() - ) - .Add(S["Package Import"], S["Package Import"].PrefixPosition(), deployment => deployment - .Action("Index", "Import", "OrchardCore.Deployment") - .Permission(Permissions.Import) - .LocalNav() - ) - .Add(S["JSON Import"], S["JSON Import"].PrefixPosition(), deployment => deployment - .Action("Json", "Import", "OrchardCore.Deployment") - .Permission(Permissions.Import) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Import/Export"], + S["Import/Export"].PrefixPosition(), + import => + import + .Add( + S["Deployment Plans"], + S["Deployment Plans"].PrefixPosition(), + deployment => deployment.Action("Index", "DeploymentPlan", "OrchardCore.Deployment").Permission(Permissions.Export).LocalNav() + ) + .Add( + S["Package Import"], + S["Package Import"].PrefixPosition(), + deployment => deployment.Action("Index", "Import", "OrchardCore.Deployment").Permission(Permissions.Import).LocalNav() + ) + .Add( + S["JSON Import"], + S["JSON Import"].PrefixPosition(), + deployment => deployment.Action("Json", "Import", "OrchardCore.Deployment").Permission(Permissions.Import).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/DeploymentPlanController.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/DeploymentPlanController.cs index 8aac781a8a8..435d72dfa74 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/DeploymentPlanController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/DeploymentPlanController.cs @@ -49,7 +49,8 @@ public DeploymentPlanController( IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer, INotifier notifier, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _displayManager = displayManager; _factories = factories; @@ -86,11 +87,7 @@ public async Task Index(ContentOptions options, PagerParameters p var count = await deploymentPlans.CountAsync(); - var results = await deploymentPlans - .OrderBy(p => p.Name) - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize) - .ListAsync(); + var results = await deploymentPlans.OrderBy(p => p.Name).Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -109,21 +106,15 @@ public async Task Index(ContentOptions options, PagerParameters p Pager = pagerShape }; - model.Options.DeploymentPlansBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Delete)), - ]; + model.Options.DeploymentPlansBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Delete)),]; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(DeploymentPlanIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(DeploymentPlanIndexViewModel model) => + RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.BulkAction")] @@ -258,11 +249,7 @@ public async Task Edit(long id) return NotFound(); } - var model = new EditDeploymentPlanViewModel - { - Id = deploymentPlan.Id, - Name = deploymentPlan.Name - }; + var model = new EditDeploymentPlanViewModel { Id = deploymentPlan.Id, Name = deploymentPlan.Name }; return View(model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/ExportFileController.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/ExportFileController.cs index 42dabf53c9a..76a01d6b6b0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/ExportFileController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/ExportFileController.cs @@ -22,10 +22,7 @@ public class ExportFileController : Controller private readonly IAuthorizationService _authorizationService; private readonly ISession _session; - public ExportFileController( - IAuthorizationService authorizationService, - ISession session, - IDeploymentManager deploymentManager) + public ExportFileController(IAuthorizationService authorizationService, ISession session, IDeploymentManager deploymentManager) { _authorizationService = authorizationService; _deploymentManager = deploymentManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/StepController.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/StepController.cs index ff2167b0e73..e2487e26201 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/StepController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Controllers/StepController.cs @@ -33,7 +33,8 @@ public StepController( ISession session, IHtmlLocalizer htmlLocalizer, INotifier notifier, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _displayManager = displayManager; _factories = factories; diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Deployment/DeploymentPlanDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Deployment/DeploymentPlanDeploymentSource.cs index f122b92eded..73561848d64 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Deployment/DeploymentPlanDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Deployment/DeploymentPlanDeploymentSource.cs @@ -10,9 +10,7 @@ public class DeploymentPlanDeploymentSource : IDeploymentSource private readonly IDeploymentPlanService _deploymentPlanService; private readonly IEnumerable _deploymentStepFactories; - public DeploymentPlanDeploymentSource( - IDeploymentPlanService deploymentPlanService, - IEnumerable deploymentStepFactories) + public DeploymentPlanDeploymentSource(IDeploymentPlanService deploymentPlanService, IEnumerable deploymentStepFactories) { _deploymentPlanService = deploymentPlanService; _deploymentStepFactories = deploymentStepFactories; @@ -36,24 +34,13 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep deploymentStep, Depl ? (await _deploymentPlanService.GetAllDeploymentPlansAsync()).ToArray() : (await _deploymentPlanService.GetDeploymentPlansAsync(deploymentPlanStep.DeploymentPlanNames)).ToArray(); - var plans = (from plan in deploymentPlans - select new - { - plan.Name, - Steps = (from step in plan.DeploymentSteps - select new - { - Type = GetStepType(deploymentStepFactories, step), - Step = step - }).ToArray(), - }).ToArray(); + var plans = ( + from plan in deploymentPlans + select new { plan.Name, Steps = (from step in plan.DeploymentSteps select new { Type = GetStepType(deploymentStepFactories, step), Step = step }).ToArray(), } + ).ToArray(); // Adding deployment plans. - result.Steps.Add(new JsonObject - { - ["name"] = "deployment", - ["Plans"] = JArray.FromObject(plans), - }); + result.Steps.Add(new JsonObject { ["name"] = "deployment", ["Plans"] = JArray.FromObject(plans), }); } /// diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Deployment/DeploymentPlanDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Deployment/DeploymentPlanDeploymentStepDriver.cs index ed1c16a1ab0..8af37edcc74 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Deployment/DeploymentPlanDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Deployment/DeploymentPlanDeploymentStepDriver.cs @@ -18,31 +18,31 @@ public DeploymentPlanDeploymentStepDriver(IDeploymentPlanService deploymentPlanS public override IDisplayResult Display(DeploymentPlanDeploymentStep step) { - return - Combine( - View("DeploymentPlanDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("DeploymentPlanDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("DeploymentPlanDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("DeploymentPlanDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(DeploymentPlanDeploymentStep step) { - return Initialize("DeploymentPlanDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.DeploymentPlanNames = step.DeploymentPlanNames; - model.AllDeploymentPlanNames = (await _deploymentPlanService.GetAllDeploymentPlanNamesAsync()).ToArray(); - }).Location("Content"); + return Initialize( + "DeploymentPlanDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.DeploymentPlanNames = step.DeploymentPlanNames; + model.AllDeploymentPlanNames = (await _deploymentPlanService.GetAllDeploymentPlanNamesAsync()).ToArray(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(DeploymentPlanDeploymentStep step, IUpdateModel updater) { step.DeploymentPlanNames = []; - await updater.TryUpdateModelAsync(step, - Prefix, - x => x.DeploymentPlanNames, - x => x.IncludeAll); + await updater.TryUpdateModelAsync(step, Prefix, x => x.DeploymentPlanNames, x => x.IncludeAll); // don't have the selected option if include all if (step.IncludeAll) diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/DeploymentPlanService.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/DeploymentPlanService.cs index bd79c533b3b..8472ead3f53 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/DeploymentPlanService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/DeploymentPlanService.cs @@ -17,10 +17,7 @@ public class DeploymentPlanService : IDeploymentPlanService private readonly IAuthorizationService _authorizationService; private Dictionary _deploymentPlans; - public DeploymentPlanService( - YesSql.ISession session, - IHttpContextAccessor httpContextAccessor, - IAuthorizationService authorizationService) + public DeploymentPlanService(YesSql.ISession session, IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService) { _session = session; _httpContextAccessor = httpContextAccessor; @@ -43,8 +40,7 @@ public async Task DoesUserHavePermissionsAsync() { var user = _httpContextAccessor.HttpContext.User; - var result = await _authorizationService.AuthorizeAsync(user, Permissions.ManageDeploymentPlan) && - await _authorizationService.AuthorizeAsync(user, Permissions.Export); + var result = await _authorizationService.AuthorizeAsync(user, Permissions.ManageDeploymentPlan) && await _authorizationService.AuthorizeAsync(user, Permissions.Export); return result; } @@ -94,9 +90,10 @@ public async Task CreateOrUpdateDeploymentPlansAsync(IEnumerable { var names = deploymentPlans.Select(x => x.Name); - var existingDeploymentPlans = (await _session.Query(x => x.Name.IsIn(names)) - .ListAsync()) - .ToDictionary(x => x.Name, StringComparer.OrdinalIgnoreCase); + var existingDeploymentPlans = (await _session.Query(x => x.Name.IsIn(names)).ListAsync()).ToDictionary( + x => x.Name, + StringComparer.OrdinalIgnoreCase + ); foreach (var deploymentPlan in deploymentPlans) { diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Indexes/DeploymentPlanIndex.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Indexes/DeploymentPlanIndex.cs index a9b1834981e..ec6bde45ae0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Indexes/DeploymentPlanIndex.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Indexes/DeploymentPlanIndex.cs @@ -13,13 +13,11 @@ public class DeploymentPlanIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(deploymentPlan => { - return new DeploymentPlanIndex - { - Name = deploymentPlan.Name - }; + return new DeploymentPlanIndex { Name = deploymentPlan.Name }; }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Migrations.cs index 7e3315b5524..eba21e77742 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Migrations.cs @@ -9,9 +9,7 @@ public class Migrations : DataMigration { public async Task CreateAsync() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("Name") - ); + await SchemaBuilder.CreateMapIndexTableAsync(table => table.Column("Name")); return 1; } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Permissions.cs index 700ce606332..275d3b6c82e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Permissions.cs @@ -10,22 +10,9 @@ public class Permissions : IPermissionProvider public static readonly Permission Export = CommonPermissions.Export; public static readonly Permission Import = CommonPermissions.Import; - private readonly IEnumerable _allPermissions = - [ - Import, - Export, - ManageDeploymentPlan, - ]; + private readonly IEnumerable _allPermissions = [Import, Export, ManageDeploymentPlan,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Recipes/DeploymentPlansRecipeStep.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Recipes/DeploymentPlansRecipeStep.cs index 22af8f5010b..c6761c8f98f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Recipes/DeploymentPlansRecipeStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Recipes/DeploymentPlansRecipeStep.cs @@ -17,9 +17,7 @@ public class DeploymentPlansRecipeStep : IRecipeStepHandler private readonly IServiceProvider _serviceProvider; private readonly IDeploymentPlanService _deploymentPlanService; - public DeploymentPlansRecipeStep( - IServiceProvider serviceProvider, - IDeploymentPlanService deploymentPlanService) + public DeploymentPlansRecipeStep(IServiceProvider serviceProvider, IDeploymentPlanService deploymentPlanService) { _serviceProvider = serviceProvider; _deploymentPlanService = deploymentPlanService; @@ -41,10 +39,7 @@ public Task ExecuteAsync(RecipeExecutionContext context) foreach (var plan in model.Plans) { - var deploymentPlan = new DeploymentPlan - { - Name = plan.Name - }; + var deploymentPlan = new DeploymentPlan { Name = plan.Name }; foreach (var step in plan.Steps) { diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Services/FileDownloadDeploymentTargetProvider.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Services/FileDownloadDeploymentTargetProvider.cs index 575053e9dfa..c7dfc7e0515 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Services/FileDownloadDeploymentTargetProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Services/FileDownloadDeploymentTargetProvider.cs @@ -17,16 +17,19 @@ public FileDownloadDeploymentTargetProvider(IStringLocalizer> GetDeploymentTargetsAsync() { return Task.FromResult>( - new[] { + new[] + { new DeploymentTarget( name: S["File Download"], description: S["Download a deployment plan locally."], - route: new RouteValueDictionary(new - { - area = "OrchardCore.Deployment", - controller = "ExportFile", - action = "Execute" - }) + route: new RouteValueDictionary( + new + { + area = "OrchardCore.Deployment", + controller = "ExportFile", + action = "Execute" + } + ) ) } ); diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/CustomFileDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/CustomFileDeploymentStepDriver.cs index ccfb9a5ed9d..bcc2b943cf6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/CustomFileDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/CustomFileDeploymentStepDriver.cs @@ -10,20 +10,23 @@ public class CustomFileDeploymentStepDriver : DisplayDriver("CustomFileDeploymentStep_Fields_Edit", model => - { - model.FileContent = step.FileContent; - model.FileName = step.FileName; - }).Location("Content"); + return Initialize( + "CustomFileDeploymentStep_Fields_Edit", + model => + { + model.FileContent = step.FileContent; + model.FileName = step.FileName; + } + ) + .Location("Content"); } public override async Task UpdateAsync(CustomFileDeploymentStep step, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/JsonRecipeDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/JsonRecipeDeploymentStepDriver.cs index 6a97cbfa7be..913ceaa1d78 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/JsonRecipeDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/JsonRecipeDeploymentStepDriver.cs @@ -15,7 +15,8 @@ public class JsonRecipeDeploymentStepDriver : DisplayDriver /// A limited schema for recipe steps. Does not include any step data. /// - public const string Schema = @" + public const string Schema = + @" { ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""object"", @@ -40,20 +41,23 @@ public JsonRecipeDeploymentStepDriver(IStringLocalizer("JsonRecipeDeploymentStep_Fields_Edit", model => - { - model.Json = step.Json; - model.Schema = Schema; - }).Location("Content"); + return Initialize( + "JsonRecipeDeploymentStep_Fields_Edit", + model => + { + model.Json = step.Json; + model.Schema = Schema; + } + ) + .Location("Content"); } public override async Task UpdateAsync(JsonRecipeDeploymentStep step, IUpdateModel updater) @@ -67,15 +71,12 @@ public override async Task UpdateAsync(JsonRecipeDeploymentStep var jObject = JObject.Parse(model.Json); if (!jObject.ContainsKey("name")) { - updater.ModelState.AddModelError(Prefix, nameof(JsonRecipeDeploymentStepViewModel.Json), S["The recipe must have a name property"]); } - } catch (Exception) { updater.ModelState.AddModelError(Prefix, nameof(JsonRecipeDeploymentStepViewModel.Json), S["Invalid JSON supplied"]); - } step.Json = model.Json; } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/RecipeFileDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/RecipeFileDeploymentStepDriver.cs index 1110eb34a76..536f0a8709d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/RecipeFileDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/Steps/RecipeFileDeploymentStepDriver.cs @@ -10,32 +10,47 @@ public class RecipeFileDeploymentStepDriver : DisplayDriver("RecipeFileDeploymentStep_Fields_Edit", model => - { - model.RecipeName = step.RecipeName; - model.DisplayName = step.DisplayName; - model.Description = step.Description; - model.Author = step.Author; - model.WebSite = step.WebSite; - model.Version = step.Version; - model.IsSetupRecipe = step.IsSetupRecipe; - model.Categories = step.Categories; - model.Tags = step.Tags; - }).Location("Content"); + return Initialize( + "RecipeFileDeploymentStep_Fields_Edit", + model => + { + model.RecipeName = step.RecipeName; + model.DisplayName = step.DisplayName; + model.Description = step.Description; + model.Author = step.Author; + model.WebSite = step.WebSite; + model.Version = step.Version; + model.IsSetupRecipe = step.IsSetupRecipe; + model.Categories = step.Categories; + model.Tags = step.Tags; + } + ) + .Location("Content"); } public override async Task UpdateAsync(RecipeFileDeploymentStep step, IUpdateModel updater) { - await updater.TryUpdateModelAsync(step, Prefix, x => x.RecipeName, x => x.DisplayName, x => x.Description, x => x.Author, x => x.WebSite, x => x.Version, x => x.IsSetupRecipe, x => x.Categories, x => x.Tags); + await updater.TryUpdateModelAsync( + step, + Prefix, + x => x.RecipeName, + x => x.DisplayName, + x => x.Description, + x => x.Author, + x => x.WebSite, + x => x.Version, + x => x.IsSetupRecipe, + x => x.Categories, + x => x.Tags + ); return Edit(step); } diff --git a/src/OrchardCore.Modules/OrchardCore.Diagnostics/DiagnosticsStartupFilter.cs b/src/OrchardCore.Modules/OrchardCore.Diagnostics/DiagnosticsStartupFilter.cs index 691fd3f6037..30d1b575191 100644 --- a/src/OrchardCore.Modules/OrchardCore.Diagnostics/DiagnosticsStartupFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Diagnostics/DiagnosticsStartupFilter.cs @@ -29,22 +29,24 @@ public Action Configure(Action next) app.UseStatusCodePagesWithReExecute("/Error/{0}"); - app.Use(async (context, next) => - { - await next(); - - if (context.Response.StatusCode < 200 || context.Response.StatusCode >= 400) + app.Use( + async (context, next) => { - if (_contentTypeProvider.TryGetContentType(context.Request.Path.Value, out var contentType)) + await next(); + + if (context.Response.StatusCode < 200 || context.Response.StatusCode >= 400) { - var statusCodePagesFeature = context.Features.Get(); - if (statusCodePagesFeature != null) + if (_contentTypeProvider.TryGetContentType(context.Request.Path.Value, out var contentType)) { - statusCodePagesFeature.Enabled = false; + var statusCodePagesFeature = context.Features.Get(); + if (statusCodePagesFeature != null) + { + statusCodePagesFeature.Enabled = false; + } } } } - }); + ); next(app); }; diff --git a/src/OrchardCore.Modules/OrchardCore.DynamicCache/EventHandlers/DynamicCacheShapeDisplayEvents.cs b/src/OrchardCore.Modules/OrchardCore.DynamicCache/EventHandlers/DynamicCacheShapeDisplayEvents.cs index 0f79bc5ed69..7328bd72966 100644 --- a/src/OrchardCore.Modules/OrchardCore.DynamicCache/EventHandlers/DynamicCacheShapeDisplayEvents.cs +++ b/src/OrchardCore.Modules/OrchardCore.DynamicCache/EventHandlers/DynamicCacheShapeDisplayEvents.cs @@ -27,7 +27,8 @@ public DynamicCacheShapeDisplayEvents( IDynamicCacheService dynamicCacheService, ICacheScopeManager cacheScopeManager, HtmlEncoder htmlEncoder, - IOptions options) + IOptions options + ) { _dynamicCacheService = dynamicCacheService; _cacheScopeManager = cacheScopeManager; diff --git a/src/OrchardCore.Modules/OrchardCore.DynamicCache/Models/CacheContextModel.cs b/src/OrchardCore.Modules/OrchardCore.DynamicCache/Models/CacheContextModel.cs index a41d4c18940..30a07bf27fd 100644 --- a/src/OrchardCore.Modules/OrchardCore.DynamicCache/Models/CacheContextModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.DynamicCache/Models/CacheContextModel.cs @@ -32,9 +32,7 @@ internal static CacheContextModel FromCacheContext(CacheContext cacheContext) internal CacheContext ToCacheContext() { - var cacheContext = new CacheContext(CacheId) - .AddContext(Contexts.ToArray()) - .AddTag(Tags.ToArray()); + var cacheContext = new CacheContext(CacheId).AddContext(Contexts.ToArray()).AddTag(Tags.ToArray()); if (ExpiresOn.HasValue) { diff --git a/src/OrchardCore.Modules/OrchardCore.DynamicCache/Services/DefaultDynamicCacheService.cs b/src/OrchardCore.Modules/OrchardCore.DynamicCache/Services/DefaultDynamicCacheService.cs index f9bfd7c6ed5..13ebbcfb0c4 100644 --- a/src/OrchardCore.Modules/OrchardCore.DynamicCache/Services/DefaultDynamicCacheService.cs +++ b/src/OrchardCore.Modules/OrchardCore.DynamicCache/Services/DefaultDynamicCacheService.cs @@ -38,7 +38,8 @@ public DefaultDynamicCacheService( IServiceProvider serviceProvider, IOptions dynamicCacheOptions, IOptions options, - ILogger logger) + ILogger logger + ) { _cacheContextManager = cacheContextManager; _dynamicCache = dynamicCache; @@ -83,10 +84,7 @@ public async Task SetCachedValueAsync(CacheContext context, string value) _localCache[cacheKey] = value; var esi = JConvert.SerializeObject(CacheContextModel.FromCacheContext(context)); - await Task.WhenAll( - SetCachedValueAsync(cacheKey, value, context), - SetCachedValueAsync(GetCacheContextCacheKey(cacheKey), esi, context) - ); + await Task.WhenAll(SetCachedValueAsync(cacheKey, value, context), SetCachedValueAsync(GetCacheContextCacheKey(cacheKey), esi, context)); } public Task TagRemovedAsync(string tag, IEnumerable keys) @@ -125,10 +123,7 @@ private async Task SetCachedValueAsync(string cacheKey, string value, CacheConte { _logger.LogError(e, "Failed to write the '{CacheKey}' to the dynamic cache", cacheKey); - _memoryCache.Set(FailoverKey, true, new MemoryCacheEntryOptions() - { - AbsoluteExpirationRelativeToNow = _dynamicCacheOptions.FailoverRetryLatency - }); + _memoryCache.Set(FailoverKey, true, new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = _dynamicCacheOptions.FailoverRetryLatency }); return; } @@ -140,9 +135,7 @@ private async Task SetCachedValueAsync(string cacheKey, string value, CacheConte private async Task GetCacheKey(CacheContext context) { - var cacheEntries = context.Contexts.Count > 0 - ? await _cacheContextManager.GetDiscriminatorsAsync(context.Contexts) - : []; + var cacheEntries = context.Contexts.Count > 0 ? await _cacheContextManager.GetDiscriminatorsAsync(context.Contexts) : []; if (!cacheEntries.Any()) { @@ -185,10 +178,7 @@ private async Task GetCachedStringAsync(string cacheKey) { _logger.LogError(e, "Failed to read the '{CacheKey}' from the dynamic cache", cacheKey); - _memoryCache.Set(FailoverKey, true, new MemoryCacheEntryOptions() - { - AbsoluteExpirationRelativeToNow = _dynamicCacheOptions.FailoverRetryLatency - }); + _memoryCache.Set(FailoverKey, true, new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = _dynamicCacheOptions.FailoverRetryLatency }); } return null; diff --git a/src/OrchardCore.Modules/OrchardCore.DynamicCache/TagHelpers/CacheDependencyTagHelper.cs b/src/OrchardCore.Modules/OrchardCore.DynamicCache/TagHelpers/CacheDependencyTagHelper.cs index b055b279399..0d7d8258c2e 100644 --- a/src/OrchardCore.Modules/OrchardCore.DynamicCache/TagHelpers/CacheDependencyTagHelper.cs +++ b/src/OrchardCore.Modules/OrchardCore.DynamicCache/TagHelpers/CacheDependencyTagHelper.cs @@ -17,14 +17,11 @@ public class CacheDependencyTagHelper : TagHelper private readonly ICacheScopeManager _cacheScopeManager; - public CacheDependencyTagHelper( - ICacheScopeManager cacheScopeManager) - + public CacheDependencyTagHelper(ICacheScopeManager cacheScopeManager) { _cacheScopeManager = cacheScopeManager; } - /// public override void Process(TagHelperContext context, TagHelperOutput output) { diff --git a/src/OrchardCore.Modules/OrchardCore.DynamicCache/TagHelpers/DynamicCacheTagHelper.cs b/src/OrchardCore.Modules/OrchardCore.DynamicCache/TagHelpers/DynamicCacheTagHelper.cs index 273bf3255f0..028433950ad 100644 --- a/src/OrchardCore.Modules/OrchardCore.DynamicCache/TagHelpers/DynamicCacheTagHelper.cs +++ b/src/OrchardCore.Modules/OrchardCore.DynamicCache/TagHelpers/DynamicCacheTagHelper.cs @@ -92,7 +92,8 @@ public DynamicCacheTagHelper( ICacheScopeManager cacheScopeManager, HtmlEncoder htmlEncoder, DynamicCacheTagHelperService dynamicCacheTagHelperService, - IOptions cacheOptions) + IOptions cacheOptions + ) { _dynamicCacheService = dynamicCacheService; _cacheScopeManager = cacheScopeManager; @@ -227,10 +228,7 @@ public async Task ProcessContentAsync(TagHelperOutput output, Cach var html = writer.ToString(); - var formattingContext = new DistributedCacheTagHelperFormattingContext - { - Html = new HtmlString(html) - }; + var formattingContext = new DistributedCacheTagHelperFormattingContext { Html = new HtmlString(html) }; await _dynamicCacheService.SetCachedValueAsync(cacheContext, html); diff --git a/src/OrchardCore.Modules/OrchardCore.Email/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Email/AdminMenu.cs index f4db7cac39a..1f20a4eaf36 100644 --- a/src/OrchardCore.Modules/OrchardCore.Email/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Email/AdminMenu.cs @@ -8,11 +8,7 @@ namespace OrchardCore.Email { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", SmtpSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", SmtpSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -28,17 +24,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Email"], S["Email"].PrefixPosition(), entry => entry - .AddClass("email").Id("email") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageEmailSettings) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Email"], + S["Email"].PrefixPosition(), + entry => entry.AddClass("email").Id("email").Action("Index", "Admin", _routeValues).Permission(Permissions.ManageEmailSettings).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Email/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Email/Controllers/AdminController.cs index edc0dae370f..ae8c7e7bd1b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Email/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Email/Controllers/AdminController.cs @@ -17,11 +17,7 @@ public class AdminController : Controller private readonly ISmtpService _smtpService; protected readonly IHtmlLocalizer H; - public AdminController( - IHtmlLocalizer h, - IAuthorizationService authorizationService, - INotifier notifier, - ISmtpService smtpService) + public AdminController(IHtmlLocalizer h, IAuthorizationService authorizationService, INotifier notifier, ISmtpService smtpService) { H = h; _authorizationService = authorizationService; diff --git a/src/OrchardCore.Modules/OrchardCore.Email/Drivers/SmtpSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Email/Drivers/SmtpSettingsDisplayDriver.cs index 789dad473af..8bf375bb76d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Email/Drivers/SmtpSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Email/Drivers/SmtpSettingsDisplayDriver.cs @@ -27,7 +27,8 @@ public SmtpSettingsDisplayDriver( IShellHost shellHost, ShellSettings shellSettings, IHttpContextAccessor httpContextAccessor, - IAuthorizationService authorizationService) + IAuthorizationService authorizationService + ) { _dataProtectionProvider = dataProtectionProvider; _shellHost = shellHost; @@ -47,23 +48,28 @@ public override async Task EditAsync(SmtpSettings settings, Buil var shapes = new List { - Initialize("SmtpSettings_Edit", model => - { - model.DefaultSender = settings.DefaultSender; - model.DeliveryMethod = settings.DeliveryMethod; - model.PickupDirectoryLocation = settings.PickupDirectoryLocation; - model.Host = settings.Host; - model.Port = settings.Port; - model.ProxyHost = settings.ProxyHost; - model.ProxyPort = settings.ProxyPort; - model.EncryptionMethod = settings.EncryptionMethod; - model.AutoSelectEncryption = settings.AutoSelectEncryption; - model.RequireCredentials = settings.RequireCredentials; - model.UseDefaultCredentials = settings.UseDefaultCredentials; - model.UserName = settings.UserName; - model.Password = settings.Password; - model.IgnoreInvalidSslCertificate = settings.IgnoreInvalidSslCertificate; - }).Location("Content:5").OnGroup(GroupId), + Initialize( + "SmtpSettings_Edit", + model => + { + model.DefaultSender = settings.DefaultSender; + model.DeliveryMethod = settings.DeliveryMethod; + model.PickupDirectoryLocation = settings.PickupDirectoryLocation; + model.Host = settings.Host; + model.Port = settings.Port; + model.ProxyHost = settings.ProxyHost; + model.ProxyPort = settings.ProxyPort; + model.EncryptionMethod = settings.EncryptionMethod; + model.AutoSelectEncryption = settings.AutoSelectEncryption; + model.RequireCredentials = settings.RequireCredentials; + model.UseDefaultCredentials = settings.UseDefaultCredentials; + model.UserName = settings.UserName; + model.Password = settings.Password; + model.IgnoreInvalidSslCertificate = settings.IgnoreInvalidSslCertificate; + } + ) + .Location("Content:5") + .OnGroup(GroupId), }; if (settings?.DefaultSender != null) diff --git a/src/OrchardCore.Modules/OrchardCore.Email/Extensions/OrchardCoreBuilderExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Email/Extensions/OrchardCoreBuilderExtensions.cs index 203210e73a5..7b46e41f1ba 100644 --- a/src/OrchardCore.Modules/OrchardCore.Email/Extensions/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Email/Extensions/OrchardCoreBuilderExtensions.cs @@ -8,12 +8,14 @@ public static class OrchardCoreBuilderExtensions { public static OrchardCoreBuilder ConfigureEmailSettings(this OrchardCoreBuilder builder) { - builder.ConfigureServices((tenantServices, serviceProvider) => - { - var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Email"); + builder.ConfigureServices( + (tenantServices, serviceProvider) => + { + var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Email"); - tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); - }); + tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); + } + ); return builder; } diff --git a/src/OrchardCore.Modules/OrchardCore.Email/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Email/Permissions.cs index 92ac634713d..32bd98c1e7e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Email/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Email/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageEmailSettings = new("ManageEmailSettings", "Manage Email Settings"); - private readonly IEnumerable _allPermissions = - [ - ManageEmailSettings, - ]; + private readonly IEnumerable _allPermissions = [ManageEmailSettings,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Email/Services/SmtpSettingsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Email/Services/SmtpSettingsConfiguration.cs index 4d2c9b3ce8d..b3afe5c2d45 100644 --- a/src/OrchardCore.Modules/OrchardCore.Email/Services/SmtpSettingsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Email/Services/SmtpSettingsConfiguration.cs @@ -11,10 +11,7 @@ public class SmtpSettingsConfiguration : IConfigureOptions private readonly IDataProtectionProvider _dataProtectionProvider; private readonly ILogger _logger; - public SmtpSettingsConfiguration( - ISiteService site, - IDataProtectionProvider dataProtectionProvider, - ILogger logger) + public SmtpSettingsConfiguration(ISiteService site, IDataProtectionProvider dataProtectionProvider, ILogger logger) { _site = site; _dataProtectionProvider = dataProtectionProvider; @@ -23,9 +20,7 @@ public SmtpSettingsConfiguration( public void Configure(SmtpSettings options) { - var settings = _site.GetSiteSettingsAsync() - .GetAwaiter().GetResult() - .As(); + var settings = _site.GetSiteSettingsAsync().GetAwaiter().GetResult().As(); options.DefaultSender = settings.DefaultSender; options.DeliveryMethod = settings.DeliveryMethod; diff --git a/src/OrchardCore.Modules/OrchardCore.Email/Workflows/Activities/EmailTask.cs b/src/OrchardCore.Modules/OrchardCore.Email/Workflows/Activities/EmailTask.cs index cf7b9d1c8ff..7dff6237323 100644 --- a/src/OrchardCore.Modules/OrchardCore.Email/Workflows/Activities/EmailTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Email/Workflows/Activities/EmailTask.cs @@ -16,12 +16,7 @@ public class EmailTask : TaskActivity protected readonly IStringLocalizer S; private readonly HtmlEncoder _htmlEncoder; - public EmailTask( - ISmtpService smtpService, - IWorkflowExpressionEvaluator expressionEvaluator, - IStringLocalizer localizer, - HtmlEncoder htmlEncoder - ) + public EmailTask(ISmtpService smtpService, IWorkflowExpressionEvaluator expressionEvaluator, IStringLocalizer localizer, HtmlEncoder htmlEncoder) { _smtpService = smtpService; _expressionEvaluator = expressionEvaluator; @@ -88,7 +83,6 @@ public bool IsHtmlBody set => SetProperty(value); } - public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { return Outcomes(S["Done"], S["Failed"]); diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/AdminMenu.cs index c149d0cf2e1..b3e238a7a79 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/AdminMenu.cs @@ -7,16 +7,11 @@ namespace OrchardCore.Facebook; public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", FacebookConstants.Features.Core }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", FacebookConstants.Features.Core }, }; protected readonly IStringLocalizer S; - public AdminMenu( - IStringLocalizer localizer) + public AdminMenu(IStringLocalizer localizer) { S = localizer; } @@ -28,18 +23,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Meta App"], S["Meta App"].PrefixPosition(), metaApp => metaApp - .AddClass("facebookApp") - .Id("facebookApp") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageFacebookApp) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Meta App"], + S["Meta App"].PrefixPosition(), + metaApp => metaApp.AddClass("facebookApp").Id("facebookApp").Action("Index", "Admin", _routeValues).Permission(Permissions.ManageFacebookApp).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } @@ -47,16 +43,11 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) public class AdminMenuLogin : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", FacebookConstants.Features.Login }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", FacebookConstants.Features.Login }, }; protected readonly IStringLocalizer S; - public AdminMenuLogin( - IStringLocalizer localizer) + public AdminMenuLogin(IStringLocalizer localizer) { S = localizer; } @@ -68,18 +59,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Authentication"], authentication => authentication - .Add(S["Meta"], S["Meta"].PrefixPosition(), meta => meta - .AddClass("facebook") - .Id("facebook") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageFacebookApp) - .LocalNav() - ) + builder.Add( + S["Security"], + security => + security.Add( + S["Authentication"], + authentication => + authentication.Add( + S["Meta"], + S["Meta"].PrefixPosition(), + meta => meta.AddClass("facebook").Id("facebook").Action("Index", "Admin", _routeValues).Permission(Permissions.ManageFacebookApp).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } @@ -87,16 +79,11 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) public class AdminMenuPixel : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", FacebookConstants.PixelSettingsGroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", FacebookConstants.PixelSettingsGroupId }, }; protected readonly IStringLocalizer S; - public AdminMenuPixel( - IStringLocalizer stringLocalizer) + public AdminMenuPixel(IStringLocalizer stringLocalizer) { S = stringLocalizer; } @@ -108,18 +95,25 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Meta Pixel"], S["Meta Pixel"].PrefixPosition(), pixel => pixel - .AddClass("facebookPixel") - .Id("facebookPixel") - .Action("Index", "Admin", _routeValues) - .Permission(FacebookConstants.ManageFacebookPixelPermission) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Meta Pixel"], + S["Meta Pixel"].PrefixPosition(), + pixel => + pixel + .AddClass("facebookPixel") + .Id("facebookPixel") + .Action("Index", "Admin", _routeValues) + .Permission(FacebookConstants.ManageFacebookPixelPermission) + .LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Deployment/FacebookLoginDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Deployment/FacebookLoginDeploymentStepDriver.cs index cd8cb48356e..c5e8f4708ce 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Deployment/FacebookLoginDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Deployment/FacebookLoginDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class FacebookLoginDeploymentStepDriver : DisplayDriver EditAsync(FacebookPixelSettings setti return null; } - return Initialize("FacebookPixelSettings_Edit", model => - { - model.PixelId = settings.PixelId; - }).Location("Content:0") - .OnGroup(FacebookConstants.PixelSettingsGroupId); + return Initialize( + "FacebookPixelSettings_Edit", + model => + { + model.PixelId = settings.PixelId; + } + ) + .Location("Content:0") + .OnGroup(FacebookConstants.PixelSettingsGroupId); } public override async Task UpdateAsync(FacebookPixelSettings settings, BuildEditorContext context) { - if (!string.Equals(FacebookConstants.PixelSettingsGroupId, context.GroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, Permissions.ManageFacebookApp)) + if ( + !string.Equals(FacebookConstants.PixelSettingsGroupId, context.GroupId, StringComparison.OrdinalIgnoreCase) + || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, Permissions.ManageFacebookApp) + ) { return null; } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Drivers/FacebookSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Drivers/FacebookSettingsDisplayDriver.cs index bbce3f93e65..f2132773fe8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Drivers/FacebookSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Drivers/FacebookSettingsDisplayDriver.cs @@ -30,7 +30,7 @@ public FacebookSettingsDisplayDriver( IShellHost shellHost, ShellSettings shellSettings, ILogger logger - ) + ) { _authorizationService = authorizationService; _dataProtectionProvider = dataProtectionProvider; @@ -48,29 +48,34 @@ public override async Task EditAsync(FacebookSettings settings, return null; } - return Initialize("FacebookSettings_Edit", model => - { - var protector = _dataProtectionProvider.CreateProtector(FacebookConstants.Features.Core); - - model.AppId = settings.AppId; - model.FBInit = settings.FBInit; - model.FBInitParams = settings.FBInitParams; - model.Version = settings.Version; - model.SdkJs = settings.SdkJs; - if (!string.IsNullOrWhiteSpace(settings.AppSecret)) - { - try + return Initialize( + "FacebookSettings_Edit", + model => { - model.AppSecret = protector.Unprotect(settings.AppSecret); - } - catch (CryptographicException) - { - _logger.LogError("The app secret could not be decrypted. It may have been encrypted using a different key."); - model.AppSecret = string.Empty; - model.HasDecryptionError = true; + var protector = _dataProtectionProvider.CreateProtector(FacebookConstants.Features.Core); + + model.AppId = settings.AppId; + model.FBInit = settings.FBInit; + model.FBInitParams = settings.FBInitParams; + model.Version = settings.Version; + model.SdkJs = settings.SdkJs; + if (!string.IsNullOrWhiteSpace(settings.AppSecret)) + { + try + { + model.AppSecret = protector.Unprotect(settings.AppSecret); + } + catch (CryptographicException) + { + _logger.LogError("The app secret could not be decrypted. It may have been encrypted using a different key."); + model.AppSecret = string.Empty; + model.HasDecryptionError = true; + } + } } - } - }).Location("Content:0").OnGroup(FacebookConstants.Features.Core); + ) + .Location("Content:0") + .OnGroup(FacebookConstants.Features.Core); } public override async Task UpdateAsync(FacebookSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Extensions/OrchardCoreBuilderExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Extensions/OrchardCoreBuilderExtensions.cs index dab0ce5413a..459e933dfb4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Extensions/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Extensions/OrchardCoreBuilderExtensions.cs @@ -8,12 +8,14 @@ public static class OrchardCoreBuilderExtensions { public static OrchardCoreBuilder ConfigureFacebookSettings(this OrchardCoreBuilder builder) { - builder.ConfigureServices((tenantServices, serviceProvider) => - { - var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Facebook"); + builder.ConfigureServices( + (tenantServices, serviceProvider) => + { + var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Facebook"); - tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); - }); + tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); + } + ); return builder; } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/FacebookConstants.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/FacebookConstants.cs index 2afd88f2575..c9d0a824f1c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/FacebookConstants.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/FacebookConstants.cs @@ -4,8 +4,7 @@ namespace OrchardCore.Facebook; public static class FacebookConstants { - public static readonly Permission ManageFacebookPixelPermission - = new("ManageFacebookPixel", "Manage Facebook Pixel settings."); + public static readonly Permission ManageFacebookPixelPermission = new("ManageFacebookPixel", "Manage Facebook Pixel settings."); public const string PixelSettingsGroupId = "facebook-pixel"; diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Filters/FBInitFilter.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Filters/FBInitFilter.cs index a0c983df505..c66b653f9b0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Filters/FBInitFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Filters/FBInitFilter.cs @@ -12,9 +12,7 @@ public class FBInitFilter : IAsyncResultFilter private readonly IResourceManager _resourceManager; private readonly ISiteService _siteService; - public FBInitFilter( - IResourceManager resourceManager, - ISiteService siteService) + public FBInitFilter(IResourceManager resourceManager, ISiteService siteService) { _resourceManager = resourceManager; _siteService = siteService; diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Filters/FacebookPixelFilter.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Filters/FacebookPixelFilter.cs index 5593343cd4d..6b55430ea0f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Filters/FacebookPixelFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Filters/FacebookPixelFilter.cs @@ -13,13 +13,14 @@ public class FacebookPixelFilter : IAsyncResultFilter { private readonly IResourceManager _resourceManager; private readonly ISiteService _siteService; - private readonly HtmlString _code = new("\r\n\r\n"); + private readonly HtmlString _code = + new( + "\r\n\r\n" + ); private HtmlString _scriptsCache; - public FacebookPixelFilter( - IResourceManager resourceManager, - ISiteService siteService) + public FacebookPixelFilter(IResourceManager resourceManager, ISiteService siteService) { _resourceManager = resourceManager; _siteService = siteService; diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Configuration/FacebookLoginConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Configuration/FacebookLoginConfiguration.cs index 51ea48644c9..469fd25873f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Configuration/FacebookLoginConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Configuration/FacebookLoginConfiguration.cs @@ -15,9 +15,7 @@ namespace OrchardCore.Facebook.Login.Configuration { [Feature(FacebookConstants.Features.Login)] - public class FacebookLoginConfiguration : - IConfigureOptions, - IConfigureNamedOptions + public class FacebookLoginConfiguration : IConfigureOptions, IConfigureNamedOptions { private readonly FacebookSettings _facebookSettings; private readonly IFacebookLoginService _loginService; @@ -28,7 +26,8 @@ public FacebookLoginConfiguration( IOptions facebookSettings, IFacebookLoginService loginService, IDataProtectionProvider dataProtectionProvider, - ILogger logger) + ILogger logger + ) { _facebookSettings = facebookSettings.Value; _loginService = loginService; @@ -57,11 +56,14 @@ public void Configure(AuthenticationOptions options) } // Register the OpenID Connect client handler in the authentication handlers collection. - options.AddScheme(FacebookDefaults.AuthenticationScheme, builder => - { - builder.DisplayName = "Facebook"; - builder.HandlerType = typeof(FacebookHandler); - }); + options.AddScheme( + FacebookDefaults.AuthenticationScheme, + builder => + { + builder.DisplayName = "Facebook"; + builder.HandlerType = typeof(FacebookHandler); + } + ); } public void Configure(string name, FacebookOptions options) diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Drivers/FacebookLoginSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Drivers/FacebookLoginSettingsDisplayDriver.cs index 4314721082f..676973a95e5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Drivers/FacebookLoginSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Drivers/FacebookLoginSettingsDisplayDriver.cs @@ -22,7 +22,8 @@ public FacebookLoginSettingsDisplayDriver( IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor, IShellHost shellHost, - ShellSettings shellSettings) + ShellSettings shellSettings + ) { _authorizationService = authorizationService; _httpContextAccessor = httpContextAccessor; @@ -38,11 +39,16 @@ public override async Task EditAsync(FacebookLoginSettings setti return null; } - return Initialize("FacebookLoginSettings_Edit", model => - { - model.CallbackPath = settings.CallbackPath.Value; - model.SaveTokens = settings.SaveTokens; - }).Location("Content:5").OnGroup(FacebookConstants.Features.Login); + return Initialize( + "FacebookLoginSettings_Edit", + model => + { + model.CallbackPath = settings.CallbackPath.Value; + model.SaveTokens = settings.SaveTokens; + } + ) + .Location("Content:5") + .OnGroup(FacebookConstants.Features.Login); } public override async Task UpdateAsync(FacebookLoginSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Services/FacebookLoginService.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Services/FacebookLoginService.cs index a992d8151b5..a44b6191d73 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Services/FacebookLoginService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Login/Services/FacebookLoginService.cs @@ -13,8 +13,7 @@ public class FacebookLoginService : IFacebookLoginService { private readonly ISiteService _siteService; - public FacebookLoginService( - ISiteService siteService) + public FacebookLoginService(ISiteService siteService) { _siteService = siteService; } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Manifest.cs index 2374c361c7a..cb4eaaa4ada 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Manifest.cs @@ -22,10 +22,7 @@ Name = "Meta Login", Category = "Meta", Description = "Authenticates users from Meta.", - Dependencies = - [ - FacebookConstants.Features.Core - ] + Dependencies = [FacebookConstants.Features.Core] )] [assembly: Feature( @@ -33,17 +30,7 @@ Name = "Meta Social Plugins Widgets", Category = "Meta", Description = "Integrates Meta social plugins as predefined widgets", - Dependencies = - [ - FacebookConstants.Features.Core, - "OrchardCore.Widgets", - "OrchardCore.Recipes.Core", - ] + Dependencies = [FacebookConstants.Features.Core, "OrchardCore.Widgets", "OrchardCore.Recipes.Core",] )] -[assembly: Feature( - Id = FacebookConstants.Features.Pixel, - Name = "Meta Pixel", - Category = "Meta", - Description = "Provides a way to enable Meta Pixel tracking for your site." -)] +[assembly: Feature(Id = FacebookConstants.Features.Pixel, Name = "Meta Pixel", Category = "Meta", Description = "Provides a way to enable Meta Pixel tracking for your site.")] diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Permissions.cs index 7a147113e51..6c13cd83f2a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageFacebookApp = new("ManageFacebookApp", "View and edit the Facebook app."); - private readonly IEnumerable _allPermissions = - [ - ManageFacebookApp, - ]; + private readonly IEnumerable _allPermissions = [ManageFacebookApp,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/PixelPermissionProvider.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/PixelPermissionProvider.cs index 438061b8a8b..25e72a1ddb7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/PixelPermissionProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/PixelPermissionProvider.cs @@ -8,20 +8,9 @@ public class PixelPermissionProvider : IPermissionProvider { public static readonly Permission ManageFacebookPixelPermission = FacebookConstants.ManageFacebookPixelPermission; - private readonly IEnumerable _allPermissions = - [ - ManageFacebookPixelPermission, - ]; + private readonly IEnumerable _allPermissions = [ManageFacebookPixelPermission,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/ResourceManagementOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/ResourceManagementOptionsConfiguration.cs index e6db50209c9..3289d16e567 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/ResourceManagementOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/ResourceManagementOptionsConfiguration.cs @@ -11,14 +11,9 @@ static ResourceManagementOptionsConfiguration() { _manifest = new ResourceManifest(); - _manifest - .DefineScript("fb") - .SetDependencies("fbsdk") - .SetUrl("~/OrchardCore.Facebook/sdk/fb.js"); + _manifest.DefineScript("fb").SetDependencies("fbsdk").SetUrl("~/OrchardCore.Facebook/sdk/fb.js"); - _manifest - .DefineScript("fbsdk") - .SetUrl("~/OrchardCore.Facebook/sdk/fbsdk.js"); + _manifest.DefineScript("fbsdk").SetUrl("~/OrchardCore.Facebook/sdk/fbsdk.js"); } public void Configure(ResourceManagementOptions options) => options.ResourceManifests.Add(_manifest); diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/ScriptsMiddleware.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/ScriptsMiddleware.cs index d42ab4ac2f8..6745f9931c8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/ScriptsMiddleware.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/ScriptsMiddleware.cs @@ -31,7 +31,8 @@ public async Task Invoke(HttpContext httpContext) if (Path.GetFileName(httpContext.Request.Path.Value) == "fbsdk.js") { var locale = CultureInfo.CurrentUICulture.Name.Replace('-', '_'); - script = $@"(function(d){{ + script = + $@"(function(d){{ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {{ return; }} js = d.createElement('script'); js.id = id; js.async = true; js.src = ""https://connect.facebook.net/{locale}/{settings.SdkJs}""; diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Services/FacebookService.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Services/FacebookService.cs index 0679fbb3009..ae2099f0e80 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Services/FacebookService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Services/FacebookService.cs @@ -14,9 +14,7 @@ public class FacebookService : IFacebookService private readonly ISiteService _siteService; protected readonly IStringLocalizer S; - public FacebookService( - ISiteService siteService, - IStringLocalizer stringLocalizer) + public FacebookService(ISiteService siteService, IStringLocalizer stringLocalizer) { _siteService = siteService; S = stringLocalizer; @@ -45,18 +43,12 @@ public IEnumerable ValidateSettings(FacebookSettings settings) if (string.IsNullOrEmpty(settings.AppId)) { - results.Add(new ValidationResult(S["The AppId is required."], new[] - { - nameof(settings.AppId), - })); + results.Add(new ValidationResult(S["The AppId is required."], new[] { nameof(settings.AppId), })); } if (string.IsNullOrEmpty(settings.AppSecret)) { - results.Add(new ValidationResult(S["The App Secret is required."], new[] - { - nameof(settings.AppSecret), - })); + results.Add(new ValidationResult(S["The App Secret is required."], new[] { nameof(settings.AppSecret), })); } return results; diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Services/FacebookSettingsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Services/FacebookSettingsConfiguration.cs index a71b6ad59d5..856e993134b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Services/FacebookSettingsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Services/FacebookSettingsConfiguration.cs @@ -14,10 +14,7 @@ public class FacebookSettingsConfiguration : IConfigureOptions private readonly ShellSettings _shellSettings; private readonly ILogger _logger; - public FacebookSettingsConfiguration( - IFacebookService facebookService, - ShellSettings shellSettings, - ILogger logger) + public FacebookSettingsConfiguration(IFacebookService facebookService, ShellSettings shellSettings, ILogger logger) { _facebookService = facebookService; _shellSettings = shellSettings; @@ -26,9 +23,7 @@ public FacebookSettingsConfiguration( public void Configure(FacebookSettings options) { - var settings = GetFacebookSettingsAsync() - .GetAwaiter() - .GetResult(); + var settings = GetFacebookSettingsAsync().GetAwaiter().GetResult(); if (settings != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Settings/FacebookSettings.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Settings/FacebookSettings.cs index 41edf857317..d33e7a43db5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Settings/FacebookSettings.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Settings/FacebookSettings.cs @@ -6,7 +6,8 @@ public class FacebookSettings public string AppSecret { get; set; } public bool FBInit { get; set; } = false; - public string FBInitParams { get; set; } = @"status:true, + public string FBInitParams { get; set; } = + @"status:true, xfbml:true, autoLogAppEvents:true"; diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Startup.cs index c3b60367320..8c0dff43570 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Startup.cs @@ -38,10 +38,12 @@ public override void ConfigureServices(IServiceCollection services) services.AddTransient, ResourceManagementOptionsConfiguration>(); services.AddTransient, FacebookSettingsConfiguration>(); - services.Configure((options) => - { - options.Filters.Add(typeof(FBInitFilter)); - }); + services.Configure( + (options) => + { + options.Filters.Add(typeof(FBInitFilter)); + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/StartupLogin.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/StartupLogin.cs index 9b0edfd0ed2..f420fc81297 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/StartupLogin.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/StartupLogin.cs @@ -29,17 +29,18 @@ public override void ConfigureServices(IServiceCollection services) services.AddRecipeExecutionStep(); // Register the options initializers required by the Facebook handler. - services.TryAddEnumerable(new[] - { - // Orchard-specific initializers: - ServiceDescriptor.Transient, FacebookLoginConfiguration>(), - ServiceDescriptor.Transient, FacebookLoginConfiguration>(), + services.TryAddEnumerable( + new[] + { + // Orchard-specific initializers: + ServiceDescriptor.Transient, FacebookLoginConfiguration>(), + ServiceDescriptor.Transient, FacebookLoginConfiguration>(), + // Deployment - // Deployment - - // Built-in initializers: - ServiceDescriptor.Transient, OAuthPostConfigureOptions>() - }); + // Built-in initializers: + ServiceDescriptor.Transient, OAuthPostConfigureOptions>() + } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/StartupPixel.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/StartupPixel.cs index fa7541a203b..4536e7cedc9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/StartupPixel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/StartupPixel.cs @@ -19,9 +19,11 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); - services.Configure((options) => - { - options.Filters.Add(typeof(FacebookPixelFilter)); - }); + services.Configure( + (options) => + { + options.Filters.Add(typeof(FacebookPixelFilter)); + } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/StartupWidgets.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/StartupWidgets.cs index 880a0f67f5f..16cffe94feb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/StartupWidgets.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/StartupWidgets.cs @@ -22,9 +22,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddDataMigration(); services.AddScoped(); - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddScoped(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Drivers/FacebookPluginPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Drivers/FacebookPluginPartDisplayDriver.cs index 8cea82e4707..2362106a6a2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Drivers/FacebookPluginPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Drivers/FacebookPluginPartDisplayDriver.cs @@ -22,7 +22,8 @@ public class FacebookPluginPartDisplayDriver : ContentPartDisplayDriver localizer) + IStringLocalizer localizer + ) { _contentDefinitionManager = contentDefinitionManager; _liquidTemplateManager = liquidTemplateManager; @@ -32,10 +33,8 @@ public FacebookPluginPartDisplayDriver( public override IDisplayResult Display(FacebookPluginPart part) { return Combine( - Initialize("FacebookPluginPart", async m => await BuildViewModelAsync(m, part)) - .Location("Detail", "Content"), - Initialize("FacebookPluginPart_Summary", async m => await BuildViewModelAsync(m, part)) - .Location("Summary", "Content") + Initialize("FacebookPluginPart", async m => await BuildViewModelAsync(m, part)).Location("Detail", "Content"), + Initialize("FacebookPluginPart_Summary", async m => await BuildViewModelAsync(m, part)).Location("Summary", "Content") ); } @@ -52,12 +51,15 @@ private async Task BuildViewModelAsync(FacebookPluginPartViewModel model, Facebo public override IDisplayResult Edit(FacebookPluginPart part) { - return Initialize("FacebookPluginPart_Edit", async model => - { - model.Settings = await GetFacebookPluginPartSettingsAsync(part); - model.FacebookPluginPart = part; - model.Liquid = string.IsNullOrWhiteSpace(part.Liquid) ? model.Settings.Liquid : part.Liquid; - }); + return Initialize( + "FacebookPluginPart_Edit", + async model => + { + model.Settings = await GetFacebookPluginPartSettingsAsync(part); + model.FacebookPluginPart = part; + model.Liquid = string.IsNullOrWhiteSpace(part.Liquid) ? model.Settings.Liquid : part.Liquid; + } + ); } private async Task GetFacebookPluginPartSettingsAsync(FacebookPluginPart part) @@ -77,7 +79,10 @@ public override async Task UpdateAsync(FacebookPluginPart model, { if (!string.IsNullOrEmpty(viewModel.Liquid) && !_liquidTemplateManager.Validate(viewModel.Liquid, out var errors)) { - updater.ModelState.AddModelError(nameof(model.Liquid), S["The FaceBook Body doesn't contain a valid Liquid expression. Details: {0}", string.Join(" ", errors)]); + updater.ModelState.AddModelError( + nameof(model.Liquid), + S["The FaceBook Body doesn't contain a valid Liquid expression. Details: {0}", string.Join(" ", errors)] + ); } else { diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Handlers/FacebookPluginPartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Handlers/FacebookPluginPartHandler.cs index 56f7c120aa6..9e336c6bc28 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Handlers/FacebookPluginPartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Handlers/FacebookPluginPartHandler.cs @@ -35,8 +35,12 @@ public override Task GetContentItemAspectAsync(ContentItemAspectContext context, ContentItem = part.ContentItem }; - var result = await _liquidTemplateManager.RenderHtmlContentAsync(part.Liquid, _htmlEncoder, model, - new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) }); + var result = await _liquidTemplateManager.RenderHtmlContentAsync( + part.Liquid, + _htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); bodyAspect.Body = result; } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Services/LiquidShapes.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Services/LiquidShapes.cs index acb857d1ed1..1238d486704 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Services/LiquidShapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Services/LiquidShapes.cs @@ -29,7 +29,11 @@ private async Task BuildViewModelAsync(ShapeDisplayContext shapeDisplayContext) var model = shapeDisplayContext.Shape as FacebookPluginPartViewModel; var liquidTemplateManager = shapeDisplayContext.ServiceProvider.GetRequiredService(); - model.Html = await liquidTemplateManager.RenderStringAsync(model.FacebookPluginPart.Liquid, _htmlEncoder, shapeDisplayContext.DisplayContext.Value, - new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) }); + model.Html = await liquidTemplateManager.RenderStringAsync( + model.FacebookPluginPart.Liquid, + _htmlEncoder, + shapeDisplayContext.DisplayContext.Value, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Settings/FacebookPluginPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Settings/FacebookPluginPartSettingsDisplayDriver.cs index ad2b15d5154..ce29b8e8193 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Settings/FacebookPluginPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/Settings/FacebookPluginPartSettingsDisplayDriver.cs @@ -22,19 +22,22 @@ public FacebookPluginPartSettingsDisplayDriver(ILiquidTemplateManager templateMa public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("FacebookPluginPartSettings_Edit", model => - { - model.FacebookPluginPartSettings = contentTypePartDefinition.GetSettings(); - model.Liquid = model.FacebookPluginPartSettings.Liquid; - }).Location("Content"); + return Initialize( + "FacebookPluginPartSettings_Edit", + model => + { + model.FacebookPluginPartSettings = contentTypePartDefinition.GetSettings(); + model.Liquid = model.FacebookPluginPartSettings.Liquid; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) { var model = new FacebookPluginPartSettingsViewModel(); - await context.Updater.TryUpdateModelAsync(model, Prefix, - m => m.Liquid); + await context.Updater.TryUpdateModelAsync(model, Prefix, m => m.Liquid); if (!string.IsNullOrEmpty(model.Liquid) && !_templateManager.Validate(model.Liquid, out var errors)) { diff --git a/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/WidgetMigrations.cs b/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/WidgetMigrations.cs index 8c876a063f4..faa5f58ea8b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/WidgetMigrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Facebook/Widgets/WidgetMigrations.cs @@ -23,9 +23,10 @@ public WidgetMigrations(IRecipeMigrator recipeMigrator, IContentDefinitionManage public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync(nameof(FacebookPluginPart), builder => builder - .Attachable() - .WithDescription("Provides a Facebook plugin part to create Facebook social plugin widgets.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + nameof(FacebookPluginPart), + builder => builder.Attachable().WithDescription("Provides a Facebook plugin part to create Facebook social plugin widgets.") + ); await _recipeMigrator.ExecuteAsync($"Widgets/migration{RecipesConstants.RecipeExtension}", this); return 1; diff --git a/src/OrchardCore.Modules/OrchardCore.Features/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Features/AdminMenu.cs index c7bd974eef4..9396d87d689 100644 --- a/src/OrchardCore.Modules/OrchardCore.Features/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Features/AdminMenu.cs @@ -7,12 +7,13 @@ namespace OrchardCore.Features { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", FeaturesConstants.FeatureId }, - // Since features admin accepts tenant, always pass empty string to create valid link for current tenant. - { "tenant", string.Empty }, - }; + private static readonly RouteValueDictionary _routeValues = + new() + { + { "area", FeaturesConstants.FeatureId }, + // Since features admin accepts tenant, always pass empty string to create valid link for current tenant. + { "tenant", string.Empty }, + }; protected readonly IStringLocalizer S; @@ -28,14 +29,15 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Features"], S["Features"].PrefixPosition(), deployment => deployment - .Action("Features", "Admin", _routeValues) - .Permission(Permissions.ManageFeatures) - .LocalNav() + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Features"], + S["Features"].PrefixPosition(), + deployment => deployment.Action("Features", "Admin", _routeValues).Permission(Permissions.ManageFeatures).LocalNav() ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Features/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Features/Controllers/AdminController.cs index ff3b0053fa6..6f162b089cf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Features/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Features/Controllers/AdminController.cs @@ -40,7 +40,8 @@ public AdminController( IOptions adminOptions, INotifier notifier, IStringLocalizer stringLocalizer, - IHtmlLocalizer htmlLocalizer) + IHtmlLocalizer htmlLocalizer + ) { _authorizationService = authorizationService; _shellHost = shellHost; @@ -63,18 +64,21 @@ public async Task Features(string tenant) var viewModel = new FeaturesViewModel(); - await ExecuteAsync(tenant, async (featureService, settings, isProxy) => - { - // If the user provide an invalid tenant value, we'll set it to null so it's not available on the next request. - if (isProxy) + await ExecuteAsync( + tenant, + async (featureService, settings, isProxy) => { - viewModel.IsProxy = true; - tenant = settings.Name; - viewModel.Name = settings.Name; + // If the user provide an invalid tenant value, we'll set it to null so it's not available on the next request. + if (isProxy) + { + viewModel.IsProxy = true; + tenant = settings.Name; + viewModel.Name = settings.Name; + } + + viewModel.Features = await featureService.GetModuleFeaturesAsync(); } - - viewModel.Features = await featureService.GetModuleFeaturesAsync(); - }); + ); return View(viewModel); } @@ -95,12 +99,20 @@ public async Task Features(BulkActionViewModel model, bool? force, if (ModelState.IsValid) { - await ExecuteAsync(tenant, async (featureService, settings, isProxy) => - { - var availableFeatures = await featureService.GetAvailableFeatures(model.FeatureIds); - - await featureService.EnableOrDisableFeaturesAsync(availableFeatures, model.BulkAction, force, async (features, isEnabled) => await NotifyAsync(features, isEnabled)); - }); + await ExecuteAsync( + tenant, + async (featureService, settings, isProxy) => + { + var availableFeatures = await featureService.GetAvailableFeatures(model.FeatureIds); + + await featureService.EnableOrDisableFeaturesAsync( + availableFeatures, + model.BulkAction, + force, + async (features, isEnabled) => await NotifyAsync(features, isEnabled) + ); + } + ); } return RedirectToAction(nameof(Features)); @@ -117,26 +129,34 @@ public async Task Disable(string id, string tenant) var found = false; - await ExecuteAsync(tenant, async (featureService, settings, isProxy) => - { - var feature = await featureService.GetAvailableFeature(id); - - if (feature == null) + await ExecuteAsync( + tenant, + async (featureService, settings, isProxy) => { - return; - } + var feature = await featureService.GetAvailableFeature(id); - found = true; + if (feature == null) + { + return; + } - if (!isProxy && id == FeaturesConstants.FeatureId) - { - await _notifier.ErrorAsync(H["This feature is always enabled and cannot be disabled."]); + found = true; - return; - } + if (!isProxy && id == FeaturesConstants.FeatureId) + { + await _notifier.ErrorAsync(H["This feature is always enabled and cannot be disabled."]); + + return; + } - await featureService.EnableOrDisableFeaturesAsync(new[] { feature }, FeaturesBulkAction.Disable, true, async (features, isEnabled) => await NotifyAsync(features, isEnabled)); - }); + await featureService.EnableOrDisableFeaturesAsync( + new[] { feature }, + FeaturesBulkAction.Disable, + true, + async (features, isEnabled) => await NotifyAsync(features, isEnabled) + ); + } + ); if (!found) { @@ -157,19 +177,27 @@ public async Task Enable(string id, string tenant) var found = false; - await ExecuteAsync(tenant, async (featureService, settings, isProxy) => - { - var feature = await featureService.GetAvailableFeature(id); - - if (feature == null) + await ExecuteAsync( + tenant, + async (featureService, settings, isProxy) => { - return; - } + var feature = await featureService.GetAvailableFeature(id); - found = true; + if (feature == null) + { + return; + } - await featureService.EnableOrDisableFeaturesAsync(new[] { feature }, FeaturesBulkAction.Enable, true, async (features, isEnabled) => await NotifyAsync(features, isEnabled)); - }); + found = true; + + await featureService.EnableOrDisableFeaturesAsync( + new[] { feature }, + FeaturesBulkAction.Enable, + true, + async (features, isEnabled) => await NotifyAsync(features, isEnabled) + ); + } + ); if (!found) { @@ -181,11 +209,13 @@ await ExecuteAsync(tenant, async (featureService, settings, isProxy) => private async Task ExecuteAsync(string tenant, Func action) { - if (_shellSettings.IsDefaultShell() && - !string.IsNullOrWhiteSpace(tenant) && - _shellHost.TryGetSettings(tenant, out var settings) && - !settings.IsDefaultShell() && - settings.IsRunning()) + if ( + _shellSettings.IsDefaultShell() + && !string.IsNullOrWhiteSpace(tenant) + && _shellHost.TryGetSettings(tenant, out var settings) + && !settings.IsDefaultShell() + && settings.IsRunning() + ) { // At this point, we know that this request is being executed from the Default tenant. // Also, we were able to find a matching and running tenant that isn't the Default one. diff --git a/src/OrchardCore.Modules/OrchardCore.Features/Deployment/AllFeaturesDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Features/Deployment/AllFeaturesDeploymentSource.cs index 882fceed3fd..d48ada59e2b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Features/Deployment/AllFeaturesDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Features/Deployment/AllFeaturesDeploymentSource.cs @@ -25,11 +25,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan } var features = await _moduleService.GetAvailableFeaturesAsync(); - var featureStep = new JsonObject - { - ["name"] = "Feature", - ["enable"] = JNode.FromObject(features.Where(f => f.IsEnabled).Select(f => f.Descriptor.Id).ToArray()), - }; + var featureStep = new JsonObject { ["name"] = "Feature", ["enable"] = JNode.FromObject(features.Where(f => f.IsEnabled).Select(f => f.Descriptor.Id).ToArray()), }; if (!allFeaturesStep.IgnoreDisabledFeatures) { diff --git a/src/OrchardCore.Modules/OrchardCore.Features/Deployment/AllFeaturesDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Features/Deployment/AllFeaturesDeploymentStepDriver.cs index 3122db0c24c..40049ba17f3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Features/Deployment/AllFeaturesDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Features/Deployment/AllFeaturesDeploymentStepDriver.cs @@ -11,19 +11,22 @@ public class AllFeaturesDeploymentStepDriver : DisplayDriver("AllFeaturesDeploymentStep_Fields_Edit", model => - { - model.IgnoreDisabledFeatures = step.IgnoreDisabledFeatures; - }).Location("Content"); + return Initialize( + "AllFeaturesDeploymentStep_Fields_Edit", + model => + { + model.IgnoreDisabledFeatures = step.IgnoreDisabledFeatures; + } + ) + .Location("Content"); } public override async Task UpdateAsync(AllFeaturesDeploymentStep step, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Features/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Features/Manifest.cs index 4738ab27b7c..7277897c957 100644 --- a/src/OrchardCore.Modules/OrchardCore.Features/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Features/Manifest.cs @@ -1,12 +1,7 @@ using OrchardCore.Features; using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Features", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Features", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = FeaturesConstants.FeatureId, diff --git a/src/OrchardCore.Modules/OrchardCore.Features/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Features/Permissions.cs index 64ffdff25e5..7536cc1f592 100644 --- a/src/OrchardCore.Modules/OrchardCore.Features/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Features/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageFeatures = new("ManageFeatures", "Manage Features"); - private readonly IEnumerable _allPermissions = - [ - ManageFeatures, - ]; + private readonly IEnumerable _allPermissions = [ManageFeatures,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Features/Services/ModuleService.cs b/src/OrchardCore.Modules/OrchardCore.Features/Services/ModuleService.cs index 051791852df..370649f4c8c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Features/Services/ModuleService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Features/Services/ModuleService.cs @@ -17,11 +17,7 @@ public class ModuleService : IModuleService private readonly INotifier _notifier; protected readonly IHtmlLocalizer H; - public ModuleService( - IExtensionManager extensionManager, - IShellFeaturesManager shellFeaturesManager, - IHtmlLocalizer htmlLocalizer, - INotifier notifier) + public ModuleService(IExtensionManager extensionManager, IShellFeaturesManager shellFeaturesManager, IHtmlLocalizer htmlLocalizer, INotifier notifier) { _notifier = notifier; _extensionManager = extensionManager; @@ -35,14 +31,11 @@ public ModuleService( /// An enumeration of the available features together with its state (enabled / disabled). public async Task> GetAvailableFeaturesAsync() { - var enabledFeatures = - await _shellFeaturesManager.GetEnabledFeaturesAsync(); + var enabledFeatures = await _shellFeaturesManager.GetEnabledFeaturesAsync(); var availableFeatures = _extensionManager.GetFeatures(); - return availableFeatures - .Select(f => AssembleModuleFromDescriptor(f, enabledFeatures - .Any(sf => sf.Id == f.Id))); + return availableFeatures.Select(f => AssembleModuleFromDescriptor(f, enabledFeatures.Any(sf => sf.Id == f.Id))); } /// @@ -61,9 +54,7 @@ public Task EnableFeaturesAsync(IEnumerable featureIds) /// Boolean parameter indicating if the feature should enable it's dependencies if required or fail otherwise. public async Task EnableFeaturesAsync(IEnumerable featureIds, bool force) { - var featuresToEnable = _extensionManager - .GetFeatures() - .Where(x => featureIds.Contains(x.Id)); + var featuresToEnable = _extensionManager.GetFeatures().Where(x => featureIds.Contains(x.Id)); var enabledFeatures = await _shellFeaturesManager.EnableFeaturesAsync(featuresToEnable, force); foreach (var enabledFeature in enabledFeatures) @@ -88,9 +79,7 @@ public Task DisableFeaturesAsync(IEnumerable featureIds) /// Boolean parameter indicating if the feature should disable the features which depend on it if required or fail otherwise. public async Task DisableFeaturesAsync(IEnumerable featureIds, bool force) { - var featuresToDisable = _extensionManager - .GetFeatures() - .Where(x => featureIds.Contains(x.Id)); + var featuresToDisable = _extensionManager.GetFeatures().Where(x => featureIds.Contains(x.Id)); var features = await _shellFeaturesManager.DisableFeaturesAsync(featuresToDisable, force); foreach (var feature in features) @@ -134,11 +123,7 @@ public async Task DisableFeaturesAsync(IEnumerable featureIds, bool forc private static ModuleFeature AssembleModuleFromDescriptor(IFeatureInfo featureInfo, bool isEnabled) { - return new ModuleFeature - { - Descriptor = featureInfo, - IsEnabled = isEnabled - }; + return new ModuleFeature { Descriptor = featureInfo, IsEnabled = isEnabled }; } // private void GenerateWarning(string messageFormat, string featureName, IEnumerable featuresInQuestion) { diff --git a/src/OrchardCore.Modules/OrchardCore.Feeds/Controllers/FeedController.cs b/src/OrchardCore.Modules/OrchardCore.Feeds/Controllers/FeedController.cs index 8607f8d1103..4a49948b948 100644 --- a/src/OrchardCore.Modules/OrchardCore.Feeds/Controllers/FeedController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Feeds/Controllers/FeedController.cs @@ -21,7 +21,8 @@ public FeedController( IEnumerable feedFormatProviders, IFeedItemBuilder feedItemBuilder, IServiceProvider serviceProvider, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _feedQueryProviders = feedQueryProviders; _feedFormatProviders = feedFormatProviders; @@ -53,33 +54,30 @@ public async Task Index(string format) queryMatches.Add(await provider.MatchAsync(context)); } - var bestQueryMatch = queryMatches - .Where(match => match != null && match.FeedQuery != null) - .MaxBy(match => match.Priority); + var bestQueryMatch = queryMatches.Where(match => match != null && match.FeedQuery != null).MaxBy(match => match.Priority); if (bestQueryMatch == null || bestQueryMatch.FeedQuery == null) { return NotFound(); } - var document = await context.Builder.ProcessAsync(context, async () => - { - await bestQueryMatch.FeedQuery.ExecuteAsync(context); + var document = await context.Builder.ProcessAsync( + context, + async () => + { + await bestQueryMatch.FeedQuery.ExecuteAsync(context); - await _feedItemBuilder.PopulateAsync(context); + await _feedItemBuilder.PopulateAsync(context); - foreach (var contextualizer in context.Response.Contextualizers) - { - if (ControllerContext != null) + foreach (var contextualizer in context.Response.Contextualizers) { - contextualizer(new ContextualizeContext + if (ControllerContext != null) { - ServiceProvider = _serviceProvider, - Url = Url - }); + contextualizer(new ContextualizeContext { ServiceProvider = _serviceProvider, Url = Url }); + } } } - }); + ); return Content(document.ToString(), "text/xml"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Controllers/AdminController.cs index 1f09fda5cc8..a94901cd268 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Controllers/AdminController.cs @@ -29,7 +29,8 @@ public AdminController( IContentDefinitionManager contentDefinitionManager, IContentItemDisplayManager contentItemDisplayManager, IShapeFactory shapeFactory, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _contentManager = contentManager; _contentDefinitionManager = contentDefinitionManager; @@ -38,7 +39,17 @@ public AdminController( _updateModelAccessor = updateModelAccessor; } - public async Task BuildEditor(string id, string prefix, string prefixesName, string contentTypesName, string contentItemsName, string targetId, bool flowMetadata, string parentContentType, string partName) + public async Task BuildEditor( + string id, + string prefix, + string prefixesName, + string contentTypesName, + string contentItemsName, + string targetId, + bool flowMetadata, + string parentContentType, + string partName + ) { if (string.IsNullOrWhiteSpace(id)) { @@ -100,10 +111,7 @@ public async Task BuildEditor(string id, string prefix, string pr contentCard.ColumnSize = colSize; } - var model = new BuildEditorViewModel - { - EditorShape = contentCard - }; + var model = new BuildEditorViewModel { EditorShape = contentCard }; return View("Display", model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/BagPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/BagPartDisplayDriver.cs index 18019918baf..95bb8b701b7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/BagPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/BagPartDisplayDriver.cs @@ -43,7 +43,7 @@ public BagPartDisplayDriver( INotifier notifier, IHtmlLocalizer htmlLocalizer, IAuthorizationService authorizationService - ) + ) { _contentDefinitionManager = contentDefinitionManager; _contentManager = contentManager; @@ -59,27 +59,33 @@ public override IDisplayResult Display(BagPart bagPart, BuildPartDisplayContext { var hasItems = bagPart.ContentItems.Count > 0; - return Initialize(hasItems ? "BagPart" : "BagPart_Empty", m => - { - m.BagPart = bagPart; - m.BuildPartDisplayContext = context; - m.Settings = context.TypePartDefinition.GetSettings(); - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + hasItems ? "BagPart" : "BagPart_Empty", + m => + { + m.BagPart = bagPart; + m.BuildPartDisplayContext = context; + m.Settings = context.TypePartDefinition.GetSettings(); + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(BagPart bagPart, BuildPartEditorContext context) { - return Initialize(GetEditorShapeType(context), async m => - { - var contentDefinitionManager = _serviceProvider.GetRequiredService(); + return Initialize( + GetEditorShapeType(context), + async m => + { + var contentDefinitionManager = _serviceProvider.GetRequiredService(); - m.BagPart = bagPart; - m.Updater = context.Updater; - m.ContainedContentTypeDefinitions = await GetContainedContentTypesAsync(context.TypePartDefinition); - m.AccessibleWidgets = await GetAccessibleWidgetsAsync(bagPart.ContentItems, contentDefinitionManager); - }); + m.BagPart = bagPart; + m.Updater = context.Updater; + m.ContainedContentTypeDefinitions = await GetContainedContentTypesAsync(context.TypePartDefinition); + m.AccessibleWidgets = await GetAccessibleWidgetsAsync(bagPart.ContentItems, contentDefinitionManager); + } + ); } public override async Task UpdateAsync(BagPart part, UpdatePartEditorContext context) @@ -182,9 +188,15 @@ private async Task> GetAccessibleWidgetsAsyn if (contentTypeDefinition == null) { - _logger.LogWarning("The Widget content item with id {ContentItemId} has no matching {ContentType} content type definition.", contentItem.ContentItemId, contentItem.ContentType); + _logger.LogWarning( + "The Widget content item with id {ContentItemId} has no matching {ContentType} content type definition.", + contentItem.ContentItemId, + contentItem.ContentType + ); - await _notifier.WarningAsync(H["The Widget content item with id {0} has no matching {1} content type definition.", contentItem.ContentItemId, contentItem.ContentType]); + await _notifier.WarningAsync( + H["The Widget content item with id {0} has no matching {1} content type definition.", contentItem.ContentItemId, contentItem.ContentType] + ); continue; } @@ -219,8 +231,8 @@ private async Task AuthorizeAsync(IContentDefinitionManager contentDefinit return await AuthorizeAsync(permission, contentItem); } - private Task AuthorizeAsync(Permission permission, ContentItem contentItem) - => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, permission, contentItem); + private Task AuthorizeAsync(Permission permission, ContentItem contentItem) => + _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, permission, contentItem); private async Task> GetContainedContentTypesAsync(ContentTypePartDefinition typePartDefinition) { @@ -229,8 +241,9 @@ private async Task> GetContainedContentTypesA if (settings.ContainedStereotypes != null && settings.ContainedStereotypes.Length > 0) { - contentTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(contentType => contentType.HasStereotype() && settings.ContainedStereotypes.Contains(contentType.GetStereotype(), StringComparer.OrdinalIgnoreCase)); + contentTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(contentType => + contentType.HasStereotype() && settings.ContainedStereotypes.Contains(contentType.GetStereotype(), StringComparer.OrdinalIgnoreCase) + ); } else if (settings.ContainedContentTypes != null && settings.ContainedContentTypes.Length > 0) { diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/FlowMetadataDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/FlowMetadataDisplayDriver.cs index a2e723157a4..3df458563e5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/FlowMetadataDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/FlowMetadataDisplayDriver.cs @@ -18,11 +18,15 @@ public override IDisplayResult Edit(ContentItem model, IUpdateModel updater) return null; } - return Initialize("FlowMetadata_Edit", m => - { - m.Alignment = flowMetadata.Alignment; - m.Size = flowMetadata.Size; - }).Location("Footer"); + return Initialize( + "FlowMetadata_Edit", + m => + { + m.Alignment = flowMetadata.Alignment; + m.Size = flowMetadata.Size; + } + ) + .Location("Footer"); } public override async Task UpdateAsync(ContentItem contentItem, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/FlowPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/FlowPartDisplayDriver.cs index 9f361066cd5..6a6404a526d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/FlowPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Drivers/FlowPartDisplayDriver.cs @@ -34,7 +34,7 @@ public FlowPartDisplayDriver( IHtmlLocalizer htmlLocalizer, INotifier notifier, ILogger logger - ) + ) { _contentDefinitionManager = contentDefinitionManager; _contentManager = contentManager; @@ -48,48 +48,64 @@ public override IDisplayResult Display(FlowPart flowPart, BuildPartDisplayContex { var hasItems = flowPart.Widgets.Count > 0; - return Initialize(hasItems ? "FlowPart" : "FlowPart_Empty", m => - { - m.FlowPart = flowPart; - m.BuildPartDisplayContext = context; - }) - .Location("Detail", "Content"); + return Initialize( + hasItems ? "FlowPart" : "FlowPart_Empty", + m => + { + m.FlowPart = flowPart; + m.BuildPartDisplayContext = context; + } + ) + .Location("Detail", "Content"); } public override IDisplayResult Edit(FlowPart flowPart, BuildPartEditorContext context) { - return Initialize(GetEditorShapeType(context), async model => - { - var containedContentTypes = await GetContainedContentTypesAsync(context.TypePartDefinition); - var notify = false; + return Initialize( + GetEditorShapeType(context), + async model => + { + var containedContentTypes = await GetContainedContentTypesAsync(context.TypePartDefinition); + var notify = false; - var existingWidgets = new List(); + var existingWidgets = new List(); - foreach (var widget in flowPart.Widgets) - { - if (!containedContentTypes.Any(c => c.Name == widget.ContentType)) + foreach (var widget in flowPart.Widgets) { - _logger.LogWarning("The Widget content item with id {ContentItemId} has no matching {ContentType} content type definition.", widget.ContentItem.ContentItemId, widget.ContentItem.ContentType); - await _notifier.WarningAsync(H["The Widget content item with id {0} has no matching {1} content type definition.", widget.ContentItem.ContentItemId, widget.ContentItem.ContentType]); - notify = true; + if (!containedContentTypes.Any(c => c.Name == widget.ContentType)) + { + _logger.LogWarning( + "The Widget content item with id {ContentItemId} has no matching {ContentType} content type definition.", + widget.ContentItem.ContentItemId, + widget.ContentItem.ContentType + ); + await _notifier.WarningAsync( + H[ + "The Widget content item with id {0} has no matching {1} content type definition.", + widget.ContentItem.ContentItemId, + widget.ContentItem.ContentType + ] + ); + notify = true; + } + else + { + existingWidgets.Add(widget); + } } - else + + flowPart.Widgets = existingWidgets; + + if (notify) { - existingWidgets.Add(widget); + await _notifier.WarningAsync(H["Publishing this content item may erase created content. Fix any content type issues beforehand."]); } - } - flowPart.Widgets = existingWidgets; - - if (notify) - { - await _notifier.WarningAsync(H["Publishing this content item may erase created content. Fix any content type issues beforehand."]); + model.FlowPart = flowPart; + model.Updater = context.Updater; + model.ContainedContentTypeDefinitions = containedContentTypes; } - - model.FlowPart = flowPart; - model.Updater = context.Updater; - model.ContainedContentTypeDefinitions = containedContentTypes; - }); + ); } public override async Task UpdateAsync(FlowPart part, UpdatePartEditorContext context) @@ -134,12 +150,10 @@ private async Task> GetContainedContentTypesA if (settings?.ContainedContentTypes?.Length == 0) { - return (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(t => t.StereotypeEquals("Widget")); + return (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(t => t.StereotypeEquals("Widget")); } - return (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(t => settings.ContainedContentTypes.Contains(t.Name) && t.StereotypeEquals("Widget")); + return (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(t => settings.ContainedContentTypes.Contains(t.Name) && t.StereotypeEquals("Widget")); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/GraphQL/FlowMetadataContentTypeBuilder.cs b/src/OrchardCore.Modules/OrchardCore.Flows/GraphQL/FlowMetadataContentTypeBuilder.cs index 79a62f2e601..a2b969092f2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/GraphQL/FlowMetadataContentTypeBuilder.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/GraphQL/FlowMetadataContentTypeBuilder.cs @@ -15,8 +15,7 @@ public void Build(FieldType contentQuery, ContentTypeDefinition contentTypeDefin return; } - contentItemType.Field("metadata") - .Resolve(context => context.Source.As()); + contentItemType.Field("metadata").Resolve(context => context.Source.As()); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/GraphQL/FlowPartQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Flows/GraphQL/FlowPartQueryObjectType.cs index 7f3019906be..68551326780 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/GraphQL/FlowPartQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/GraphQL/FlowPartQueryObjectType.cs @@ -12,9 +12,7 @@ public FlowPartQueryObjectType(IStringLocalizer S) Name = "FlowPart"; Description = S["A FlowPart allows to add content items directly within another content item"]; - Field>("widgets") - .Description("The widgets.") - .Resolve(context => context.Source.Widgets); + Field>("widgets").Description("The widgets.").Resolve(context => context.Source.Widgets); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Handlers/BagPartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Handlers/BagPartHandler.cs index f26e5f44f01..3e6cf371bcc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Handlers/BagPartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Handlers/BagPartHandler.cs @@ -12,12 +12,14 @@ public override Task GetContentItemAspectAsync(ContentItemAspectContext context, { return context.ForAsync(aspect => { - aspect.Accessors.Add((jsonObject) => - { - // Content.Path contains the accessor for named bag parts and typed bag parts. - var jContent = (JsonObject)part.Content; - return jsonObject[jContent.GetNormalizedPath()]["ContentItems"] as JsonArray; - }); + aspect.Accessors.Add( + (jsonObject) => + { + // Content.Path contains the accessor for named bag parts and typed bag parts. + var jContent = (JsonObject)part.Content; + return jsonObject[jContent.GetNormalizedPath()]["ContentItems"] as JsonArray; + } + ); return Task.CompletedTask; }); diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/BagPartIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/BagPartIndexHandler.cs index 928643d7994..83205094fe3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/BagPartIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/BagPartIndexHandler.cs @@ -33,10 +33,7 @@ public override async Task BuildIndexAsync(BagPart bagPart, BuildPartIndexContex { foreach (var contentItem in bagPart.ContentItems) { - var keys = new List - { - contentItem.ContentType, - }; + var keys = new List { contentItem.ContentType, }; foreach (var key in context.Keys) { diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/FlowPartIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/FlowPartIndexHandler.cs index 11597f9d0f3..6eb3c1c5fa4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/FlowPartIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/FlowPartIndexHandler.cs @@ -33,10 +33,7 @@ public override async Task BuildIndexAsync(FlowPart FlowPart, BuildPartIndexCont { foreach (var contentItem in FlowPart.Widgets) { - var keys = new List - { - contentItem.ContentType, - }; + var keys = new List { contentItem.ContentType, }; foreach (var key in context.Keys) { diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Manifest.cs index 1cd397e757d..1c5e78a4d5a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Manifest.cs @@ -1,11 +1,6 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Flows", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Flows", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Flows", diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Migrations.cs index d0b98cfcf6b..0ff429df6d9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Migrations.cs @@ -17,14 +17,15 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("FlowPart", builder => builder - .Attachable() - .WithDescription("Provides a customizable body for your content item where you can build a content structure with widgets.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "FlowPart", + builder => builder.Attachable().WithDescription("Provides a customizable body for your content item where you can build a content structure with widgets.") + ); - await _contentDefinitionManager.AlterPartDefinitionAsync("BagPart", builder => builder - .Attachable() - .Reusable() - .WithDescription("Provides a collection behavior for your content item where you can place other content items.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "BagPart", + builder => builder.Attachable().Reusable().WithDescription("Provides a collection behavior for your content item where you can place other content items.") + ); // Shortcut other migration steps on new content definition schemas. return 3; @@ -33,10 +34,10 @@ await _contentDefinitionManager.AlterPartDefinitionAsync("BagPart", builder => b // This code can be removed in a later version. public async Task UpdateFrom1Async() { - await _contentDefinitionManager.AlterPartDefinitionAsync("BagPart", builder => builder - .Attachable() - .Reusable() - .WithDescription("Provides a collection behavior for your content item where you can place other content items.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "BagPart", + builder => builder.Attachable().Reusable().WithDescription("Provides a collection behavior for your content item where you can place other content items.") + ); return 2; } diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Settings/BagPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Settings/BagPartSettingsDisplayDriver.cs index 30bfeb943f5..79ffb2ba9a0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Settings/BagPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Settings/BagPartSettingsDisplayDriver.cs @@ -17,9 +17,7 @@ public class BagPartSettingsDisplayDriver : ContentTypePartDefinitionDisplayDriv private readonly IContentDefinitionManager _contentDefinitionManager; protected readonly IStringLocalizer S; - public BagPartSettingsDisplayDriver( - IContentDefinitionManager contentDefinitionManager, - IStringLocalizer localizer) + public BagPartSettingsDisplayDriver(IContentDefinitionManager contentDefinitionManager, IStringLocalizer localizer) { _contentDefinitionManager = contentDefinitionManager; S = localizer; @@ -27,21 +25,26 @@ public BagPartSettingsDisplayDriver( public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("BagPartSettings_Edit", async model => - { - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + "BagPartSettings_Edit", + async model => + { + var settings = contentTypePartDefinition.GetSettings(); - model.BagPartSettings = settings; - model.ContainedContentTypes = model.BagPartSettings.ContainedContentTypes; - model.DisplayType = model.BagPartSettings.DisplayType; - model.ContentTypes = []; - model.Source = settings.ContainedStereotypes != null && settings.ContainedStereotypes.Length > 0 ? BagPartSettingType.Stereotypes : BagPartSettingType.ContentTypes; - model.Stereotypes = string.Join(',', settings.ContainedStereotypes ?? []); - foreach (var contentTypeDefinition in await _contentDefinitionManager.ListTypeDefinitionsAsync()) - { - model.ContentTypes.Add(contentTypeDefinition.Name, contentTypeDefinition.DisplayName); - } - }).Location("Content"); + model.BagPartSettings = settings; + model.ContainedContentTypes = model.BagPartSettings.ContainedContentTypes; + model.DisplayType = model.BagPartSettings.DisplayType; + model.ContentTypes = []; + model.Source = + settings.ContainedStereotypes != null && settings.ContainedStereotypes.Length > 0 ? BagPartSettingType.Stereotypes : BagPartSettingType.ContentTypes; + model.Stereotypes = string.Join(',', settings.ContainedStereotypes ?? []); + foreach (var contentTypeDefinition in await _contentDefinitionManager.ListTypeDefinitionsAsync()) + { + model.ContentTypes.Add(contentTypeDefinition.Name, contentTypeDefinition.DisplayName); + } + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) @@ -75,12 +78,14 @@ private void SetStereoTypes(UpdateTypePartEditorContext context, BagPartSettings return; } - context.Builder.WithSettings(new BagPartSettings - { - ContainedContentTypes = [], - ContainedStereotypes = model.Stereotypes.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries), - DisplayType = model.DisplayType - }); + context.Builder.WithSettings( + new BagPartSettings + { + ContainedContentTypes = [], + ContainedStereotypes = model.Stereotypes.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries), + DisplayType = model.DisplayType + } + ); } private void SetContentTypes(UpdateTypePartEditorContext context, BagPartSettingsViewModel model) @@ -92,12 +97,14 @@ private void SetContentTypes(UpdateTypePartEditorContext context, BagPartSetting return; } - context.Builder.WithSettings(new BagPartSettings - { - ContainedContentTypes = model.ContainedContentTypes, - ContainedStereotypes = [], - DisplayType = model.DisplayType - }); + context.Builder.WithSettings( + new BagPartSettings + { + ContainedContentTypes = model.ContainedContentTypes, + ContainedStereotypes = [], + DisplayType = model.DisplayType + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Settings/FlowPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Settings/FlowPartSettingsDisplayDriver.cs index c2f02f9eae1..ab37918c3ae 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Settings/FlowPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Settings/FlowPartSettingsDisplayDriver.cs @@ -21,17 +21,21 @@ public FlowPartSettingsDisplayDriver(IContentDefinitionManager contentDefinition public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("FlowPartSettings_Edit", async model => - { - model.FlowPartSettings = contentTypePartDefinition.GetSettings(); - model.ContainedContentTypes = model.FlowPartSettings.ContainedContentTypes; - model.ContentTypes = []; - - foreach (var contentTypeDefinition in (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(t => t.GetStereotype() == "Widget")) - { - model.ContentTypes.Add(contentTypeDefinition.Name, contentTypeDefinition.DisplayName); - } - }).Location("Content"); + return Initialize( + "FlowPartSettings_Edit", + async model => + { + model.FlowPartSettings = contentTypePartDefinition.GetSettings(); + model.ContainedContentTypes = model.FlowPartSettings.ContainedContentTypes; + model.ContentTypes = []; + + foreach (var contentTypeDefinition in (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(t => t.GetStereotype() == "Widget")) + { + model.ContentTypes.Add(contentTypeDefinition.Name, contentTypeDefinition.DisplayName); + } + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) @@ -40,10 +44,7 @@ public override async Task UpdateAsync(ContentTypePartDefinition await context.Updater.TryUpdateModelAsync(model, Prefix, m => m.ContainedContentTypes); - context.Builder.WithSettings(new FlowPartSettings - { - ContainedContentTypes = model.ContainedContentTypes - }); + context.Builder.WithSettings(new FlowPartSettings { ContainedContentTypes = model.ContainedContentTypes }); return Edit(contentTypePartDefinition, context.Updater); } diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Startup.cs index 58884ad145d..9ab505f2e3a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Startup.cs @@ -35,17 +35,14 @@ public override void ConfigureServices(IServiceCollection services) }); // Flow Part - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddScoped(); services.AddScoped(); services.AddScoped(); // Bag Part - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Activities/HttpRedirectToFormLocationTask.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Activities/HttpRedirectToFormLocationTask.cs index b1e6d64b7d5..3cb03c7080c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Activities/HttpRedirectToFormLocationTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Activities/HttpRedirectToFormLocationTask.cs @@ -14,10 +14,7 @@ public class HttpRedirectToFormLocationTask : TaskActivity stringLocalizer - ) + public HttpRedirectToFormLocationTask(IHttpContextAccessor httpContextAccessor, IStringLocalizer stringLocalizer) { _httpContextAccessor = httpContextAccessor; S = stringLocalizer; @@ -27,8 +24,7 @@ IStringLocalizer stringLocalizer public override LocalizedString Category => S["HTTP"]; - public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) - => Outcomes(S["Done"], S["Failed"]); + public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) => Outcomes(S["Done"], S["Failed"]); public string FormLocationKey { @@ -38,8 +34,7 @@ public string FormLocationKey public override Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - if (workflowContext.Output.TryGetValue(WorkflowConstants.HttpFormLocationOutputKeyName, out var obj) - && obj is Dictionary formLocations) + if (workflowContext.Output.TryGetValue(WorkflowConstants.HttpFormLocationOutputKeyName, out var obj) && obj is Dictionary formLocations) { if (formLocations.TryGetValue(FormLocationKey, out var path)) { diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ButtonPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ButtonPartDisplayDriver.cs index 07222857eca..15eefc22bc6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ButtonPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ButtonPartDisplayDriver.cs @@ -16,14 +16,17 @@ public override IDisplayResult Display(ButtonPart part) public override IDisplayResult Edit(ButtonPart part) { - return Initialize("ButtonPart_Fields_Edit", m => - { - m.Text = part.Text; - m.Type = part.Type; - }); + return Initialize( + "ButtonPart_Fields_Edit", + m => + { + m.Text = part.Text; + m.Type = part.Type; + } + ); } - public async override Task UpdateAsync(ButtonPart part, IUpdateModel updater) + public override async Task UpdateAsync(ButtonPart part, IUpdateModel updater) { var viewModel = new ButtonPartEditViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementLabelPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementLabelPartDisplayDriver.cs index b525bb75750..38f5ac43006 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementLabelPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementLabelPartDisplayDriver.cs @@ -16,14 +16,17 @@ public override IDisplayResult Display(FormElementLabelPart part) public override IDisplayResult Edit(FormElementLabelPart part) { - return Initialize("FormElementLabelPart_Fields_Edit", m => - { - m.Label = part.Label; - m.LabelOption = part.Option; - }); + return Initialize( + "FormElementLabelPart_Fields_Edit", + m => + { + m.Label = part.Label; + m.LabelOption = part.Option; + } + ); } - public async override Task UpdateAsync(FormElementLabelPart part, IUpdateModel updater) + public override async Task UpdateAsync(FormElementLabelPart part, IUpdateModel updater) { var viewModel = new FormElementLabelPartViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementPartDisplayDriver.cs index e2399cf8a27..adff34a9ef1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementPartDisplayDriver.cs @@ -11,13 +11,16 @@ public class FormElementPartDisplayDriver : ContentPartDisplayDriver("FormElementPart_Fields_Edit", m => - { - m.Id = part.Id; - }); + return Initialize( + "FormElementPart_Fields_Edit", + m => + { + m.Id = part.Id; + } + ); } - public async override Task UpdateAsync(FormElementPart part, IUpdateModel updater) + public override async Task UpdateAsync(FormElementPart part, IUpdateModel updater) { var viewModel = new FormElementPartEditViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementValidationPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementValidationPartDisplayDriver.cs index aa8b227e548..f65f665d65a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementValidationPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormElementValidationPartDisplayDriver.cs @@ -16,13 +16,16 @@ public override IDisplayResult Display(FormElementValidationPart part) public override IDisplayResult Edit(FormElementValidationPart part) { - return Initialize("FormElementValidationPart_Fields_Edit", m => - { - m.ValidationOption = part.Option; - }); + return Initialize( + "FormElementValidationPart_Fields_Edit", + m => + { + m.ValidationOption = part.Option; + } + ); } - public async override Task UpdateAsync(FormElementValidationPart part, IUpdateModel updater) + public override async Task UpdateAsync(FormElementValidationPart part, IUpdateModel updater) { var viewModel = new FormElementValidationPartViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormInputElementPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormInputElementPartDisplayDriver.cs index eb689235623..e45c5fd2513 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormInputElementPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormInputElementPartDisplayDriver.cs @@ -20,13 +20,16 @@ public FormInputElementPartDisplayDriver(IStringLocalizer("FormInputElementPart_Fields_Edit", m => - { - m.Name = part.Name; - }); + return Initialize( + "FormInputElementPart_Fields_Edit", + m => + { + m.Name = part.Name; + } + ); } - public async override Task UpdateAsync(FormInputElementPart part, IUpdateModel updater) + public override async Task UpdateAsync(FormInputElementPart part, IUpdateModel updater) { var viewModel = new FormInputElementPartEditViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormPartDisplayDriver.cs index 3816418a7dd..db8544a287d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/FormPartDisplayDriver.cs @@ -11,18 +11,21 @@ public class FormPartDisplayDriver : ContentPartDisplayDriver { public override IDisplayResult Edit(FormPart part) { - return Initialize("FormPart_Fields_Edit", m => - { - m.Action = part.Action; - m.Method = part.Method; - m.WorkflowTypeId = part.WorkflowTypeId; - m.EncType = part.EncType; - m.EnableAntiForgeryToken = part.EnableAntiForgeryToken; - m.SaveFormLocation = part.SaveFormLocation; - }); + return Initialize( + "FormPart_Fields_Edit", + m => + { + m.Action = part.Action; + m.Method = part.Method; + m.WorkflowTypeId = part.WorkflowTypeId; + m.EncType = part.EncType; + m.EnableAntiForgeryToken = part.EnableAntiForgeryToken; + m.SaveFormLocation = part.SaveFormLocation; + } + ); } - public async override Task UpdateAsync(FormPart part, IUpdateModel updater) + public override async Task UpdateAsync(FormPart part, IUpdateModel updater) { var viewModel = new FormPartEditViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/InputPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/InputPartDisplayDriver.cs index cd3577d3107..5ca00a15df5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/InputPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/InputPartDisplayDriver.cs @@ -16,15 +16,18 @@ public override IDisplayResult Display(InputPart part) public override IDisplayResult Edit(InputPart part) { - return Initialize("InputPart_Fields_Edit", m => - { - m.Placeholder = part.Placeholder; - m.DefaultValue = part.DefaultValue; - m.Type = part.Type; - }); + return Initialize( + "InputPart_Fields_Edit", + m => + { + m.Placeholder = part.Placeholder; + m.DefaultValue = part.DefaultValue; + m.Type = part.Type; + } + ); } - public async override Task UpdateAsync(InputPart part, IUpdateModel updater) + public override async Task UpdateAsync(InputPart part, IUpdateModel updater) { var viewModel = new InputPartEditViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/LabelPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/LabelPartDisplayDriver.cs index 23cfe8d49a9..b2e1c2f5f02 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/LabelPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/LabelPartDisplayDriver.cs @@ -17,10 +17,13 @@ public override IDisplayResult Display(LabelPart part) public override IDisplayResult Edit(LabelPart part, BuildPartEditorContext context) { - return Initialize("LabelPart_Fields_Edit", m => - { - m.For = part.For; - }); + return Initialize( + "LabelPart_Fields_Edit", + m => + { + m.For = part.For; + } + ); } public override async Task UpdateAsync(LabelPart part, IUpdateModel updater, UpdatePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/SelectPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/SelectPartDisplayDriver.cs index aed21a58a3e..9427626a87f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/SelectPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/SelectPartDisplayDriver.cs @@ -25,15 +25,18 @@ public override IDisplayResult Display(SelectPart part) public override IDisplayResult Edit(SelectPart part) { - return Initialize("SelectPart_Fields_Edit", m => - { - m.Options = JConvert.SerializeObject(part.Options ?? [], JOptions.CamelCaseIndented); - m.DefaultValue = part.DefaultValue; - m.Editor = part.Editor; - }); + return Initialize( + "SelectPart_Fields_Edit", + m => + { + m.Options = JConvert.SerializeObject(part.Options ?? [], JOptions.CamelCaseIndented); + m.DefaultValue = part.DefaultValue; + m.Editor = part.Editor; + } + ); } - public async override Task UpdateAsync(SelectPart part, IUpdateModel updater) + public override async Task UpdateAsync(SelectPart part, IUpdateModel updater) { var viewModel = new SelectPartEditViewModel(); @@ -43,9 +46,7 @@ public async override Task UpdateAsync(SelectPart part, IUpdateM try { part.Editor = viewModel.Editor; - part.Options = string.IsNullOrWhiteSpace(viewModel.Options) - ? [] - : JConvert.DeserializeObject(viewModel.Options); + part.Options = string.IsNullOrWhiteSpace(viewModel.Options) ? [] : JConvert.DeserializeObject(viewModel.Options); } catch { diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/TextAreaPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/TextAreaPartDisplayDriver.cs index bf297e440a8..aec199d1d94 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/TextAreaPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/TextAreaPartDisplayDriver.cs @@ -16,14 +16,17 @@ public override IDisplayResult Display(TextAreaPart part) public override IDisplayResult Edit(TextAreaPart part) { - return Initialize("TextAreaPart_Fields_Edit", m => - { - m.Placeholder = part.Placeholder; - m.DefaultValue = part.DefaultValue; - }); + return Initialize( + "TextAreaPart_Fields_Edit", + m => + { + m.Placeholder = part.Placeholder; + m.DefaultValue = part.DefaultValue; + } + ); } - public async override Task UpdateAsync(TextAreaPart part, IUpdateModel updater) + public override async Task UpdateAsync(TextAreaPart part, IUpdateModel updater) { var viewModel = new InputPartEditViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ValidationPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ValidationPartDisplayDriver.cs index e9b12c46cf1..6f21a3c6e2d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ValidationPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ValidationPartDisplayDriver.cs @@ -16,13 +16,16 @@ public override IDisplayResult Display(ValidationPart part) public override IDisplayResult Edit(ValidationPart part) { - return Initialize("ValidationPart_Fields_Edit", m => - { - m.For = part.For; - }); + return Initialize( + "ValidationPart_Fields_Edit", + m => + { + m.For = part.For; + } + ); } - public async override Task UpdateAsync(ValidationPart part, IUpdateModel updater) + public override async Task UpdateAsync(ValidationPart part, IUpdateModel updater) { var viewModel = new ValidationPartEditViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ValidationSummaryPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ValidationSummaryPartDisplayDriver.cs index 757d78e16e8..42c8f28e086 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ValidationSummaryPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Drivers/ValidationSummaryPartDisplayDriver.cs @@ -17,10 +17,13 @@ public override IDisplayResult Display(ValidationSummaryPart part) public override IDisplayResult Edit(ValidationSummaryPart part) { - return Initialize("ValidationSummaryPart_Fields_Edit", model => - { - model.ModelOnly = part.ModelOnly; - }); + return Initialize( + "ValidationSummaryPart_Fields_Edit", + model => + { + model.ModelOnly = part.ModelOnly; + } + ); } public override async Task UpdateAsync(ValidationSummaryPart part, IUpdateModel updater, UpdatePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Filters/ExportModelStateAttribute.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Filters/ExportModelStateAttribute.cs index 4cf0758c5a9..2584cfd4da7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Filters/ExportModelStateAttribute.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Filters/ExportModelStateAttribute.cs @@ -27,13 +27,12 @@ private static bool IsRedirect(ActionExecutedContext context) var result = context.Result; var statusCode = context.HttpContext.Response.StatusCode; - return - result is RedirectResult || - result is RedirectToRouteResult || - result is RedirectToActionResult || - result is LocalRedirectResult || - statusCode == (int)HttpStatusCode.Redirect || - statusCode == (int)HttpStatusCode.TemporaryRedirect; + return result is RedirectResult + || result is RedirectToRouteResult + || result is RedirectToActionResult + || result is LocalRedirectResult + || statusCode == (int)HttpStatusCode.Redirect + || statusCode == (int)HttpStatusCode.TemporaryRedirect; } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Filters/ImportModelStatePageFilter.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Filters/ImportModelStatePageFilter.cs index 392d552da10..ed23e367c35 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Filters/ImportModelStatePageFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Filters/ImportModelStatePageFilter.cs @@ -29,12 +29,8 @@ public void OnPageHandlerExecuted(PageHandlerExecutedContext context) } } - public void OnPageHandlerExecuting(PageHandlerExecutingContext context) - { - } + public void OnPageHandlerExecuting(PageHandlerExecutingContext context) { } - public void OnPageHandlerSelected(PageHandlerSelectedContext context) - { - } + public void OnPageHandlerSelected(PageHandlerSelectedContext context) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Manifest.cs index 3b496116914..9c4a573c6b9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Manifest.cs @@ -1,11 +1,6 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Forms", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Forms", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Forms", diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Migrations.cs index c1629600ef9..fd26c492192 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Migrations.cs @@ -18,143 +18,108 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { // Form - await _contentDefinitionManager.AlterPartDefinitionAsync("FormPart", part => part - .Attachable() - .WithDescription("Turns your content item into a form.")); - - await _contentDefinitionManager.AlterTypeDefinitionAsync("Form", type => type - .WithPart("TitlePart", part => part - .WithSettings(new TitlePartSettings { RenderTitle = false }) - .WithPosition("0") - ) - .WithPart("FormElementPart", part => - part.WithPosition("1") - ) - .WithPart("FormPart") - .WithPart("FlowPart") - .Stereotype("Widget")); + await _contentDefinitionManager.AlterPartDefinitionAsync("FormPart", part => part.Attachable().WithDescription("Turns your content item into a form.")); + + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Form", + type => + type.WithPart("TitlePart", part => part.WithSettings(new TitlePartSettings { RenderTitle = false }).WithPosition("0")) + .WithPart("FormElementPart", part => part.WithPosition("1")) + .WithPart("FormPart") + .WithPart("FlowPart") + .Stereotype("Widget") + ); // FormElement - await _contentDefinitionManager.AlterPartDefinitionAsync("FormElementPart", part => part - .WithDescription("Provides attributes common to all form elements.")); + await _contentDefinitionManager.AlterPartDefinitionAsync("FormElementPart", part => part.WithDescription("Provides attributes common to all form elements.")); - await _contentDefinitionManager.AlterPartDefinitionAsync("FormElementLabelPart", part => part - .Attachable() - .WithDescription("Provides a way to capture element's label.") + await _contentDefinitionManager.AlterPartDefinitionAsync( + "FormElementLabelPart", + part => part.Attachable().WithDescription("Provides a way to capture element's label.") ); - await _contentDefinitionManager.AlterPartDefinitionAsync("FormElementValidationPart", part => part - .Attachable() - .WithDescription("Provides validation options to form elements.") + await _contentDefinitionManager.AlterPartDefinitionAsync( + "FormElementValidationPart", + part => part.Attachable().WithDescription("Provides validation options to form elements.") ); // FormInputElement - await _contentDefinitionManager.AlterPartDefinitionAsync("FormInputElementPart", part => part - .WithDescription("Provides attributes common to all input form elements.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "FormInputElementPart", + part => part.WithDescription("Provides attributes common to all input form elements.") + ); // Label - await _contentDefinitionManager.AlterPartDefinitionAsync("LabelPart", part => part - .WithDescription("Provides label properties.")); - - await _contentDefinitionManager.AlterTypeDefinitionAsync("Label", type => type - .WithPart("TitlePart", part => part - .WithSettings(new TitlePartSettings { RenderTitle = false }) - ) - .WithPart("FormElementPart") - .WithPart("LabelPart") - .Stereotype("Widget")); + await _contentDefinitionManager.AlterPartDefinitionAsync("LabelPart", part => part.WithDescription("Provides label properties.")); + + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Label", + type => + type.WithPart("TitlePart", part => part.WithSettings(new TitlePartSettings { RenderTitle = false })) + .WithPart("FormElementPart") + .WithPart("LabelPart") + .Stereotype("Widget") + ); // Input - await _contentDefinitionManager.AlterPartDefinitionAsync("InputPart", part => part - .WithDescription("Provides input field properties.")); - - await _contentDefinitionManager.AlterTypeDefinitionAsync("Input", type => type - .WithPart("FormInputElementPart", part => part - .WithPosition("1") - ) - .WithPart("FormElementPart", part => part - .WithPosition("2") - ) - .WithPart("FormElementLabelPart", part => part - .WithPosition("3") - ) - .WithPart("InputPart", part => part - .WithPosition("4") - ) - .WithPart("FormElementValidationPart", part => part - .WithPosition("5") - ) - .Stereotype("Widget")); + await _contentDefinitionManager.AlterPartDefinitionAsync("InputPart", part => part.WithDescription("Provides input field properties.")); + + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Input", + type => + type.WithPart("FormInputElementPart", part => part.WithPosition("1")) + .WithPart("FormElementPart", part => part.WithPosition("2")) + .WithPart("FormElementLabelPart", part => part.WithPosition("3")) + .WithPart("InputPart", part => part.WithPosition("4")) + .WithPart("FormElementValidationPart", part => part.WithPosition("5")) + .Stereotype("Widget") + ); // TextArea - await _contentDefinitionManager.AlterPartDefinitionAsync("TextAreaPart", part => part - .WithDescription("Provides text area properties.")); - - await _contentDefinitionManager.AlterTypeDefinitionAsync("TextArea", type => type - .WithPart("FormInputElementPart", part => part - .WithPosition("1") - ) - .WithPart("FormElementPart", part => part - .WithPosition("2") - ) - .WithPart("FormElementLabelPart", part => part - .WithPosition("3") - ) - .WithPart("TextAreaPart", part => part - .WithPosition("4") - ) - .WithPart("FormElementValidationPart", part => part - .WithPosition("5") - ) - .Stereotype("Widget")); + await _contentDefinitionManager.AlterPartDefinitionAsync("TextAreaPart", part => part.WithDescription("Provides text area properties.")); + + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "TextArea", + type => + type.WithPart("FormInputElementPart", part => part.WithPosition("1")) + .WithPart("FormElementPart", part => part.WithPosition("2")) + .WithPart("FormElementLabelPart", part => part.WithPosition("3")) + .WithPart("TextAreaPart", part => part.WithPosition("4")) + .WithPart("FormElementValidationPart", part => part.WithPosition("5")) + .Stereotype("Widget") + ); // Select - await _contentDefinitionManager.AlterPartDefinitionAsync("SelectPart", part => part - .WithDescription("Provides select field properties.")); - - await _contentDefinitionManager.AlterTypeDefinitionAsync("Select", type => type - .WithPart("FormInputElementPart", part => part - .WithPosition("1") - ) - .WithPart("FormElementPart", part => part - .WithPosition("2") - ) - .WithPart("FormElementLabelPart", part => part - .WithPosition("3") - ) - .WithPart("SelectPart", part => part - .WithPosition("4") - ) - .WithPart("FormElementValidationPart", part => part - .WithPosition("5") - ) - .Stereotype("Widget")); + await _contentDefinitionManager.AlterPartDefinitionAsync("SelectPart", part => part.WithDescription("Provides select field properties.")); + + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Select", + type => + type.WithPart("FormInputElementPart", part => part.WithPosition("1")) + .WithPart("FormElementPart", part => part.WithPosition("2")) + .WithPart("FormElementLabelPart", part => part.WithPosition("3")) + .WithPart("SelectPart", part => part.WithPosition("4")) + .WithPart("FormElementValidationPart", part => part.WithPosition("5")) + .Stereotype("Widget") + ); // Button - await _contentDefinitionManager.AlterPartDefinitionAsync("ButtonPart", part => part - .WithDescription("Provides button properties.")); + await _contentDefinitionManager.AlterPartDefinitionAsync("ButtonPart", part => part.WithDescription("Provides button properties.")); - await _contentDefinitionManager.AlterTypeDefinitionAsync("Button", type => type - .WithPart("FormInputElementPart") - .WithPart("FormElementPart") - .WithPart("ButtonPart") - .Stereotype("Widget")); + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Button", + type => type.WithPart("FormInputElementPart").WithPart("FormElementPart").WithPart("ButtonPart").Stereotype("Widget") + ); // Validation Summary - await _contentDefinitionManager.AlterPartDefinitionAsync("ValidationSummaryPart", part => part - .WithDescription("Displays a validation summary.")); + await _contentDefinitionManager.AlterPartDefinitionAsync("ValidationSummaryPart", part => part.WithDescription("Displays a validation summary.")); - await _contentDefinitionManager.AlterTypeDefinitionAsync("ValidationSummary", type => type - .WithPart("ValidationSummaryPart") - .Stereotype("Widget")); + await _contentDefinitionManager.AlterTypeDefinitionAsync("ValidationSummary", type => type.WithPart("ValidationSummaryPart").Stereotype("Widget")); // Validation - await _contentDefinitionManager.AlterPartDefinitionAsync("ValidationPart", part => part - .WithDescription("Displays a field validation error.")); + await _contentDefinitionManager.AlterPartDefinitionAsync("ValidationPart", part => part.WithDescription("Displays a field validation error.")); - await _contentDefinitionManager.AlterTypeDefinitionAsync("Validation", type => type - .WithPart("ValidationPart") - .Stereotype("Widget")); + await _contentDefinitionManager.AlterTypeDefinitionAsync("Validation", type => type.WithPart("ValidationPart").Stereotype("Widget")); // Shortcut other migration steps on new content definition schemas. return 4; @@ -163,12 +128,14 @@ await _contentDefinitionManager.AlterTypeDefinitionAsync("Validation", type => t // This code can be removed in a later version. public async Task UpdateFrom1Async() { - await _contentDefinitionManager.AlterTypeDefinitionAsync("Form", type => type - .WithPart("TitlePart", part => part.MergeSettings(setting => setting.RenderTitle = false)) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Form", + type => type.WithPart("TitlePart", part => part.MergeSettings(setting => setting.RenderTitle = false)) ); - await _contentDefinitionManager.AlterTypeDefinitionAsync("Label", type => type - .WithPart("TitlePart", part => part.MergeSettings(setting => setting.RenderTitle = false)) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Label", + type => type.WithPart("TitlePart", part => part.MergeSettings(setting => setting.RenderTitle = false)) ); return 2; @@ -177,13 +144,9 @@ await _contentDefinitionManager.AlterTypeDefinitionAsync("Label", type => type // This code can be removed in a later version. public async Task UpdateFrom2Async() { - await _contentDefinitionManager.AlterTypeDefinitionAsync("Form", type => type - .WithPart("TitlePart", part => part - .WithPosition("0") - ) - .WithPart("FormElementPart", part => - part.WithPosition("1") - ) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Form", + type => type.WithPart("TitlePart", part => part.WithPosition("0")).WithPart("FormElementPart", part => part.WithPosition("1")) ); return 3; @@ -192,68 +155,44 @@ await _contentDefinitionManager.AlterTypeDefinitionAsync("Form", type => type // This code can be removed in a later version. public async Task UpdateFrom3Async() { - await _contentDefinitionManager.AlterPartDefinitionAsync("FormElementLabelPart", part => part - .Attachable() - .WithDescription("Provides a way to capture element's label.") + await _contentDefinitionManager.AlterPartDefinitionAsync( + "FormElementLabelPart", + part => part.Attachable().WithDescription("Provides a way to capture element's label.") ); - await _contentDefinitionManager.AlterPartDefinitionAsync("FormElementValidationPart", part => part - .Attachable() - .WithDescription("Provides validation options to form elements.") + await _contentDefinitionManager.AlterPartDefinitionAsync( + "FormElementValidationPart", + part => part.Attachable().WithDescription("Provides validation options to form elements.") ); - await _contentDefinitionManager.AlterTypeDefinitionAsync("Select", type => type - .WithPart("FormInputElementPart", part => part - .WithPosition("1") - ) - .WithPart("FormElementPart", part => part - .WithPosition("2") - ) - .WithPart("FormElementLabelPart", part => part - .WithPosition("3") - ) - .WithPart("SelectPart", part => part - .WithPosition("4") - ) - .WithPart("FormElementValidationPart", part => part - .WithPosition("5") - ) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Select", + type => + type.WithPart("FormInputElementPart", part => part.WithPosition("1")) + .WithPart("FormElementPart", part => part.WithPosition("2")) + .WithPart("FormElementLabelPart", part => part.WithPosition("3")) + .WithPart("SelectPart", part => part.WithPosition("4")) + .WithPart("FormElementValidationPart", part => part.WithPosition("5")) ); - await _contentDefinitionManager.AlterTypeDefinitionAsync("Input", type => type - .WithPart("FormInputElementPart", part => part - .WithPosition("1") - ) - .WithPart("FormElementPart", part => part - .WithPosition("2") - ) - .WithPart("FormElementLabelPart", part => part - .WithPosition("3") - ) - .WithPart("InputPart", part => part - .WithPosition("4") - ) - .WithPart("FormElementValidationPart", part => part - .WithPosition("5") - ) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Input", + type => + type.WithPart("FormInputElementPart", part => part.WithPosition("1")) + .WithPart("FormElementPart", part => part.WithPosition("2")) + .WithPart("FormElementLabelPart", part => part.WithPosition("3")) + .WithPart("InputPart", part => part.WithPosition("4")) + .WithPart("FormElementValidationPart", part => part.WithPosition("5")) ); - await _contentDefinitionManager.AlterTypeDefinitionAsync("TextArea", type => type - .WithPart("FormInputElementPart", part => part - .WithPosition("1") - ) - .WithPart("FormElementPart", part => part - .WithPosition("2") - ) - .WithPart("FormElementLabelPart", part => part - .WithPosition("3") - ) - .WithPart("TextAreaPart", part => part - .WithPosition("4") - ) - .WithPart("FormElementValidationPart", part => part - .WithPosition("5") - ) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "TextArea", + type => + type.WithPart("FormInputElementPart", part => part.WithPosition("1")) + .WithPart("FormElementPart", part => part.WithPosition("2")) + .WithPart("FormElementLabelPart", part => part.WithPosition("3")) + .WithPart("TextAreaPart", part => part.WithPosition("4")) + .WithPart("FormElementValidationPart", part => part.WithPosition("5")) ); return 4; diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Startup.cs index 507fe60bc52..8fe1d747672 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Startup.cs @@ -39,41 +39,29 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddDataMigration(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/AddModelValidationErrorTask.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/AddModelValidationErrorTask.cs index cb2d3f7a821..393096c984b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/AddModelValidationErrorTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/AddModelValidationErrorTask.cs @@ -13,10 +13,7 @@ public class AddModelValidationErrorTask : TaskActivity localizer - ) + public AddModelValidationErrorTask(IUpdateModelAccessor updateModelAccessor, IStringLocalizer localizer) { _updateModelAccessor = updateModelAccessor; S = localizer; @@ -45,8 +42,7 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex public override ActivityExecutionResult Execute(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - var updater = _updateModelAccessor.ModelUpdater - ?? throw new InvalidOperationException("Cannot add model validation errors when there's no Updater present."); + var updater = _updateModelAccessor.ModelUpdater ?? throw new InvalidOperationException("Cannot add model validation errors when there's no Updater present."); updater.ModelState.AddModelError(Key, ErrorMessage); return Outcomes("Done"); diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/BindModelStateTask.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/BindModelStateTask.cs index e5b2a749c99..57af5e9facc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/BindModelStateTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/BindModelStateTask.cs @@ -15,11 +15,7 @@ public class BindModelStateTask : TaskActivity private readonly IHttpContextAccessor _httpContextAccessor; protected readonly IStringLocalizer S; - public BindModelStateTask( - IHttpContextAccessor httpContextAccessor, - IUpdateModelAccessor updateModelAccessor, - IStringLocalizer localizer - ) + public BindModelStateTask(IHttpContextAccessor httpContextAccessor, IUpdateModelAccessor updateModelAccessor, IStringLocalizer localizer) { _updateModelAccessor = updateModelAccessor; _httpContextAccessor = httpContextAccessor; @@ -37,8 +33,7 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex public override ActivityExecutionResult Execute(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - var updater = _updateModelAccessor.ModelUpdater - ?? throw new InvalidOperationException("Cannot add model validation errors when there's no Updater present."); + var updater = _updateModelAccessor.ModelUpdater ?? throw new InvalidOperationException("Cannot add model validation errors when there's no Updater present."); var httpContext = _httpContextAccessor.HttpContext; diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateAntiforgeryTokenTask.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateAntiforgeryTokenTask.cs index 37b14f587cd..7d304f879a0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateAntiforgeryTokenTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateAntiforgeryTokenTask.cs @@ -15,11 +15,7 @@ public class ValidateAntiforgeryTokenTask : TaskActivity localizer - ) + public ValidateAntiforgeryTokenTask(IHttpContextAccessor httpContextAccessor, IAntiforgery antiforgery, IStringLocalizer localizer) { _httpContextAccessor = httpContextAccessor; _antiforgery = antiforgery; diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateFormFieldTask.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateFormFieldTask.cs index 1defcd12ae0..a008da96892 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateFormFieldTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateFormFieldTask.cs @@ -15,11 +15,7 @@ public class ValidateFormFieldTask : TaskActivity private readonly IUpdateModelAccessor _updateModelAccessor; protected readonly IStringLocalizer S; - public ValidateFormFieldTask( - IHttpContextAccessor httpContextAccessor, - IUpdateModelAccessor updateModelAccessor, - IStringLocalizer localizer - ) + public ValidateFormFieldTask(IHttpContextAccessor httpContextAccessor, IUpdateModelAccessor updateModelAccessor, IStringLocalizer localizer) { _httpContextAccessor = httpContextAccessor; _updateModelAccessor = updateModelAccessor; diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateFormTask.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateFormTask.cs index 3477af87bfe..1a4c4b92961 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateFormTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Activities/ValidateFormTask.cs @@ -13,10 +13,7 @@ public class ValidateFormTask : TaskActivity private readonly IUpdateModelAccessor _updateModelAccessor; protected readonly IStringLocalizer S; - public ValidateFormTask( - IUpdateModelAccessor updateModelAccessor, - IStringLocalizer localizer - ) + public ValidateFormTask(IUpdateModelAccessor updateModelAccessor, IStringLocalizer localizer) { _updateModelAccessor = updateModelAccessor; S = localizer; @@ -35,8 +32,7 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex public override ActivityExecutionResult Execute(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - var updater = _updateModelAccessor.ModelUpdater - ?? throw new InvalidOperationException("Cannot add model validation errors when there's no Updater present."); + var updater = _updateModelAccessor.ModelUpdater ?? throw new InvalidOperationException("Cannot add model validation errors when there's no Updater present."); var isValid = updater.ModelState.ErrorCount == 0; var outcome = isValid ? "Valid" : "Invalid"; diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/BindModelStateTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/BindModelStateTaskDisplayDriver.cs index 32850aa16ca..8e528f5de75 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/BindModelStateTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/BindModelStateTaskDisplayDriver.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Forms.Workflows.Drivers { - public class BindModelStateTaskDisplayDriver : ActivityDisplayDriver - { - } + public class BindModelStateTaskDisplayDriver : ActivityDisplayDriver { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/ValidateAntiforgeryTokenTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/ValidateAntiforgeryTokenTaskDisplayDriver.cs index f3b25b434fd..ec6ba52f2c4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/ValidateAntiforgeryTokenTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/ValidateAntiforgeryTokenTaskDisplayDriver.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Forms.Workflows.Drivers { - public class ValidateAntiforgeryTokenTaskDisplayDriver : ActivityDisplayDriver - { - } + public class ValidateAntiforgeryTokenTaskDisplayDriver : ActivityDisplayDriver { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/ValidateFormTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/ValidateFormTaskDisplayDriver.cs index a5021476fa3..bcda6dba862 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/ValidateFormTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/Workflows/Drivers/ValidateFormTaskDisplayDriver.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Forms.Workflows.Drivers { - public class ValidateFormTaskDisplayDriver : ActivityDisplayDriver - { - } + public class ValidateFormTaskDisplayDriver : ActivityDisplayDriver { } } diff --git a/src/OrchardCore.Modules/OrchardCore.GitHub/AdminMenuGitHubLogin.cs b/src/OrchardCore.Modules/OrchardCore.GitHub/AdminMenuGitHubLogin.cs index 3bf0dbd3176..0995d72f750 100644 --- a/src/OrchardCore.Modules/OrchardCore.GitHub/AdminMenuGitHubLogin.cs +++ b/src/OrchardCore.Modules/OrchardCore.GitHub/AdminMenuGitHubLogin.cs @@ -9,11 +9,7 @@ namespace OrchardCore.GitHub [Feature(GitHubConstants.Features.GitHubAuthentication)] public class AdminMenuGitHubLogin : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", GitHubConstants.Features.GitHubAuthentication }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", GitHubConstants.Features.GitHubAuthentication }, }; protected readonly IStringLocalizer S; @@ -29,18 +25,20 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Authentication"], authentication => authentication - .Add(S["GitHub"], S["GitHub"].PrefixPosition(), settings => settings - .AddClass("github") - .Id("github") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageGitHubAuthentication) - .LocalNav() - ) + builder.Add( + S["Security"], + security => + security.Add( + S["Authentication"], + authentication => + authentication.Add( + S["GitHub"], + S["GitHub"].PrefixPosition(), + settings => + settings.AddClass("github").Id("github").Action("Index", "Admin", _routeValues).Permission(Permissions.ManageGitHubAuthentication).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GitHubAuthenticationSettingsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GitHubAuthenticationSettingsConfiguration.cs index 75843108f94..77a80400b1b 100644 --- a/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GitHubAuthenticationSettingsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GitHubAuthenticationSettingsConfiguration.cs @@ -18,7 +18,8 @@ public class GitHubAuthenticationSettingsConfiguration : IConfigureOptions logger) + ILogger logger + ) { _gitHubAuthenticationService = gitHubAuthenticationService; _shellSettings = shellSettings; @@ -27,9 +28,7 @@ public GitHubAuthenticationSettingsConfiguration( public void Configure(GitHubAuthenticationSettings options) { - var settings = GetGitHubAuthenticationSettingsAsync() - .GetAwaiter() - .GetResult(); + var settings = GetGitHubAuthenticationSettingsAsync().GetAwaiter().GetResult(); if (settings != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GithubHandler.cs b/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GithubHandler.cs index 35f1fdc0115..b866dab35e2 100644 --- a/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GithubHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GithubHandler.cs @@ -17,9 +17,7 @@ namespace OrchardCore.GitHub.Configuration public class GitHubHandler : OAuthHandler { public GitHubHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder) - : base(options, logger, encoder) - { - } + : base(options, logger, encoder) { } protected override async Task CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { @@ -29,7 +27,9 @@ protected override async Task CreateTicketAsync(ClaimsIden var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { - throw new HttpRequestException($"An error occurred when retrieving GitHub user information ({response.StatusCode}). Please check if the authentication information is correct in the corresponding GitHub Application."); + throw new HttpRequestException( + $"An error occurred when retrieving GitHub user information ({response.StatusCode}). Please check if the authentication information is correct in the corresponding GitHub Application." + ); } var payload = (await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync())).RootElement; @@ -97,6 +97,7 @@ protected override async Task ExchangeCodeAsync(OAuthCodeExc return OAuthTokenResponse.Failed(new Exception(error)); } } + private static async Task Display(HttpResponseMessage response) { var output = new StringBuilder(); diff --git a/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GithubOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GithubOptionsConfiguration.cs index c2096bfd1d4..0010e35fa23 100644 --- a/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GithubOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.GitHub/Configuration/GithubOptionsConfiguration.cs @@ -7,9 +7,7 @@ namespace OrchardCore.GitHub.Configuration { - public class GitHubOptionsConfiguration : - IConfigureOptions, - IConfigureNamedOptions + public class GitHubOptionsConfiguration : IConfigureOptions, IConfigureNamedOptions { private readonly GitHubAuthenticationSettings _gitHubAuthenticationSettings; private readonly IDataProtectionProvider _dataProtectionProvider; @@ -18,7 +16,8 @@ public class GitHubOptionsConfiguration : public GitHubOptionsConfiguration( IOptions gitHubAuthenticationSettings, IDataProtectionProvider dataProtectionProvider, - ILogger logger) + ILogger logger + ) { _gitHubAuthenticationSettings = gitHubAuthenticationSettings.Value; _dataProtectionProvider = dataProtectionProvider; @@ -32,8 +31,7 @@ public void Configure(AuthenticationOptions options) return; } - if (string.IsNullOrWhiteSpace(_gitHubAuthenticationSettings.ClientID) || - string.IsNullOrWhiteSpace(_gitHubAuthenticationSettings.ClientSecret)) + if (string.IsNullOrWhiteSpace(_gitHubAuthenticationSettings.ClientID) || string.IsNullOrWhiteSpace(_gitHubAuthenticationSettings.ClientSecret)) { _logger.LogWarning("The Github login provider is enabled but not configured."); @@ -41,11 +39,14 @@ public void Configure(AuthenticationOptions options) } // Register the OpenID Connect client handler in the authentication handlers collection. - options.AddScheme(GitHubDefaults.AuthenticationScheme, builder => - { - builder.DisplayName = "GitHub"; - builder.HandlerType = typeof(GitHubHandler); - }); + options.AddScheme( + GitHubDefaults.AuthenticationScheme, + builder => + { + builder.DisplayName = "GitHub"; + builder.HandlerType = typeof(GitHubHandler); + } + ); } public void Configure(string name, GitHubOptions options) diff --git a/src/OrchardCore.Modules/OrchardCore.GitHub/Drivers/GithubAuthenticationSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.GitHub/Drivers/GithubAuthenticationSettingsDisplayDriver.cs index 6d8d2bb049d..60a3688462d 100644 --- a/src/OrchardCore.Modules/OrchardCore.GitHub/Drivers/GithubAuthenticationSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.GitHub/Drivers/GithubAuthenticationSettingsDisplayDriver.cs @@ -29,7 +29,8 @@ public GitHubAuthenticationSettingsDisplayDriver( IHttpContextAccessor httpContextAccessor, IShellHost shellHost, ShellSettings shellSettings, - ILogger logger) + ILogger logger + ) { _authorizationService = authorizationService; _dataProtectionProvider = dataProtectionProvider; @@ -47,33 +48,38 @@ public override async Task EditAsync(GitHubAuthenticationSetting return null; } - return Initialize("GitHubAuthenticationSettings_Edit", model => - { - model.ClientID = settings.ClientID; - if (!string.IsNullOrWhiteSpace(settings.ClientSecret)) - { - try + return Initialize( + "GitHubAuthenticationSettings_Edit", + model => { - var protector = _dataProtectionProvider.CreateProtector(GitHubConstants.Features.GitHubAuthentication); - model.ClientSecret = protector.Unprotect(settings.ClientSecret); + model.ClientID = settings.ClientID; + if (!string.IsNullOrWhiteSpace(settings.ClientSecret)) + { + try + { + var protector = _dataProtectionProvider.CreateProtector(GitHubConstants.Features.GitHubAuthentication); + model.ClientSecret = protector.Unprotect(settings.ClientSecret); + } + catch (CryptographicException) + { + _logger.LogError("The client secret could not be decrypted. It may have been encrypted using a different key."); + model.ClientSecret = string.Empty; + model.HasDecryptionError = true; + } + } + else + { + model.ClientSecret = string.Empty; + } + if (settings.CallbackPath.HasValue) + { + model.CallbackUrl = settings.CallbackPath.Value; + } + model.SaveTokens = settings.SaveTokens; } - catch (CryptographicException) - { - _logger.LogError("The client secret could not be decrypted. It may have been encrypted using a different key."); - model.ClientSecret = string.Empty; - model.HasDecryptionError = true; - } - } - else - { - model.ClientSecret = string.Empty; - } - if (settings.CallbackPath.HasValue) - { - model.CallbackUrl = settings.CallbackPath.Value; - } - model.SaveTokens = settings.SaveTokens; - }).Location("Content:5").OnGroup(GitHubConstants.Features.GitHubAuthentication); + ) + .Location("Content:5") + .OnGroup(GitHubConstants.Features.GitHubAuthentication); } public override async Task UpdateAsync(GitHubAuthenticationSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.GitHub/Extensions/OrchardCoreBuilderExtensions.cs b/src/OrchardCore.Modules/OrchardCore.GitHub/Extensions/OrchardCoreBuilderExtensions.cs index a83f7bcbb71..cfb9c95fc0b 100644 --- a/src/OrchardCore.Modules/OrchardCore.GitHub/Extensions/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.GitHub/Extensions/OrchardCoreBuilderExtensions.cs @@ -8,12 +8,14 @@ public static class OrchardCoreBuilderExtensions { public static OrchardCoreBuilder ConfigureGitHubSettings(this OrchardCoreBuilder builder) { - builder.ConfigureServices((tenantServices, serviceProvider) => - { - var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_GitHub"); + builder.ConfigureServices( + (tenantServices, serviceProvider) => + { + var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_GitHub"); - tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); - }); + tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); + } + ); return builder; } diff --git a/src/OrchardCore.Modules/OrchardCore.GitHub/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.GitHub/Permissions.cs index 6ea951ce41c..eafc840bff1 100644 --- a/src/OrchardCore.Modules/OrchardCore.GitHub/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.GitHub/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageGitHubAuthentication = new("ManageGitHubAuthentication", "Manage GitHub Authentication settings"); - private readonly IEnumerable _allPermissions = - [ - ManageGitHubAuthentication, - ]; + private readonly IEnumerable _allPermissions = [ManageGitHubAuthentication,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.GitHub/Services/GithubAuthenticationService.cs b/src/OrchardCore.Modules/OrchardCore.GitHub/Services/GithubAuthenticationService.cs index 4d954cff7c2..80ce8b736f0 100644 --- a/src/OrchardCore.Modules/OrchardCore.GitHub/Services/GithubAuthenticationService.cs +++ b/src/OrchardCore.Modules/OrchardCore.GitHub/Services/GithubAuthenticationService.cs @@ -14,9 +14,7 @@ public class GitHubAuthenticationService : IGitHubAuthenticationService private readonly ISiteService _siteService; protected readonly IStringLocalizer S; - public GitHubAuthenticationService( - ISiteService siteService, - IStringLocalizer stringLocalizer) + public GitHubAuthenticationService(ISiteService siteService, IStringLocalizer stringLocalizer) { _siteService = siteService; S = stringLocalizer; @@ -39,12 +37,15 @@ public async Task UpdateSettingsAsync(GitHubAuthenticationSettings settings) ArgumentNullException.ThrowIfNull(settings); var container = await _siteService.LoadSiteSettingsAsync(); - container.Alter(nameof(GitHubAuthenticationSettings), aspect => - { - aspect.ClientID = settings.ClientID; - aspect.ClientSecret = settings.ClientSecret; - aspect.CallbackPath = settings.CallbackPath; - }); + container.Alter( + nameof(GitHubAuthenticationSettings), + aspect => + { + aspect.ClientID = settings.ClientID; + aspect.ClientSecret = settings.ClientSecret; + aspect.CallbackPath = settings.CallbackPath; + } + ); await _siteService.UpdateSiteSettingsAsync(container); } diff --git a/src/OrchardCore.Modules/OrchardCore.GitHub/Startup.cs b/src/OrchardCore.Modules/OrchardCore.GitHub/Startup.cs index fefe09b0c3f..853b3ea1240 100644 --- a/src/OrchardCore.Modules/OrchardCore.GitHub/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.GitHub/Startup.cs @@ -37,14 +37,16 @@ public override void ConfigureServices(IServiceCollection services) services.AddTransient, GitHubAuthenticationSettingsConfiguration>(); // Register the options initializers required by the GitHub Handler. - services.TryAddEnumerable(new[] - { - // Orchard-specific initializers: - ServiceDescriptor.Transient, GitHubOptionsConfiguration>(), - ServiceDescriptor.Transient, GitHubOptionsConfiguration>(), - // Built-in initializers: - ServiceDescriptor.Transient, OAuthPostConfigureOptions>() - }); + services.TryAddEnumerable( + new[] + { + // Orchard-specific initializers: + ServiceDescriptor.Transient, GitHubOptionsConfiguration>(), + ServiceDescriptor.Transient, GitHubOptionsConfiguration>(), + // Built-in initializers: + ServiceDescriptor.Transient, OAuthPostConfigureOptions>() + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/Analytics/Drivers/GoogleAnalyticsSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Google/Analytics/Drivers/GoogleAnalyticsSettingsDisplayDriver.cs index 55e920df597..2ee6a429300 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/Analytics/Drivers/GoogleAnalyticsSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/Analytics/Drivers/GoogleAnalyticsSettingsDisplayDriver.cs @@ -15,9 +15,7 @@ public class GoogleAnalyticsSettingsDisplayDriver : SectionDisplayDriver EditAsync(GoogleAnalyticsSettings set return null; } - return Initialize("GoogleAnalyticsSettings_Edit", model => - { - model.TrackingID = settings.TrackingID; - }).Location("Content:5").OnGroup(GoogleConstants.Features.GoogleAnalytics); + return Initialize( + "GoogleAnalyticsSettings_Edit", + model => + { + model.TrackingID = settings.TrackingID; + } + ) + .Location("Content:5") + .OnGroup(GoogleConstants.Features.GoogleAnalytics); } public override async Task UpdateAsync(GoogleAnalyticsSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Google/Analytics/GoogleAnalyticsFilter.cs b/src/OrchardCore.Modules/OrchardCore.Google/Analytics/GoogleAnalyticsFilter.cs index 31671da1642..813b5458b9e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/Analytics/GoogleAnalyticsFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/Analytics/GoogleAnalyticsFilter.cs @@ -16,9 +16,7 @@ public class GoogleAnalyticsFilter : IAsyncResultFilter private HtmlString _scriptsCache; - public GoogleAnalyticsFilter( - IResourceManager resourceManager, - ISiteService siteService) + public GoogleAnalyticsFilter(IResourceManager resourceManager, ISiteService siteService) { _resourceManager = resourceManager; _siteService = siteService; @@ -37,7 +35,9 @@ public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultE if (!string.IsNullOrWhiteSpace(settings?.TrackingID)) { - _scriptsCache = new HtmlString($"\n\n\n"); + _scriptsCache = new HtmlString( + $"\n\n\n" + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/Analytics/Services/GoogleAnalyticsService.cs b/src/OrchardCore.Modules/OrchardCore.Google/Analytics/Services/GoogleAnalyticsService.cs index e356ebf9431..11a5f5f0ea0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/Analytics/Services/GoogleAnalyticsService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/Analytics/Services/GoogleAnalyticsService.cs @@ -8,8 +8,7 @@ public class GoogleAnalyticsService : IGoogleAnalyticsService { private readonly ISiteService _siteService; - public GoogleAnalyticsService( - ISiteService siteService) + public GoogleAnalyticsService(ISiteService siteService) { _siteService = siteService; } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Configuration/GoogleAuthenticationSettingsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Configuration/GoogleAuthenticationSettingsConfiguration.cs index 015a4ef3a1e..59521d3088b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Configuration/GoogleAuthenticationSettingsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Configuration/GoogleAuthenticationSettingsConfiguration.cs @@ -17,7 +17,8 @@ public class GoogleAuthenticationSettingsConfiguration : IConfigureOptions logger) + ILogger logger + ) { _googleAuthenticationService = gitHubAuthenticationService; _shellSettings = shellSettings; @@ -26,9 +27,7 @@ public GoogleAuthenticationSettingsConfiguration( public void Configure(GoogleAuthenticationSettings options) { - var settings = GetGoogleAuthenticationSettingsAsync() - .GetAwaiter() - .GetResult(); + var settings = GetGoogleAuthenticationSettingsAsync().GetAwaiter().GetResult(); if (settings != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Configuration/GoogleOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Configuration/GoogleOptionsConfiguration.cs index 944ddd88228..a6048f87750 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Configuration/GoogleOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Configuration/GoogleOptionsConfiguration.cs @@ -8,9 +8,7 @@ namespace OrchardCore.Google.Authentication.Configuration { - public class GoogleOptionsConfiguration : - IConfigureOptions, - IConfigureNamedOptions + public class GoogleOptionsConfiguration : IConfigureOptions, IConfigureNamedOptions { private readonly GoogleAuthenticationSettings _googleAuthenticationSettings; private readonly IDataProtectionProvider _dataProtectionProvider; @@ -19,7 +17,8 @@ public class GoogleOptionsConfiguration : public GoogleOptionsConfiguration( IOptions googleAuthenticationSettings, IDataProtectionProvider dataProtectionProvider, - ILogger logger) + ILogger logger + ) { _googleAuthenticationSettings = googleAuthenticationSettings.Value; _dataProtectionProvider = dataProtectionProvider; @@ -33,19 +32,21 @@ public void Configure(AuthenticationOptions options) return; } - if (string.IsNullOrWhiteSpace(_googleAuthenticationSettings.ClientID) || - string.IsNullOrWhiteSpace(_googleAuthenticationSettings.ClientSecret)) + if (string.IsNullOrWhiteSpace(_googleAuthenticationSettings.ClientID) || string.IsNullOrWhiteSpace(_googleAuthenticationSettings.ClientSecret)) { _logger.LogWarning("The Google login provider is enabled but not configured."); return; } - options.AddScheme(GoogleDefaults.AuthenticationScheme, builder => - { - builder.DisplayName = "Google"; - builder.HandlerType = typeof(GoogleHandler); - }); + options.AddScheme( + GoogleDefaults.AuthenticationScheme, + builder => + { + builder.DisplayName = "Google"; + builder.HandlerType = typeof(GoogleHandler); + } + ); } public void Configure(string name, GoogleOptions options) diff --git a/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Drivers/GoogleAuthenticationSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Drivers/GoogleAuthenticationSettingsDisplayDriver.cs index 86260536322..8ebe475d4db 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Drivers/GoogleAuthenticationSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Drivers/GoogleAuthenticationSettingsDisplayDriver.cs @@ -29,7 +29,8 @@ public GoogleAuthenticationSettingsDisplayDriver( IHttpContextAccessor httpContextAccessor, IShellHost shellHost, ShellSettings shellSettings, - ILogger logger) + ILogger logger + ) { _authorizationService = authorizationService; _dataProtectionProvider = dataProtectionProvider; @@ -47,33 +48,38 @@ public override async Task EditAsync(GoogleAuthenticationSetting return null; } - return Initialize("GoogleAuthenticationSettings_Edit", model => - { - model.ClientID = settings.ClientID; - if (!string.IsNullOrWhiteSpace(settings.ClientSecret)) - { - try + return Initialize( + "GoogleAuthenticationSettings_Edit", + model => { - var protector = _dataProtectionProvider.CreateProtector(GoogleConstants.Features.GoogleAuthentication); - model.ClientSecret = protector.Unprotect(settings.ClientSecret); + model.ClientID = settings.ClientID; + if (!string.IsNullOrWhiteSpace(settings.ClientSecret)) + { + try + { + var protector = _dataProtectionProvider.CreateProtector(GoogleConstants.Features.GoogleAuthentication); + model.ClientSecret = protector.Unprotect(settings.ClientSecret); + } + catch (CryptographicException) + { + _logger.LogError("The client secret could not be decrypted. It may have been encrypted using a different key."); + model.ClientSecret = string.Empty; + model.HasDecryptionError = true; + } + } + else + { + model.ClientSecret = string.Empty; + } + if (settings.CallbackPath.HasValue) + { + model.CallbackPath = settings.CallbackPath.Value; + } + model.SaveTokens = settings.SaveTokens; } - catch (CryptographicException) - { - _logger.LogError("The client secret could not be decrypted. It may have been encrypted using a different key."); - model.ClientSecret = string.Empty; - model.HasDecryptionError = true; - } - } - else - { - model.ClientSecret = string.Empty; - } - if (settings.CallbackPath.HasValue) - { - model.CallbackPath = settings.CallbackPath.Value; - } - model.SaveTokens = settings.SaveTokens; - }).Location("Content:5").OnGroup(GoogleConstants.Features.GoogleAuthentication); + ) + .Location("Content:5") + .OnGroup(GoogleConstants.Features.GoogleAuthentication); } public override async Task UpdateAsync(GoogleAuthenticationSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Services/GoogleAuthenticationService.cs b/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Services/GoogleAuthenticationService.cs index 48e7009665b..5a36cf91f98 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Services/GoogleAuthenticationService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/Authentication/Services/GoogleAuthenticationService.cs @@ -14,9 +14,7 @@ public class GoogleAuthenticationService : IGoogleAuthenticationService private readonly ISiteService _siteService; protected readonly IStringLocalizer S; - public GoogleAuthenticationService( - ISiteService siteService, - IStringLocalizer stringLocalizer) + public GoogleAuthenticationService(ISiteService siteService, IStringLocalizer stringLocalizer) { _siteService = siteService; S = stringLocalizer; @@ -39,12 +37,15 @@ public async Task UpdateSettingsAsync(GoogleAuthenticationSettings settings) ArgumentNullException.ThrowIfNull(settings); var container = await _siteService.LoadSiteSettingsAsync(); - container.Alter(nameof(GoogleAuthenticationSettings), aspect => - { - aspect.ClientID = settings.ClientID; - aspect.ClientSecret = settings.ClientSecret; - aspect.CallbackPath = settings.CallbackPath; - }); + container.Alter( + nameof(GoogleAuthenticationSettings), + aspect => + { + aspect.ClientID = settings.ClientID; + aspect.ClientSecret = settings.ClientSecret; + aspect.CallbackPath = settings.CallbackPath; + } + ); await _siteService.UpdateSiteSettingsAsync(container); } @@ -57,18 +58,12 @@ public IEnumerable ValidateSettings(GoogleAuthenticationSettin if (string.IsNullOrEmpty(settings.ClientID)) { - results.Add(new ValidationResult(S["The Client ID is required."], new[] - { - nameof(settings.ClientID) - })); + results.Add(new ValidationResult(S["The Client ID is required."], new[] { nameof(settings.ClientID) })); } if (string.IsNullOrEmpty(settings.ClientSecret)) { - results.Add(new ValidationResult(S["The Client Secret is required."], new[] - { - nameof(settings.ClientSecret) - })); + results.Add(new ValidationResult(S["The Client Secret is required."], new[] { nameof(settings.ClientSecret) })); } return results; diff --git a/src/OrchardCore.Modules/OrchardCore.Google/Extensions/OrchardCoreBuilderExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Google/Extensions/OrchardCoreBuilderExtensions.cs index 9d36371cb00..779b7c79d44 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/Extensions/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/Extensions/OrchardCoreBuilderExtensions.cs @@ -8,12 +8,14 @@ public static class OrchardCoreBuilderExtensions { public static OrchardCoreBuilder ConfigureGoogleSettings(this OrchardCoreBuilder builder) { - builder.ConfigureServices((tenantServices, serviceProvider) => - { - var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Google"); + builder.ConfigureServices( + (tenantServices, serviceProvider) => + { + var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Google"); - tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); - }); + tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); + } + ); return builder; } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/GoogleAnalyticsPermissionsProvider.cs b/src/OrchardCore.Modules/OrchardCore.Google/GoogleAnalyticsPermissionsProvider.cs index 42943baa0f6..79d88ba093d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/GoogleAnalyticsPermissionsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/GoogleAnalyticsPermissionsProvider.cs @@ -8,20 +8,9 @@ public class GoogleAnalyticsPermissionsProvider : IPermissionProvider { public static readonly Permission ManageGoogleAnalytics = Permissions.ManageGoogleAnalytics; - private readonly IEnumerable _allPermissions = - [ - ManageGoogleAnalytics, - ]; + private readonly IEnumerable _allPermissions = [ManageGoogleAnalytics,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationAdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationAdminMenu.cs index 425dfc883e9..2f88f09d853 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationAdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationAdminMenu.cs @@ -9,11 +9,7 @@ namespace OrchardCore.Google [Feature(GoogleConstants.Features.GoogleAuthentication)] public class GoogleAuthenticationAdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", GoogleConstants.Features.GoogleAuthentication }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", GoogleConstants.Features.GoogleAuthentication }, }; protected readonly IStringLocalizer S; @@ -29,17 +25,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Authentication"], authentication => authentication - .Add(S["Google"], S["Google"].PrefixPosition(), google => google - .AddClass("google") - .Id("google") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageGoogleAuthentication) - .LocalNav() + builder.Add( + S["Security"], + security => + security.Add( + S["Authentication"], + authentication => + authentication.Add( + S["Google"], + S["Google"].PrefixPosition(), + google => + google.AddClass("google").Id("google").Action("Index", "Admin", _routeValues).Permission(Permissions.ManageGoogleAuthentication).LocalNav() + ) ) - ) ); return Task.CompletedTask; @@ -49,11 +47,7 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) [Feature(GoogleConstants.Features.GoogleAnalytics)] public class GoogleAnalyticsAdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", GoogleConstants.Features.GoogleAnalytics }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", GoogleConstants.Features.GoogleAnalytics }, }; protected readonly IStringLocalizer S; @@ -69,17 +63,25 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Google Analytics"], S["Google Analytics"].PrefixPosition(), google => google - .AddClass("googleAnalytics").Id("googleAnalytics") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageGoogleAnalytics) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Google Analytics"], + S["Google Analytics"].PrefixPosition(), + google => + google + .AddClass("googleAnalytics") + .Id("googleAnalytics") + .Action("Index", "Admin", _routeValues) + .Permission(Permissions.ManageGoogleAnalytics) + .LocalNav() + ) ) - ); + ); return Task.CompletedTask; } @@ -88,11 +90,7 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) [Feature(GoogleConstants.Features.GoogleTagManager)] public class GoogleTagManagerAdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", GoogleConstants.Features.GoogleTagManager }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", GoogleConstants.Features.GoogleTagManager }, }; protected readonly IStringLocalizer S; @@ -108,18 +106,25 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Google Tag Manager"], S["Google Tag Manager"].PrefixPosition(), google => google - .AddClass("googleTagManager") - .Id("googleTagManager") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageGoogleTagManager) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Google Tag Manager"], + S["Google Tag Manager"].PrefixPosition(), + google => + google + .AddClass("googleTagManager") + .Id("googleTagManager") + .Action("Index", "Admin", _routeValues) + .Permission(Permissions.ManageGoogleTagManager) + .LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationPermissionProvider.cs b/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationPermissionProvider.cs index 115f8274ed9..a2a24efb2b5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationPermissionProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationPermissionProvider.cs @@ -8,20 +8,9 @@ public class GoogleAuthenticationPermissionProvider : IPermissionProvider { public static readonly Permission ManageGoogleAuthentication = Permissions.ManageGoogleAuthentication; - private readonly IEnumerable _allPermissions = - [ - ManageGoogleAuthentication, - ]; + private readonly IEnumerable _allPermissions = [ManageGoogleAuthentication,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationStartup.cs b/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationStartup.cs index 6460b689ad3..81401559cc7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationStartup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationStartup.cs @@ -35,14 +35,16 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped, GoogleAuthenticationSettingsDisplayDriver>(); services.AddScoped(); // Register the options initializers required by the Google Handler. - services.TryAddEnumerable(new[] - { - // Orchard-specific initializers: - ServiceDescriptor.Transient, GoogleOptionsConfiguration>(), - ServiceDescriptor.Transient, GoogleOptionsConfiguration>(), - // Built-in initializers: - ServiceDescriptor.Transient, OAuthPostConfigureOptions>() - }); + services.TryAddEnumerable( + new[] + { + // Orchard-specific initializers: + ServiceDescriptor.Transient, GoogleOptionsConfiguration>(), + ServiceDescriptor.Transient, GoogleOptionsConfiguration>(), + // Built-in initializers: + ServiceDescriptor.Transient, OAuthPostConfigureOptions>() + } + ); services.AddTransient, GoogleAuthenticationSettingsConfiguration>(); } @@ -58,10 +60,12 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped, GoogleAnalyticsSettingsDisplayDriver>(); services.AddScoped(); - services.Configure((options) => - { - options.Filters.Add(); - }); + services.Configure( + (options) => + { + options.Filters.Add(); + } + ); } } @@ -75,10 +79,12 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped, GoogleTagManagerSettingsDisplayDriver>(); services.AddScoped(); - services.Configure((options) => - { - options.Filters.Add(); - }); + services.Configure( + (options) => + { + options.Filters.Add(); + } + ); } } @@ -88,7 +94,10 @@ public class GoogleAuthenticationDeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddSiteSettingsPropertyDeploymentStep(S => S["Google Authentication Settings"], S => S["Exports the Google Authentication settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Google Authentication Settings"], + S => S["Exports the Google Authentication settings."] + ); } } @@ -98,7 +107,10 @@ public class GoogleAnalyticsDeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddSiteSettingsPropertyDeploymentStep(S => S["Google Analytics Settings"], S => S["Exports the Google Analytics settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Google Analytics Settings"], + S => S["Exports the Google Analytics settings."] + ); } } @@ -108,7 +120,10 @@ public class GoogleTagManagerDeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddSiteSettingsPropertyDeploymentStep(S => S["Google Tag Manager Settings"], S => S["Exports the Google Tag Manager settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Google Tag Manager Settings"], + S => S["Exports the Google Tag Manager settings."] + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/GoogleTagManagerPermissionProvider.cs b/src/OrchardCore.Modules/OrchardCore.Google/GoogleTagManagerPermissionProvider.cs index e4d55201421..e8d96e62612 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/GoogleTagManagerPermissionProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/GoogleTagManagerPermissionProvider.cs @@ -8,20 +8,9 @@ public class GoogleTagManagerPermissionProvider : IPermissionProvider { public static readonly Permission ManageGoogleTagManager = Permissions.ManageGoogleTagManager; - private readonly IEnumerable _allPermissions = - [ - ManageGoogleTagManager, - ]; + private readonly IEnumerable _allPermissions = [ManageGoogleTagManager,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Google/Manifest.cs index 5ca5c03429d..83346a8bc1a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/Manifest.cs @@ -16,16 +16,6 @@ Description = "Authenticates users with their Google Account." )] -[assembly: Feature( - Id = GoogleConstants.Features.GoogleAnalytics, - Name = "Google Analytics", - Category = "Google", - Description = "Integrate Google Analytics (gtag.js)" -)] +[assembly: Feature(Id = GoogleConstants.Features.GoogleAnalytics, Name = "Google Analytics", Category = "Google", Description = "Integrate Google Analytics (gtag.js)")] -[assembly: Feature( - Id = GoogleConstants.Features.GoogleTagManager, - Name = "Google Tag Manager", - Category = "Google", - Description = "Integrate Google Tag Manager" -)] +[assembly: Feature(Id = GoogleConstants.Features.GoogleTagManager, Name = "Google Tag Manager", Category = "Google", Description = "Integrate Google Tag Manager")] diff --git a/src/OrchardCore.Modules/OrchardCore.Google/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Google/Permissions.cs index d7f030d73d2..ceb25dc323f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/Permissions.cs @@ -4,12 +4,9 @@ namespace OrchardCore.Google; public partial class Permissions { - public static readonly Permission ManageGoogleAuthentication - = new("ManageGoogleAuthentication", "Manage Google Authentication settings"); + public static readonly Permission ManageGoogleAuthentication = new("ManageGoogleAuthentication", "Manage Google Authentication settings"); - public static readonly Permission ManageGoogleAnalytics - = new("ManageGoogleAnalytics", "Manage Google Analytics settings"); + public static readonly Permission ManageGoogleAnalytics = new("ManageGoogleAnalytics", "Manage Google Analytics settings"); - public static readonly Permission ManageGoogleTagManager - = new("ManageGoogleTagManager", "Manage Google Tag Manager settings"); + public static readonly Permission ManageGoogleTagManager = new("ManageGoogleTagManager", "Manage Google Tag Manager settings"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/TagManager/Drivers/GoogleTagManagerSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Google/TagManager/Drivers/GoogleTagManagerSettingsDisplayDriver.cs index 1eaa91a8b24..c06b64eff86 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/TagManager/Drivers/GoogleTagManagerSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/TagManager/Drivers/GoogleTagManagerSettingsDisplayDriver.cs @@ -15,9 +15,7 @@ public class GoogleTagManagerSettingsDisplayDriver : SectionDisplayDriver EditAsync(GoogleTagManagerSettings se return null; } - return Initialize("GoogleTagManagerSettings_Edit", model => - { - model.ContainerID = settings.ContainerID; - }).Location("Content:5").OnGroup(GoogleConstants.Features.GoogleTagManager); + return Initialize( + "GoogleTagManagerSettings_Edit", + model => + { + model.ContainerID = settings.ContainerID; + } + ) + .Location("Content:5") + .OnGroup(GoogleConstants.Features.GoogleTagManager); } public override async Task UpdateAsync(GoogleTagManagerSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Google/TagManager/GoogleTagManagerFilter.cs b/src/OrchardCore.Modules/OrchardCore.Google/TagManager/GoogleTagManagerFilter.cs index 75365c9670c..4fbd964e277 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/TagManager/GoogleTagManagerFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/TagManager/GoogleTagManagerFilter.cs @@ -16,9 +16,7 @@ public class GoogleTagManagerFilter : IAsyncResultFilter private HtmlString _scriptsCache; - public GoogleTagManagerFilter( - IResourceManager resourceManager, - ISiteService siteService) + public GoogleTagManagerFilter(IResourceManager resourceManager, ISiteService siteService) { _resourceManager = resourceManager; _siteService = siteService; @@ -37,7 +35,11 @@ public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultE if (!string.IsNullOrWhiteSpace(settings?.ContainerID)) { - _scriptsCache = new HtmlString("\n\n"); + _scriptsCache = new HtmlString( + "\n\n" + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.HomeRoute/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.HomeRoute/Manifest.cs index 0480d41050a..00c01c93a66 100644 --- a/src/OrchardCore.Modules/OrchardCore.HomeRoute/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.HomeRoute/Manifest.cs @@ -1,11 +1,6 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Home Route", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Home Route", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.HomeRoute", diff --git a/src/OrchardCore.Modules/OrchardCore.HomeRoute/Routing/HomeRouteValuesAddressScheme.cs b/src/OrchardCore.Modules/OrchardCore.HomeRoute/Routing/HomeRouteValuesAddressScheme.cs index 9926881c3b0..f8d010f6353 100644 --- a/src/OrchardCore.Modules/OrchardCore.HomeRoute/Routing/HomeRouteValuesAddressScheme.cs +++ b/src/OrchardCore.Modules/OrchardCore.HomeRoute/Routing/HomeRouteValuesAddressScheme.cs @@ -41,14 +41,7 @@ public IEnumerable FindEndpoints(RouteValuesAddress address) } } - var endpoint = new RouteEndpoint - ( - c => null, - RoutePatternFactory.Parse(string.Empty, routeValues, null), - 0, - null, - null - ); + var endpoint = new RouteEndpoint(c => null, RoutePatternFactory.Parse(string.Empty, routeValues, null), 0, null, null); return new[] { endpoint }; } diff --git a/src/OrchardCore.Modules/OrchardCore.Html/Drivers/HtmlBodyPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Html/Drivers/HtmlBodyPartDisplayDriver.cs index dfe53cdbf94..207ebd5d5a8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Html/Drivers/HtmlBodyPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Html/Drivers/HtmlBodyPartDisplayDriver.cs @@ -27,11 +27,13 @@ public class HtmlBodyPartDisplayDriver : ContentPartDisplayDriver private readonly IShortcodeService _shortcodeService; protected readonly IStringLocalizer S; - public HtmlBodyPartDisplayDriver(ILiquidTemplateManager liquidTemplateManager, + public HtmlBodyPartDisplayDriver( + ILiquidTemplateManager liquidTemplateManager, IHtmlSanitizerService htmlSanitizerService, HtmlEncoder htmlEncoder, IShortcodeService shortcodeService, - IStringLocalizer localizer) + IStringLocalizer localizer + ) { _liquidTemplateManager = liquidTemplateManager; _htmlSanitizerService = htmlSanitizerService; @@ -49,13 +51,16 @@ public override IDisplayResult Display(HtmlBodyPart HtmlBodyPart, BuildPartDispl public override IDisplayResult Edit(HtmlBodyPart HtmlBodyPart, BuildPartEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.Html = HtmlBodyPart.Html; - model.ContentItem = HtmlBodyPart.ContentItem; - model.HtmlBodyPart = HtmlBodyPart; - model.TypePartDefinition = context.TypePartDefinition; - }); + return Initialize( + GetEditorShapeType(context), + model => + { + model.Html = HtmlBodyPart.Html; + model.ContentItem = HtmlBodyPart.ContentItem; + model.HtmlBodyPart = HtmlBodyPart; + model.TypePartDefinition = context.TypePartDefinition; + } + ); } public override async Task UpdateAsync(HtmlBodyPart model, IUpdateModel updater, UpdatePartEditorContext context) @@ -69,7 +74,11 @@ public override async Task UpdateAsync(HtmlBodyPart model, IUpda if (!string.IsNullOrEmpty(viewModel.Html) && !_liquidTemplateManager.Validate(viewModel.Html, out var errors)) { var partName = context.TypePartDefinition.DisplayName(); - updater.ModelState.AddModelError(Prefix, nameof(viewModel.Html), S["{0} doesn't contain a valid Liquid expression. Details: {1}", partName, string.Join(" ", errors)]); + updater.ModelState.AddModelError( + Prefix, + nameof(viewModel.Html), + S["{0} doesn't contain a valid Liquid expression. Details: {1}", partName, string.Join(" ", errors)] + ); } else { @@ -89,16 +98,18 @@ private async ValueTask BuildViewModelAsync(HtmlBodyPartViewModel model, HtmlBod if (!settings.SanitizeHtml) { - model.Html = await _liquidTemplateManager.RenderStringAsync(htmlBodyPart.Html, _htmlEncoder, model, - new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) }); + model.Html = await _liquidTemplateManager.RenderStringAsync( + htmlBodyPart.Html, + _htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); } - model.Html = await _shortcodeService.ProcessAsync(model.Html, - new Context - { - ["ContentItem"] = htmlBodyPart.ContentItem, - ["TypePartDefinition"] = context.TypePartDefinition - }); + model.Html = await _shortcodeService.ProcessAsync( + model.Html, + new Context { ["ContentItem"] = htmlBodyPart.ContentItem, ["TypePartDefinition"] = context.TypePartDefinition } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Html/GraphQL/HtmlBodyQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Html/GraphQL/HtmlBodyQueryObjectType.cs index d6f32392687..7c236e2f5a9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Html/GraphQL/HtmlBodyQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Html/GraphQL/HtmlBodyQueryObjectType.cs @@ -25,9 +25,7 @@ public HtmlBodyQueryObjectType(IStringLocalizer S) Name = "HtmlBodyPart"; Description = S["Content stored as HTML."]; - Field("html") - .Description(S["the HTML content"]) - .ResolveLockedAsync(RenderHtml); + Field("html").Description(S["the HTML content"]).ResolveLockedAsync(RenderHtml); } private static async ValueTask RenderHtml(IResolveFieldContext ctx) @@ -52,15 +50,15 @@ private static async ValueTask RenderHtml(IResolveFieldContext(); var htmlEncoder = ctx.RequestServices.GetService(); - html = await liquidTemplateManager.RenderStringAsync(html, htmlEncoder, model, new Dictionary { ["ContentItem"] = new ObjectValue(model.ContentItem) }); + html = await liquidTemplateManager.RenderStringAsync( + html, + htmlEncoder, + model, + new Dictionary { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); } - return await shortcodeService.ProcessAsync(html, - new Context - { - ["ContentItem"] = ctx.Source.ContentItem, - ["TypePartDefinition"] = contentTypePartDefinition - }); + return await shortcodeService.ProcessAsync(html, new Context { ["ContentItem"] = ctx.Source.ContentItem, ["TypePartDefinition"] = contentTypePartDefinition }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Html/Handlers/HtmlBodyPartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Html/Handlers/HtmlBodyPartHandler.cs index 6c9d08f9af7..76beb8b2ea6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Html/Handlers/HtmlBodyPartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Html/Handlers/HtmlBodyPartHandler.cs @@ -23,10 +23,12 @@ public class HtmlBodyPartHandler : ContentPartHandler private readonly ILiquidTemplateManager _liquidTemplateManager; private readonly HtmlEncoder _htmlEncoder; - public HtmlBodyPartHandler(IContentDefinitionManager contentDefinitionManager, + public HtmlBodyPartHandler( + IContentDefinitionManager contentDefinitionManager, IShortcodeService shortcodeService, ILiquidTemplateManager liquidTemplateManager, - HtmlEncoder htmlEncoder) + HtmlEncoder htmlEncoder + ) { _contentDefinitionManager = contentDefinitionManager; _shortcodeService = shortcodeService; @@ -55,16 +57,15 @@ public override Task GetContentItemAspectAsync(ContentItemAspectContext context, ContentItem = part.ContentItem, }; - html = await _liquidTemplateManager.RenderStringAsync(html, _htmlEncoder, model, - new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) }); + html = await _liquidTemplateManager.RenderStringAsync( + html, + _htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); } - html = await _shortcodeService.ProcessAsync(html, - new Context - { - ["ContentItem"] = part.ContentItem, - ["TypePartDefinition"] = contentTypePartDefinition - }); + html = await _shortcodeService.ProcessAsync(html, new Context { ["ContentItem"] = part.ContentItem, ["TypePartDefinition"] = contentTypePartDefinition }); bodyAspect.Body = new HtmlString(html); } diff --git a/src/OrchardCore.Modules/OrchardCore.Html/Media/MediaShapes.cs b/src/OrchardCore.Modules/OrchardCore.Html/Media/MediaShapes.cs index 80d7f65d285..3bcc4a967b1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Html/Media/MediaShapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.Html/Media/MediaShapes.cs @@ -9,7 +9,8 @@ public class MediaShapes : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("HtmlBodyPart_Edit") + builder + .Describe("HtmlBodyPart_Edit") .OnDisplaying(displaying => { var editor = displaying.Shape; diff --git a/src/OrchardCore.Modules/OrchardCore.Html/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Html/Migrations.cs index 72c8004bbad..0d34fb78baa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Html/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Html/Migrations.cs @@ -19,10 +19,7 @@ public class Migrations : DataMigration private readonly ILogger _logger; private readonly IContentDefinitionManager _contentDefinitionManager; - public Migrations( - IContentDefinitionManager contentDefinitionManager, - ISession session, - ILogger logger) + public Migrations(IContentDefinitionManager contentDefinitionManager, ISession session, ILogger logger) { _contentDefinitionManager = contentDefinitionManager; _session = session; @@ -31,9 +28,10 @@ public Migrations( public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("HtmlBodyPart", builder => builder - .Attachable() - .WithDescription("Provides an HTML Body for your content item.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "HtmlBodyPart", + builder => builder.Attachable().WithDescription("Provides an HTML Body for your content item.") + ); // Shortcut other migration steps on new content definition schemas. return 5; @@ -138,10 +136,17 @@ public async Task UpdateFrom4() { if (contentType.Parts.Any(x => x.PartDefinition.Name == "HtmlBodyPart")) { - await _contentDefinitionManager.AlterTypeDefinitionAsync(contentType.Name, x => x.WithPart("HtmlBodyPart", part => - { - part.MergeSettings(x => x.SanitizeHtml = false); - })); + await _contentDefinitionManager.AlterTypeDefinitionAsync( + contentType.Name, + x => + x.WithPart( + "HtmlBodyPart", + part => + { + part.MergeSettings(x => x.SanitizeHtml = false); + } + ) + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartMonacoEditorSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartMonacoEditorSettingsDriver.cs index de5000334ec..9964c24353a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartMonacoEditorSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartMonacoEditorSettingsDriver.cs @@ -23,16 +23,19 @@ public HtmlBodyPartMonacoEditorSettingsDriver(IStringLocalizer("HtmlBodyPartMonacoSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); - if (string.IsNullOrWhiteSpace(settings.Options)) - { - settings.Options = JConvert.SerializeObject(new { automaticLayout = true, language = "html" }, JOptions.Indented); - } - model.Options = settings.Options; - }) - .Location("Editor"); + return Initialize( + "HtmlBodyPartMonacoSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); + if (string.IsNullOrWhiteSpace(settings.Options)) + { + settings.Options = JConvert.SerializeObject(new { automaticLayout = true, language = "html" }, JOptions.Indented); + } + model.Options = settings.Options; + } + ) + .Location("Editor"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartSettingsDisplayDriver.cs index f5e3902f4b1..0b202658812 100644 --- a/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartSettingsDisplayDriver.cs @@ -12,13 +12,16 @@ public class HtmlBodyPartSettingsDisplayDriver : ContentTypePartDefinitionDispla { public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("HtmlBodyPartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + "HtmlBodyPartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); - model.SanitizeHtml = settings.SanitizeHtml; - }) - .Location("Content:20"); + model.SanitizeHtml = settings.SanitizeHtml; + } + ) + .Location("Content:20"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartTrumbowygEditorSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartTrumbowygEditorSettingsDriver.cs index 0ced177131b..afe65142104 100644 --- a/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartTrumbowygEditorSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Html/Settings/HtmlBodyPartTrumbowygEditorSettingsDriver.cs @@ -21,14 +21,17 @@ public HtmlBodyPartTrumbowygEditorSettingsDriver(IStringLocalizer("HtmlBodyPartTrumbowygSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); - - model.Options = settings.Options; - model.InsertMediaWithUrl = settings.InsertMediaWithUrl; - }) - .Location("Editor"); + return Initialize( + "HtmlBodyPartTrumbowygSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); + + model.Options = settings.Options; + model.InsertMediaWithUrl = settings.InsertMediaWithUrl; + } + ) + .Location("Editor"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Html/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Html/Startup.cs index 4ba19266480..9344ef44070 100644 --- a/src/OrchardCore.Modules/OrchardCore.Html/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Html/Startup.cs @@ -22,9 +22,7 @@ public override void ConfigureServices(IServiceCollection services) services.Configure(o => o.MemberAccessStrategy.Register()); // Body Part - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Https/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Https/AdminMenu.cs index 4ddb15109ac..a5672a80d63 100644 --- a/src/OrchardCore.Modules/OrchardCore.Https/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Https/AdminMenu.cs @@ -8,11 +8,7 @@ namespace OrchardCore.Https { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", HttpsSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", HttpsSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -28,16 +24,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Settings"], settings => settings - .Add(S["HTTPS"], S["HTTPS"].PrefixPosition(), https => https - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageHttps) - .LocalNav() - ) + builder.Add( + S["Security"], + security => + security.Add( + S["Settings"], + settings => + settings.Add( + S["HTTPS"], + S["HTTPS"].PrefixPosition(), + https => https.Action("Index", "Admin", _routeValues).Permission(Permissions.ManageHttps).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Https/Drivers/HttpsSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Https/Drivers/HttpsSettingsDisplayDriver.cs index f9d84ae91bb..64ed187268d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Https/Drivers/HttpsSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Https/Drivers/HttpsSettingsDisplayDriver.cs @@ -24,12 +24,14 @@ public class HttpsSettingsDisplayDriver : SectionDisplayDriver htmlLocalizer) + IHtmlLocalizer htmlLocalizer + ) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -47,22 +49,24 @@ public override async Task EditAsync(HttpsSettings settings, Bui return null; } - return Initialize("HttpsSettings_Edit", async model => - { - var isHttpsRequest = _httpContextAccessor.HttpContext.Request.IsHttps; + return Initialize( + "HttpsSettings_Edit", + async model => + { + var isHttpsRequest = _httpContextAccessor.HttpContext.Request.IsHttps; - if (!isHttpsRequest) - await _notifier.WarningAsync(H["For safety, Enabling require HTTPS over HTTP has been prevented."]); + if (!isHttpsRequest) + await _notifier.WarningAsync(H["For safety, Enabling require HTTPS over HTTP has been prevented."]); - model.EnableStrictTransportSecurity = settings.EnableStrictTransportSecurity; - model.IsHttpsRequest = isHttpsRequest; - model.RequireHttps = settings.RequireHttps; - model.RequireHttpsPermanent = settings.RequireHttpsPermanent; - model.SslPort = settings.SslPort ?? - (isHttpsRequest && !settings.RequireHttps - ? _httpContextAccessor.HttpContext.Request.Host.Port - : null); - }).Location("Content:2").OnGroup(GroupId); + model.EnableStrictTransportSecurity = settings.EnableStrictTransportSecurity; + model.IsHttpsRequest = isHttpsRequest; + model.RequireHttps = settings.RequireHttps; + model.RequireHttpsPermanent = settings.RequireHttpsPermanent; + model.SslPort = settings.SslPort ?? (isHttpsRequest && !settings.RequireHttps ? _httpContextAccessor.HttpContext.Request.Host.Port : null); + } + ) + .Location("Content:2") + .OnGroup(GroupId); } public override async Task UpdateAsync(HttpsSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Https/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Https/Permissions.cs index a7ba0125afa..0b4aaa10e5e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Https/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Https/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageHttps = new("ManageHttps", "Manage HTTPS"); - private readonly IEnumerable _allPermissions = - [ - ManageHttps, - ]; + private readonly IEnumerable _allPermissions = [ManageHttps,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Https/Properties/AssemblyInfo.cs b/src/OrchardCore.Modules/OrchardCore.Https/Properties/AssemblyInfo.cs index 35b5603e505..4d640ba13e3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Https/Properties/AssemblyInfo.cs +++ b/src/OrchardCore.Modules/OrchardCore.Https/Properties/AssemblyInfo.cs @@ -9,8 +9,8 @@ [assembly: AssemblyProduct("OrchardCore.Https")] [assembly: AssemblyTrademark("")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] diff --git a/src/OrchardCore.Modules/OrchardCore.Https/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Https/Startup.cs index f95a90e0103..aa69acabbc1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Https/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Https/Startup.cs @@ -41,17 +41,20 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); - services.AddOptions() - .Configure((options, service) => - { - var settings = service.GetSettingsAsync().GetAwaiter().GetResult(); - if (settings.RequireHttpsPermanent) + services + .AddOptions() + .Configure( + (options, service) => { - options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect; - } + var settings = service.GetSettingsAsync().GetAwaiter().GetResult(); + if (settings.RequireHttpsPermanent) + { + options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect; + } - options.HttpsPort = settings.SslPort; - }); + options.HttpsPort = settings.SslPort; + } + ); services.AddHsts(options => { diff --git a/src/OrchardCore.Modules/OrchardCore.Indexing/IndexingTaskManager.cs b/src/OrchardCore.Modules/OrchardCore.Indexing/IndexingTaskManager.cs index 1acb5cba94e..92deb931b35 100644 --- a/src/OrchardCore.Modules/OrchardCore.Indexing/IndexingTaskManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.Indexing/IndexingTaskManager.cs @@ -37,7 +37,8 @@ public IndexingTaskManager( IStore store, IDbConnectionAccessor dbConnectionAccessor, IHttpContextAccessor httpContextAccessor, - ILogger logger) + ILogger logger + ) { _clock = clock; _store = store; @@ -130,7 +131,8 @@ private async Task FlushAsync(ShellScope scope, IEnumerable tasks) // Page delete statements to prevent the limits from IN sql statements. var pageSize = 100; - var deleteCmd = $"delete from {dialect.QuoteForTableName(table, _store.Configuration.Schema)} where {dialect.QuoteForColumnName("ContentItemId")} {dialect.InOperator("@Ids")};"; + var deleteCmd = + $"delete from {dialect.QuoteForTableName(table, _store.Configuration.Schema)} where {dialect.QuoteForColumnName("ContentItemId")} {dialect.InOperator("@Ids")};"; do { @@ -143,7 +145,8 @@ private async Task FlushAsync(ShellScope scope, IEnumerable tasks) } } while (ids.Length > 0); - var insertCmd = $"insert into {dialect.QuoteForTableName(table, _store.Configuration.Schema)} ({dialect.QuoteForColumnName("CreatedUtc")}, {dialect.QuoteForColumnName("ContentItemId")}, {dialect.QuoteForColumnName("Type")}) values (@CreatedUtc, @ContentItemId, @Type);"; + var insertCmd = + $"insert into {dialect.QuoteForTableName(table, _store.Configuration.Schema)} ({dialect.QuoteForColumnName("CreatedUtc")}, {dialect.QuoteForColumnName("ContentItemId")}, {dialect.QuoteForColumnName("Type")}) values (@CreatedUtc, @ContentItemId, @Type);"; await transaction.Connection.ExecuteAsync(insertCmd, localQueue, transaction); await transaction.CommitAsync(); diff --git a/src/OrchardCore.Modules/OrchardCore.Indexing/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Indexing/Migrations.cs index daa2af05675..ab49ffa7dbb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Indexing/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Indexing/Migrations.cs @@ -8,16 +8,17 @@ public class Migrations : DataMigration { public async Task CreateAsync() { - await SchemaBuilder.CreateTableAsync(nameof(IndexingTask), table => table - .Column("Id", col => col.PrimaryKey().Identity()) - .Column("ContentItemId", c => c.WithLength(26)) - .Column("CreatedUtc", col => col.NotNull()) - .Column("Type") + await SchemaBuilder.CreateTableAsync( + nameof(IndexingTask), + table => + table + .Column("Id", col => col.PrimaryKey().Identity()) + .Column("ContentItemId", c => c.WithLength(26)) + .Column("CreatedUtc", col => col.NotNull()) + .Column("Type") ); - await SchemaBuilder.AlterTableAsync(nameof(IndexingTask), table => table - .CreateIndex("IDX_IndexingTask_ContentItemId", "ContentItemId") - ); + await SchemaBuilder.AlterTableAsync(nameof(IndexingTask), table => table.CreateIndex("IDX_IndexingTask_ContentItemId", "ContentItemId")); return 1; } diff --git a/src/OrchardCore.Modules/OrchardCore.Indexing/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Indexing/Permissions.cs index e30c801d08b..94e10e134e1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Indexing/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Indexing/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageIndexes = new("ManageIndexes", "Manage Indexes"); - private readonly IEnumerable _allPermissions = - [ - ManageIndexes, - ]; + private readonly IEnumerable _allPermissions = [ManageIndexes,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Layers/AdminMenu.cs index 3d89f76db7e..5d8c06eb4fd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/AdminMenu.cs @@ -8,11 +8,7 @@ namespace OrchardCore.Layers { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", LayerSiteSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", LayerSiteSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -28,21 +24,25 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Design"], design => design - .Add(S["Settings"], settings => settings - .Add(S["Zones"], S["Zones"].PrefixPosition(), zones => zones - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageLayers) - .LocalNav() + builder.Add( + S["Design"], + design => + design + .Add( + S["Settings"], + settings => + settings.Add( + S["Zones"], + S["Zones"].PrefixPosition(), + zones => zones.Action("Index", "Admin", _routeValues).Permission(Permissions.ManageLayers).LocalNav() + ) + ) + .Add( + S["Widgets"], + S["Widgets"].PrefixPosition(), + widgets => widgets.Permission(Permissions.ManageLayers).Action("Index", "Admin", "OrchardCore.Layers").LocalNav() ) - ) - .Add(S["Widgets"], S["Widgets"].PrefixPosition(), widgets => widgets - .Permission(Permissions.ManageLayers) - .Action("Index", "Admin", "OrchardCore.Layers") - .LocalNav() - ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/AdminController.cs index c93048e9855..20db3bf2e65 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/AdminController.cs @@ -65,7 +65,8 @@ public AdminController( IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer, INotifier notifier, - ILogger logger) + ILogger logger + ) { _contentDefinitionManager = contentDefinitionManager; _contentManager = contentManager; @@ -120,8 +121,14 @@ public async Task Index() } else { - _logger.LogWarning("The Widget content item with id {ContentItemId} has no matching {ContentType} content type definition.", widget.ContentItem.ContentItemId, widget.ContentItem.ContentType); - await _notifier.WarningAsync(H["The Widget content item with id {0} has no matching {1} content type definition.", widget.ContentItem.ContentItemId, widget.ContentItem.ContentType]); + _logger.LogWarning( + "The Widget content item with id {ContentItemId} has no matching {ContentType} content type definition.", + widget.ContentItem.ContentItemId, + widget.ContentItem.ContentType + ); + await _notifier.WarningAsync( + H["The Widget content item with id {0} has no matching {1} content type definition.", widget.ContentItem.ContentItemId, widget.ContentItem.ContentType] + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/LayerRuleController.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/LayerRuleController.cs index 0e72e66b1fe..ee6b786d21e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/LayerRuleController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/LayerRuleController.cs @@ -37,7 +37,8 @@ public LayerRuleController( IConditionIdGenerator conditionIdGenerator, IHtmlLocalizer htmlLocalizer, INotifier notifier, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _displayManager = displayManager; _factories = factories; diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Deployment/AllLayersDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Deployment/AllLayersDeploymentSource.cs index 7b30fe6f5bf..d81e77cd4cc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Deployment/AllLayersDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Deployment/AllLayersDeploymentSource.cs @@ -17,19 +17,13 @@ public class AllLayersDeploymentSource : IDeploymentSource private readonly ISiteService _siteService; private readonly JsonSerializerOptions _serializationOptions; - public AllLayersDeploymentSource( - ILayerService layerService, - ISiteService siteService, - IOptions derivedTypesOptions) + public AllLayersDeploymentSource(ILayerService layerService, ISiteService siteService, IOptions derivedTypesOptions) { _layerService = layerService; _siteService = siteService; // The recipe step contains polymorphic types which need to be resolved - _serializationOptions = new() - { - TypeInfoResolver = new PolymorphicJsonTypeInfoResolver(derivedTypesOptions.Value) - }; + _serializationOptions = new() { TypeInfoResolver = new PolymorphicJsonTypeInfoResolver(derivedTypesOptions.Value) }; } public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult result) @@ -43,20 +37,12 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan var layers = await _layerService.GetLayersAsync(); - result.Steps.Add(new JsonObject - { - ["name"] = "Layers", - ["Layers"] = JArray.FromObject(layers.Layers, _serializationOptions), - }); + result.Steps.Add(new JsonObject { ["name"] = "Layers", ["Layers"] = JArray.FromObject(layers.Layers, _serializationOptions), }); var siteSettings = await _siteService.GetSiteSettingsAsync(); // Adding Layer settings - result.Steps.Add(new JsonObject - { - ["name"] = "Settings", - ["LayerSettings"] = JObject.FromObject(siteSettings.As()), - }); + result.Steps.Add(new JsonObject { ["name"] = "Settings", ["LayerSettings"] = JObject.FromObject(siteSettings.As()), }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Deployment/AllLayersDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Deployment/AllLayersDeploymentStepDriver.cs index b6955560792..717a6100e7a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Deployment/AllLayersDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Deployment/AllLayersDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class AllLayersDeploymentStepDriver : DisplayDriver EditAsync(ContentItem model, BuildEdi layerMetadata = new LayerMetadata(); // Are we loading an editor that requires layer metadata? - if (await context.Updater.TryUpdateModelAsync(layerMetadata, Prefix, m => m.Zone, m => m.Position) - && !string.IsNullOrEmpty(layerMetadata.Zone)) + if (await context.Updater.TryUpdateModelAsync(layerMetadata, Prefix, m => m.Zone, m => m.Position) && !string.IsNullOrEmpty(layerMetadata.Zone)) { model.Weld(layerMetadata); } @@ -51,13 +50,16 @@ public override async Task EditAsync(ContentItem model, BuildEdi } } - return Initialize("LayerMetadata_Edit", async shape => - { - shape.Title = model.DisplayText; - shape.LayerMetadata = layerMetadata; - shape.Layers = (await _layerService.GetLayersAsync()).Layers; - }) - .Location("Content:before"); + return Initialize( + "LayerMetadata_Edit", + async shape => + { + shape.Title = model.DisplayText; + shape.LayerMetadata = layerMetadata; + shape.Layers = (await _layerService.GetLayersAsync()).Layers; + } + ) + .Location("Content:before"); } public override async Task UpdateAsync(ContentItem model, UpdateEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Drivers/LayerSiteSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Drivers/LayerSiteSettingsDisplayDriver.cs index 18a9b028baa..d6cf4fb8bcb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Drivers/LayerSiteSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Drivers/LayerSiteSettingsDisplayDriver.cs @@ -18,9 +18,7 @@ public class LayerSiteSettingsDisplayDriver : SectionDisplayDriver EditAsync(LayerSettings settings, Bui return null; } - return Initialize("LayerSettings_Edit", model => - { - model.Zones = string.Join(", ", settings.Zones); - }).Location("Content:3").OnGroup(GroupId); + return Initialize( + "LayerSettings_Edit", + model => + { + model.Zones = string.Join(", ", settings.Zones); + } + ) + .Location("Content:3") + .OnGroup(GroupId); } public override async Task UpdateAsync(LayerSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/LayerQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/LayerQueryObjectType.cs index aabec619a61..507b24ffb5c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/LayerQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/LayerQueryObjectType.cs @@ -45,7 +45,8 @@ async ValueTask> GetWidgetsForLayerAsync(IResolveFieldC var layerWidgets = widgets?.Where(item => { var metadata = item.As(); - if (metadata == null) return false; + if (metadata == null) + return false; return metadata.Layer == context.Source.Name; }); diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/LayerWidgetQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/LayerWidgetQueryObjectType.cs index ac252281451..f6acf50af8f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/LayerWidgetQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/LayerWidgetQueryObjectType.cs @@ -11,21 +11,13 @@ public LayerWidgetQueryObjectType() { Name = "LayerWidget"; - Field("zone") - .Description("The name of the widget's zone.") - .Resolve(context => context.Source.As()?.Zone); + Field("zone").Description("The name of the widget's zone.").Resolve(context => context.Source.As()?.Zone); - Field("position") - .Description("The position of the widget in the zone.") - .Resolve(context => context.Source.As()?.Position); + Field("position").Description("The position of the widget in the zone.").Resolve(context => context.Source.As()?.Position); - Field("renderTitle") - .Description("Whether to render the widget's title.") - .Resolve(context => context.Source.As()?.RenderTitle); + Field("renderTitle").Description("Whether to render the widget's title.").Resolve(context => context.Source.As()?.RenderTitle); - Field("widget") - .Description("A widget on this layer.") - .Resolve(context => context.Source); + Field("widget").Description("A widget on this layer.").Resolve(context => context.Source); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/SiteLayersQuery.cs b/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/SiteLayersQuery.cs index 593b645cd27..b138741955b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/SiteLayersQuery.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/GraphQL/SiteLayersQuery.cs @@ -18,9 +18,7 @@ public class SiteLayersQuery : ISchemaBuilder protected readonly IStringLocalizer S; private readonly GraphQLContentOptions _graphQLContentOptions; - public SiteLayersQuery( - IStringLocalizer localizer, - IOptions graphQLContentOptions) + public SiteLayersQuery(IStringLocalizer localizer, IOptions graphQLContentOptions) { S = localizer; _graphQLContentOptions = graphQLContentOptions.Value; diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Handlers/LayerMetadataHandler.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Handlers/LayerMetadataHandler.cs index 1eaec4dfa1f..499e8d5a32d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Handlers/LayerMetadataHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Handlers/LayerMetadataHandler.cs @@ -36,7 +36,5 @@ private Task UpdateAsync(ContentItem contentItem) } } - public class LayerState : Document - { - } + public class LayerState : Document { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Indexes/LayerMetadataIndex.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Indexes/LayerMetadataIndex.cs index d43b04a3226..1eb711b0a74 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Indexes/LayerMetadataIndex.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Indexes/LayerMetadataIndex.cs @@ -13,7 +13,8 @@ public class LayerMetadataIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() + context + .For() .When(contentItem => contentItem.Has()) .Map(contentItem => { @@ -23,10 +24,7 @@ public override void Describe(DescribeContext context) return null; } - return new LayerMetadataIndex - { - Zone = layerMetadata.Zone, - }; + return new LayerMetadataIndex { Zone = layerMetadata.Zone, }; }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Manifest.cs index 748f0eba9f7..9e6419cc2a6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Manifest.cs @@ -1,21 +1,11 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Layers", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Layers", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Layers", Name = "Layers", Description = "Enables users to render Widgets across pages of the site based on conditions.", - Dependencies = - [ - "OrchardCore.Widgets", - "OrchardCore.Scripting", - "OrchardCore.Rules" - ], + Dependencies = ["OrchardCore.Widgets", "OrchardCore.Scripting", "OrchardCore.Rules"], Category = "Content" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Migrations.cs index 5a8339d0399..f94a84eab78 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Migrations.cs @@ -14,10 +14,7 @@ public class Migrations : DataMigration private readonly IConditionIdGenerator _conditionIdGenerator; private readonly IRuleMigrator _ruleMigrator; - public Migrations( - ILayerService layerService, - IConditionIdGenerator conditionIdGenerator, - IRuleMigrator ruleMigrator) + public Migrations(ILayerService layerService, IConditionIdGenerator conditionIdGenerator, IRuleMigrator ruleMigrator) { _layerService = layerService; _conditionIdGenerator = conditionIdGenerator; @@ -26,15 +23,9 @@ public Migrations( public async Task CreateAsync() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("Zone", c => c.WithLength(64)) - ); + await SchemaBuilder.CreateMapIndexTableAsync(table => table.Column("Zone", c => c.WithLength(64))); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LayerMetadataIndex_DocumentId", - "DocumentId", - "Zone") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_LayerMetadataIndex_DocumentId", "DocumentId", "Zone")); // Shortcut other migration steps on new content definition schemas. return 3; @@ -43,11 +34,7 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom1Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_LayerMetadataIndex_DocumentId", - "DocumentId", - "Zone") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_LayerMetadataIndex_DocumentId", "DocumentId", "Zone")); return 2; } diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Permissions.cs index b6bc3d3ca75..936a048a95f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageLayers = new("ManageLayers", "Manage layers"); - private readonly IEnumerable _allPermissions = - [ - ManageLayers, - ]; + private readonly IEnumerable _allPermissions = [ManageLayers,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Recipes/LayerStep.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Recipes/LayerStep.cs index 2c6ba7d64dd..9904babf1d0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Recipes/LayerStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Recipes/LayerStep.cs @@ -32,17 +32,15 @@ public LayerStep( IRuleMigrator ruleMigrator, IConditionIdGenerator conditionIdGenerator, IEnumerable factories, - IOptions derivedTypesOptions) + IOptions derivedTypesOptions + ) { _layerService = layerService; _ruleMigrator = ruleMigrator; _conditionIdGenerator = conditionIdGenerator; _factories = factories; - _serializationOptions = new() - { - TypeInfoResolver = new PolymorphicJsonTypeInfoResolver(derivedTypesOptions.Value) - }; + _serializationOptions = new() { TypeInfoResolver = new PolymorphicJsonTypeInfoResolver(derivedTypesOptions.Value) }; } public async Task ExecuteAsync(RecipeExecutionContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Services/DefaultLayersMethodProvider.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Services/DefaultLayersMethodProvider.cs index 5d441541580..561bf739e3a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Services/DefaultLayersMethodProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Services/DefaultLayersMethodProvider.cs @@ -26,84 +26,102 @@ public DefaultLayersMethodProvider() _isHomepage = new GlobalMethod { Name = "isHomepage", - Method = serviceProvider => (Func)(() => - { - var httpContext = serviceProvider.GetRequiredService().HttpContext; - var requestPath = httpContext.Request.Path.Value; - return requestPath == "/" || string.IsNullOrEmpty(requestPath); - }), + Method = serviceProvider => + (Func)( + () => + { + var httpContext = serviceProvider.GetRequiredService().HttpContext; + var requestPath = httpContext.Request.Path.Value; + return requestPath == "/" || string.IsNullOrEmpty(requestPath); + } + ), }; _isAnonymous = new GlobalMethod { Name = "isAnonymous", - Method = serviceProvider => (Func)(() => - { - var httpContext = serviceProvider.GetRequiredService().HttpContext; - return httpContext.User?.Identity.IsAuthenticated != true; - }), + Method = serviceProvider => + (Func)( + () => + { + var httpContext = serviceProvider.GetRequiredService().HttpContext; + return httpContext.User?.Identity.IsAuthenticated != true; + } + ), }; _isAuthenticated = new GlobalMethod { Name = "isAuthenticated", - Method = serviceProvider => (Func)(() => - { - var httpContext = serviceProvider.GetRequiredService().HttpContext; - return httpContext.User?.Identity.IsAuthenticated == true; - }), + Method = serviceProvider => + (Func)( + () => + { + var httpContext = serviceProvider.GetRequiredService().HttpContext; + return httpContext.User?.Identity.IsAuthenticated == true; + } + ), }; _isInRole = new GlobalMethod { Name = "isInRole", - Method = serviceProvider => (Func)(role => - { - var httpContext = serviceProvider.GetRequiredService().HttpContext; - var optionsAccessor = serviceProvider.GetRequiredService>(); - var roleClaimType = optionsAccessor.Value.ClaimsIdentity.RoleClaimType; + Method = serviceProvider => + (Func)( + role => + { + var httpContext = serviceProvider.GetRequiredService().HttpContext; + var optionsAccessor = serviceProvider.GetRequiredService>(); + var roleClaimType = optionsAccessor.Value.ClaimsIdentity.RoleClaimType; - // IsInRole() & HasClaim() are case sensitive. - return httpContext.User?.Claims.Any(claim => claim.Type == roleClaimType && claim.Value.Equals(role, StringComparison.OrdinalIgnoreCase)) == true; - }), + // IsInRole() & HasClaim() are case sensitive. + return httpContext.User?.Claims.Any(claim => claim.Type == roleClaimType && claim.Value.Equals(role, StringComparison.OrdinalIgnoreCase)) == true; + } + ), }; _url = new GlobalMethod { Name = "url", - Method = serviceProvider => (Func)(url => - { - if (url.StartsWith("~/", StringComparison.Ordinal)) - { - url = url[1..]; - } + Method = serviceProvider => + (Func)( + url => + { + if (url.StartsWith("~/", StringComparison.Ordinal)) + { + url = url[1..]; + } - var httpContext = serviceProvider.GetRequiredService().HttpContext; - var requestPath = httpContext.Request.Path.Value; + var httpContext = serviceProvider.GetRequiredService().HttpContext; + var requestPath = httpContext.Request.Path.Value; - // Tenant home page could have an empty string as a request path, where - // the default tenant does not. - if (string.IsNullOrEmpty(requestPath)) - { - requestPath = "/"; - } + // Tenant home page could have an empty string as a request path, where + // the default tenant does not. + if (string.IsNullOrEmpty(requestPath)) + { + requestPath = "/"; + } - return url.EndsWith('*') - ? requestPath.StartsWith(url.TrimEnd('*'), StringComparison.OrdinalIgnoreCase) - : string.Equals(requestPath, url, StringComparison.OrdinalIgnoreCase); - }), + return url.EndsWith('*') + ? requestPath.StartsWith(url.TrimEnd('*'), StringComparison.OrdinalIgnoreCase) + : string.Equals(requestPath, url, StringComparison.OrdinalIgnoreCase); + } + ), }; _culture = new GlobalMethod { Name = "culture", - Method = serviceProvider => (Func)(culture => - { - var currentCulture = CultureInfo.CurrentCulture; + Method = serviceProvider => + (Func)( + culture => + { + var currentCulture = CultureInfo.CurrentCulture; - return string.Equals(culture, currentCulture.Name, StringComparison.OrdinalIgnoreCase) || - string.Equals(culture, currentCulture.Parent.Name, StringComparison.OrdinalIgnoreCase); - }), + return string.Equals(culture, currentCulture.Name, StringComparison.OrdinalIgnoreCase) + || string.Equals(culture, currentCulture.Parent.Name, StringComparison.OrdinalIgnoreCase); + } + ), }; _allMethods = [_isAnonymous, _isAuthenticated, _isInRole, _isHomepage, _url, _culture]; diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Services/LayerFilter.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Services/LayerFilter.cs index a8f56f461b1..38dc216c613 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Services/LayerFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Services/LayerFilter.cs @@ -43,7 +43,8 @@ public LayerFilter( IMemoryCache memoryCache, IThemeManager themeManager, IAdminThemeService adminThemeService, - IVolatileDocumentManager layerStateManager) + IVolatileDocumentManager layerStateManager + ) { _contentDefinitionManager = contentDefinitionManager; _layerService = layerService; @@ -76,11 +77,7 @@ public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultE if (!_memoryCache.TryGetValue(WidgetsKey, out var cacheEntry) || cacheEntry.Identifier != layerState.Identifier) { - cacheEntry = new CacheEntry() - { - Identifier = layerState.Identifier, - Widgets = await _layerService.GetLayerWidgetsMetadataAsync(x => x.Published) - }; + cacheEntry = new CacheEntry() { Identifier = layerState.Identifier, Widgets = await _layerService.GetLayerWidgetsMetadataAsync(x => x.Published) }; _memoryCache.Set(WidgetsKey, cacheEntry); } @@ -124,11 +121,7 @@ public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultE widgetContent.Classes.Add("widget"); widgetContent.Classes.Add("widget-" + widget.ContentItem.ContentType.HtmlClassify()); - var wrapper = new WidgetWrapper - { - Widget = widget.ContentItem, - Content = widgetContent - }; + var wrapper = new WidgetWrapper { Widget = widget.ContentItem, Content = widgetContent }; wrapper.Metadata.Alternates.Add("Widget_Wrapper__" + widget.ContentItem.ContentType); wrapper.Metadata.Alternates.Add("Widget_Wrapper__Zone__" + widget.Zone); diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Services/LayerService.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Services/LayerService.cs index ee4b29c714e..ece7366ddad 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Services/LayerService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Services/LayerService.cs @@ -33,25 +33,16 @@ public LayerService(ISession session, IDocumentManager documentM /// public Task GetLayersAsync() => _documentManager.GetOrCreateImmutableAsync(); - public Task> GetLayerWidgetsAsync( - Expression> predicate) + public Task> GetLayerWidgetsAsync(Expression> predicate) { - return _session - .Query() - .With(predicate) - .ListAsync(); + return _session.Query().With(predicate).ListAsync(); } - public async Task> GetLayerWidgetsMetadataAsync( - Expression> predicate) + public async Task> GetLayerWidgetsMetadataAsync(Expression> predicate) { var allWidgets = await GetLayerWidgetsAsync(predicate); - return allWidgets - .Select(x => x.As()) - .Where(x => x != null) - .OrderBy(x => x.Position) - .ToList(); + return allWidgets.Select(x => x.As()).Where(x => x != null).OrderBy(x => x.Position).ToList(); } /// diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Startup.cs index e70d1b00d3a..4b3446f22c4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Startup.cs @@ -34,10 +34,12 @@ public override void ConfigureServices(IServiceCollection services) o.MemberAccessStrategy.Register(); }); - services.Configure((options) => - { - options.Filters.Add(typeof(LayerFilter)); - }); + services.Configure( + (options) => + { + options.Filters.Add(typeof(LayerFilter)); + } + ); services.AddScoped, LayerSiteSettingsDisplayDriver>(); services.AddContentPart(); diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/ViewModels/WidgetWrapper.cs b/src/OrchardCore.Modules/OrchardCore.Layers/ViewModels/WidgetWrapper.cs index a1111edfe90..73f540048f0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/ViewModels/WidgetWrapper.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/ViewModels/WidgetWrapper.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Layers.ViewModels { public class WidgetWrapper : ShapeViewModel { - public WidgetWrapper() : base("Widget_Wrapper") - { - } + public WidgetWrapper() + : base("Widget_Wrapper") { } public ContentItem Widget { get; set; } public IShape Content { get; set; } diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/Drivers/LiquidPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/Drivers/LiquidPartDisplayDriver.cs index ee03e39ef6c..b1263264b40 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/Drivers/LiquidPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/Drivers/LiquidPartDisplayDriver.cs @@ -23,10 +23,8 @@ public LiquidPartDisplayDriver(ILiquidTemplateManager liquidTemplatemanager, ISt public override IDisplayResult Display(LiquidPart liquidPart) { return Combine( - Initialize("LiquidPart", m => BuildViewModel(m, liquidPart)) - .Location("Detail", "Content"), - Initialize("LiquidPart_Summary", m => BuildViewModel(m, liquidPart)) - .Location("Summary", "Content") + Initialize("LiquidPart", m => BuildViewModel(m, liquidPart)).Location("Detail", "Content"), + Initialize("LiquidPart_Summary", m => BuildViewModel(m, liquidPart)).Location("Summary", "Content") ); } @@ -43,7 +41,11 @@ public override async Task UpdateAsync(LiquidPart model, IUpdate { if (!string.IsNullOrEmpty(viewModel.Liquid) && !_liquidTemplatemanager.Validate(viewModel.Liquid, out var errors)) { - updater.ModelState.AddModelError(Prefix, nameof(viewModel.Liquid), S["The Liquid Body doesn't contain a valid Liquid expression. Details: {0}", string.Join(" ", errors)]); + updater.ModelState.AddModelError( + Prefix, + nameof(viewModel.Liquid), + S["The Liquid Body doesn't contain a valid Liquid expression. Details: {0}", string.Join(" ", errors)] + ); } else { diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/AbsoluteUrlFilter.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/AbsoluteUrlFilter.cs index 44d525cdaec..4219694d0b3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/AbsoluteUrlFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/AbsoluteUrlFilter.cs @@ -14,6 +14,7 @@ public AbsoluteUrlFilter(IUrlHelperFactory urlHelperFactory) { _urlHelperFactory = urlHelperFactory; } + public ValueTask ProcessAsync(FluidValue input, FilterArguments arguments, LiquidTemplateContext context) { var relativePath = input.ToStringValue(); diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/LiquidFilter.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/LiquidFilter.cs index 4eac1e7b12b..e9a09b57c80 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/LiquidFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/LiquidFilter.cs @@ -15,6 +15,7 @@ public LiquidFilter(ILiquidTemplateManager liquidTemplateManager, HtmlEncoder ht _liquidTemplateManager = liquidTemplateManager; _htmlEncoder = htmlEncoder; } + public async ValueTask ProcessAsync(FluidValue input, FilterArguments arguments, LiquidTemplateContext ctx) { var content = await _liquidTemplateManager.RenderStringAsync(input.ToStringValue(), _htmlEncoder, arguments.At(0)); diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/SlugifyFilter.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/SlugifyFilter.cs index 006fd72a293..2014671b170 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/SlugifyFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/Filters/SlugifyFilter.cs @@ -13,6 +13,7 @@ public SlugifyFilter(ISlugService slugService) { _slugService = slugService; } + public ValueTask ProcessAsync(FluidValue input, FilterArguments arguments, LiquidTemplateContext ctx) { var text = input.ToStringValue(); diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/Handlers/LiquidPartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/Handlers/LiquidPartHandler.cs index f75a97cfa85..c190cb1db24 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/Handlers/LiquidPartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/Handlers/LiquidPartHandler.cs @@ -27,14 +27,14 @@ public override Task GetContentItemAspectAsync(ContentItemAspectContext context, { try { - var model = new LiquidPartViewModel() - { - LiquidPart = part, - ContentItem = part.ContentItem, - }; + var model = new LiquidPartViewModel() { LiquidPart = part, ContentItem = part.ContentItem, }; - var result = await _liquidTemplateManager.RenderHtmlContentAsync(part.Liquid, _htmlEncoder, model, - new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) }); + var result = await _liquidTemplateManager.RenderHtmlContentAsync( + part.Liquid, + _htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); bodyAspect.Body = result; } diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/Migrations.cs index fb586f7d92e..99f172044b6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/Migrations.cs @@ -16,9 +16,10 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("LiquidPart", builder => builder - .Attachable() - .WithDescription("Provides a Liquid formatted body for your content item.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "LiquidPart", + builder => builder.Attachable().WithDescription("Provides a Liquid formatted body for your content item.") + ); return 1; } diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/ResourceManagementOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/ResourceManagementOptionsConfiguration.cs index d9371a946e7..e9ede4f7a7a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/ResourceManagementOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/ResourceManagementOptionsConfiguration.cs @@ -11,16 +11,9 @@ static ResourceManagementOptionsConfiguration() { _manifest = new ResourceManifest(); - _manifest - .DefineScript("monaco-liquid-intellisense") - .SetUrl("~/OrchardCore.Liquid/monaco/liquid-intellisense.js") - .SetDependencies("monaco") - .SetVersion("1.0.0"); + _manifest.DefineScript("monaco-liquid-intellisense").SetUrl("~/OrchardCore.Liquid/monaco/liquid-intellisense.js").SetDependencies("monaco").SetVersion("1.0.0"); - _manifest - .DefineScript("liquid-intellisense") - .SetDependencies("monaco-liquid-intellisense") - .SetUrl("~/OrchardCore.Liquid/Scripts/liquid-intellisense.js"); + _manifest.DefineScript("liquid-intellisense").SetDependencies("monaco-liquid-intellisense").SetUrl("~/OrchardCore.Liquid/Scripts/liquid-intellisense.js"); } public void Configure(ResourceManagementOptions options) diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/ScriptsMiddleware.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/ScriptsMiddleware.cs index ad4598fb9ca..565d74b9256 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/ScriptsMiddleware.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/ScriptsMiddleware.cs @@ -53,7 +53,8 @@ public async Task Invoke(HttpContext httpContext) var filters = string.Join(',', templateOptions.Value.Filters.Select(x => $"'{x.Key}'")); var tags = string.Join(',', liquidViewParser.RegisteredTags.Select(x => $"'{x.Key}'")); - var script = $@"[{filters}].forEach(value=>{{if(!liquidFilters.includes(value)){{ liquidFilters.push(value);}}}}); + var script = + $@"[{filters}].forEach(value=>{{if(!liquidFilters.includes(value)){{ liquidFilters.push(value);}}}}); [{tags}].forEach(value=>{{if(!liquidTags.includes(value)){{ liquidTags.push(value);}}}});"; _etag = Guid.NewGuid().ToString("n"); diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/Services/LiquidShapes.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/Services/LiquidShapes.cs index 2744e73c4fd..1bb7969ccc2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/Services/LiquidShapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/Services/LiquidShapes.cs @@ -34,10 +34,11 @@ private async Task BuildViewModelAsync(ShapeDisplayContext shapeDisplayContext) var liquidTemplateManager = shapeDisplayContext.ServiceProvider.GetRequiredService(); - model.Html = await liquidTemplateManager.RenderStringAsync(model.LiquidPart.Liquid, _htmlEncoder, shapeDisplayContext.DisplayContext.Value, - new Dictionary() - { - ["ContentItem"] = new ObjectValue(model.ContentItem) - }); + model.Html = await liquidTemplateManager.RenderStringAsync( + model.LiquidPart.Liquid, + _htmlEncoder, + shapeDisplayContext.DisplayContext.Value, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/Services/LiquidTemplateManager.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/Services/LiquidTemplateManager.cs index e36e9b68026..430dcdbd6a2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/Services/LiquidTemplateManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/Services/LiquidTemplateManager.cs @@ -20,12 +20,7 @@ public class LiquidTemplateManager : ILiquidTemplateManager private readonly TemplateOptions _templateOptions; private readonly IServiceProvider _serviceProvider; - public LiquidTemplateManager( - IMemoryCache memoryCache, - LiquidViewParser liquidViewParser, - IOptions templateOptions, - IServiceProvider serviceProvider - ) + public LiquidTemplateManager(IMemoryCache memoryCache, LiquidViewParser liquidViewParser, IOptions templateOptions, IServiceProvider serviceProvider) { _memoryCache = memoryCache; _liquidViewParser = liquidViewParser; @@ -54,7 +49,12 @@ public Task RenderStringAsync(string source, TextEncoder encoder, object return result.RenderAsync(encoder, context, model); } - public async Task RenderHtmlContentAsync(string source, TextEncoder encoder, object model = null, IEnumerable> properties = null) + public async Task RenderHtmlContentAsync( + string source, + TextEncoder encoder, + object model = null, + IEnumerable> properties = null + ) { if (string.IsNullOrWhiteSpace(source)) { @@ -104,20 +104,23 @@ public LiquidViewTemplate GetCachedTemplate(string source) { var errors = Enumerable.Empty(); - var result = _memoryCache.GetOrCreate(source, (ICacheEntry e) => - { - if (!_liquidViewParser.TryParse(source, out var parsed, out var error)) + var result = _memoryCache.GetOrCreate( + source, + (ICacheEntry e) => { - // If the source string cannot be parsed, create a template that contains the parser errors - _liquidViewParser.TryParse(string.Join(System.Environment.NewLine, errors), out parsed, out error); + if (!_liquidViewParser.TryParse(source, out var parsed, out var error)) + { + // If the source string cannot be parsed, create a template that contains the parser errors + _liquidViewParser.TryParse(string.Join(System.Environment.NewLine, errors), out parsed, out error); + } + + // Define a default sliding expiration to prevent the + // cache from being filled and still apply some micro-caching + // in case the template is used commonly + e.SetSlidingExpiration(TimeSpan.FromSeconds(30)); + return new LiquidViewTemplate(parsed); } - - // Define a default sliding expiration to prevent the - // cache from being filled and still apply some micro-caching - // in case the template is used commonly - e.SetSlidingExpiration(TimeSpan.FromSeconds(30)); - return new LiquidViewTemplate(parsed); - }); + ); return result; } diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/Startup.cs index f2a5fa79451..0769d4f7f28 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/Startup.cs @@ -36,44 +36,45 @@ public override void ConfigureServices(IServiceCollection services) { services.AddScoped(); - services.Configure(options => - { - options.Filters.AddFilter("t", LiquidViewFilters.Localize); - options.Filters.AddFilter("html_class", LiquidViewFilters.HtmlClass); - options.Filters.AddFilter("shape_properties", LiquidViewFilters.ShapeProperties); + services + .Configure(options => + { + options.Filters.AddFilter("t", LiquidViewFilters.Localize); + options.Filters.AddFilter("html_class", LiquidViewFilters.HtmlClass); + options.Filters.AddFilter("shape_properties", LiquidViewFilters.ShapeProperties); - options.MemberAccessStrategy.Register(); + options.MemberAccessStrategy.Register(); - // Used to provide a factory to return a value based on a property name that is unknown at registration time. - options.MemberAccessStrategy.Register((obj, name) => obj.GetValueAsync(name)); + // Used to provide a factory to return a value based on a property name that is unknown at registration time. + options.MemberAccessStrategy.Register((obj, name) => obj.GetValueAsync(name)); - // When a property of a 'JsonObject' value is accessed, try to look into its properties. - options.MemberAccessStrategy.Register((source, name) => source[name]); + // When a property of a 'JsonObject' value is accessed, try to look into its properties. + options.MemberAccessStrategy.Register((source, name) => source[name]); - // Convert JToken to FluidValue - options.ValueConverters.Add(x => - { - return x switch + // Convert JToken to FluidValue + options.ValueConverters.Add(x => { - JsonObject o => new ObjectValue(o), - JsonDynamicObject o => new ObjectValue((JsonObject)o), - DateTime d => new ObjectValue(d), - _ => null - }; - }); + return x switch + { + JsonObject o => new ObjectValue(o), + JsonDynamicObject o => new ObjectValue((JsonObject)o), + DateTime d => new ObjectValue(d), + _ => null + }; + }); - options.Filters.AddFilter("json", JsonFilter.Json); - options.Filters.AddFilter("jsonparse", JsonParseFilter.JsonParse); - }) - .AddLiquidFilter("local") - .AddLiquidFilter("utc") - .AddLiquidFilter("slugify") - .AddLiquidFilter("liquid") - .AddLiquidFilter("href") - .AddLiquidFilter("absolute_url") - .AddLiquidFilter("shape_new") - .AddLiquidFilter("shape_render") - .AddLiquidFilter("shape_stringify"); + options.Filters.AddFilter("json", JsonFilter.Json); + options.Filters.AddFilter("jsonparse", JsonParseFilter.JsonParse); + }) + .AddLiquidFilter("local") + .AddLiquidFilter("utc") + .AddLiquidFilter("slugify") + .AddLiquidFilter("liquid") + .AddLiquidFilter("href") + .AddLiquidFilter("absolute_url") + .AddLiquidFilter("shape_new") + .AddLiquidFilter("shape_render") + .AddLiquidFilter("shape_stringify"); services.AddTransient, ResourceManagementOptionsConfiguration>(); } @@ -86,9 +87,7 @@ public override void ConfigureServices(IServiceCollection services) { // Liquid Part services.AddScoped(); - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddDataMigration(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeDriver.cs b/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeDriver.cs index f476ba23a3c..a06d324c7d5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeDriver.cs @@ -31,29 +31,32 @@ public override IDisplayResult Display(ListsAdminNode treeNode) public override IDisplayResult Edit(ListsAdminNode treeNode) { - return Initialize("ListsAdminNode_Fields_TreeEdit", async model => - { - model.ContentType = treeNode.ContentType; - model.ContentTypes = await GetContentTypesSelectListAsync(); - model.IconForContentItems = treeNode.IconForContentItems; - model.AddContentTypeAsParent = treeNode.AddContentTypeAsParent; - model.IconForParentLink = treeNode.IconForParentLink; - }).Location("Content"); + return Initialize( + "ListsAdminNode_Fields_TreeEdit", + async model => + { + model.ContentType = treeNode.ContentType; + model.ContentTypes = await GetContentTypesSelectListAsync(); + model.IconForContentItems = treeNode.IconForContentItems; + model.AddContentTypeAsParent = treeNode.AddContentTypeAsParent; + model.IconForParentLink = treeNode.IconForParentLink; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ListsAdminNode treeNode, IUpdateModel updater) { var model = new ListsAdminNodeViewModel(); - if (await updater.TryUpdateModelAsync(model, Prefix, - x => x.ContentType, x => x.IconForContentItems, - x => x.AddContentTypeAsParent, x => x.IconForParentLink)) + if (await updater.TryUpdateModelAsync(model, Prefix, x => x.ContentType, x => x.IconForContentItems, x => x.AddContentTypeAsParent, x => x.IconForParentLink)) { treeNode.ContentType = model.ContentType; treeNode.IconForContentItems = model.IconForContentItems; treeNode.AddContentTypeAsParent = model.AddContentTypeAsParent; treeNode.IconForParentLink = model.IconForParentLink; - }; + } + ; return Edit(treeNode); } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeNavigationBuilder.cs b/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeNavigationBuilder.cs index 0a111d6684a..d88a64ae31c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeNavigationBuilder.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeNavigationBuilder.cs @@ -32,7 +32,8 @@ public ListsAdminNodeNavigationBuilder( IContentDefinitionManager contentDefinitionManager, IContentManager contentManager, ISession session, - ILogger logger) + ILogger logger + ) { _contentDefinitionManager = contentDefinitionManager; _contentManager = contentManager; @@ -60,13 +61,17 @@ public async Task BuildNavigationAsync(MenuItem menuItem, NavigationBuilder buil _logger.LogError("Can't find The content type '{ContentType}' for list admin node.", _node.ContentType); } - await builder.AddAsync(new LocalizedString(_contentType.DisplayName, _contentType.DisplayName), async listTypeMenu => - { - AddPrefixToClasses(_node.IconForParentLink).ForEach(c => listTypeMenu.AddClass(c)); - listTypeMenu.Permission(ContentTypePermissionsHelper.CreateDynamicPermission( - ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditContent.Name], _contentType)); - await AddContentItemsAsync(listTypeMenu); - }); + await builder.AddAsync( + new LocalizedString(_contentType.DisplayName, _contentType.DisplayName), + async listTypeMenu => + { + AddPrefixToClasses(_node.IconForParentLink).ForEach(c => listTypeMenu.AddClass(c)); + listTypeMenu.Permission( + ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditContent.Name], _contentType) + ); + await AddContentItemsAsync(listTypeMenu); + } + ); } else { @@ -96,39 +101,41 @@ private async Task AddContentItemsAsync(NavigationBuilder listTypeMenu) if (cim.AdminRouteValues.Count > 0 && ci.DisplayText != null) { - listTypeMenu.Add(new LocalizedString(ci.DisplayText, ci.DisplayText), m => - { - m.Action(cim.AdminRouteValues["Action"] as string, cim.AdminRouteValues["Controller"] as string, cim.AdminRouteValues); - m.Resource(ci); - m.Priority(_node.Priority); - m.Position(_node.Position); - m.LocalNav(); - AddPrefixToClasses(_node.IconForContentItems).ToList().ForEach(c => m.AddClass(c)); + listTypeMenu.Add( + new LocalizedString(ci.DisplayText, ci.DisplayText), + m => + { + m.Action(cim.AdminRouteValues["Action"] as string, cim.AdminRouteValues["Controller"] as string, cim.AdminRouteValues); + m.Resource(ci); + m.Priority(_node.Priority); + m.Position(_node.Position); + m.LocalNav(); + AddPrefixToClasses(_node.IconForContentItems).ToList().ForEach(c => m.AddClass(c)); - m.Permission(ContentTypePermissionsHelper.CreateDynamicPermission( - ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditContent.Name], _contentType)); - }); + m.Permission( + ContentTypePermissionsHelper.CreateDynamicPermission( + ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditContent.Name], + _contentType + ) + ); + } + ); } } } private async Task> GetContentItemsAsync() { - return (await _session.Query() - .With(x => x.Latest && x.ContentType == _node.ContentType) - .Take(MaxItemsInNode) - .ListAsync()) + return ( + await _session.Query().With(x => x.Latest && x.ContentType == _node.ContentType).Take(MaxItemsInNode).ListAsync() + ) .OrderBy(x => x.DisplayText) .ToList(); } private static List AddPrefixToClasses(string unprefixed) { - return unprefixed?.Split(' ') - .ToList() - .Select(c => "icon-class-" + c) - .ToList() - ?? []; + return unprefixed?.Split(' ').ToList().Select(c => "icon-class-" + c).ToList() ?? []; } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/OrderController.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/OrderController.cs index 8564d23fd04..42ccc950a55 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/OrderController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/OrderController.cs @@ -54,12 +54,9 @@ public async Task UpdateContentItemOrders(string containerId, int } // Include draft items. - var pageOfContentItems = (await _containerService.QueryContainedItemsAsync( - containerId, - true, - pager, - new ContainedItemOptions { Status = ContentsStatus.Latest })) - .ToList(); + var pageOfContentItems = ( + await _containerService.QueryContainedItemsAsync(containerId, true, pager, new ContainedItemOptions { Status = ContentsStatus.Latest }) + ).ToList(); if (pageOfContentItems == null || pageOfContentItems.Count == 0) { diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/RemotePublishingController.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/RemotePublishingController.cs index 80e6ebdae9a..f8e77527f30 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/RemotePublishingController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/RemotePublishingController.cs @@ -14,9 +14,7 @@ public class RemotePublishingController : Controller private readonly IContentManager _contentManager; private readonly ILogger _logger; - public RemotePublishingController( - IContentManager contentManager, - ILogger logger) + public RemotePublishingController(IContentManager contentManager, ILogger logger) { _contentManager = contentManager; _logger = logger; @@ -52,17 +50,19 @@ public async Task Rsd(string contentItemId) new XElement(XName.Get("engineName", manifestUri), "Orchard CMS"), new XElement(XName.Get("engineLink", manifestUri), "https://orchardcore.net"), new XElement(XName.Get("homePageLink", manifestUri), "https://orchardcore.net"), - new XElement(XName.Get("apis", manifestUri), - new XElement(XName.Get("api", manifestUri), + new XElement( + XName.Get("apis", manifestUri), + new XElement( + XName.Get("api", manifestUri), new XAttribute("name", "MetaWeblog"), new XAttribute("preferred", true), new XAttribute("apiLink", url), - new XAttribute("blogID", contentItem.ContentItemId)))); + new XAttribute("blogID", contentItem.ContentItemId) + ) + ) + ); - var doc = new XDocument(new XElement( - XName.Get("rsd", manifestUri), - new XAttribute("version", "1.0"), - options)); + var doc = new XDocument(new XElement(XName.Get("rsd", manifestUri), new XAttribute("version", "1.0"), options)); return Content(doc.ToString(), "text/xml"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Drivers/ContainedPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Drivers/ContainedPartDisplayDriver.cs index 07da41aad2c..affe5014836 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Drivers/ContainedPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Drivers/ContainedPartDisplayDriver.cs @@ -19,11 +19,7 @@ public class ContainedPartDisplayDriver : ContentDisplayDriver private readonly IContentDefinitionManager _contentDefinitionManager; private readonly IContainerService _containerService; - public ContainedPartDisplayDriver( - IContentManager contentManager, - IContentDefinitionManager contentDefinitionManager, - IContainerService containerService - ) + public ContainedPartDisplayDriver(IContentManager contentManager, IContentDefinitionManager contentDefinitionManager, IContainerService containerService) { _contentManager = contentManager; _contentDefinitionManager = contentDefinitionManager; @@ -45,9 +41,7 @@ public override async Task EditAsync(ContentItem model, IUpdateM var viewModel = new EditContainedPartViewModel(); - if (await updater.TryUpdateModelAsync(viewModel, nameof(ListPart)) - && viewModel.ContainerId != null - && viewModel.ContentType == model.ContentType) + if (await updater.TryUpdateModelAsync(viewModel, nameof(ListPart)) && viewModel.ContainerId != null && viewModel.ContentType == model.ContentType) { // We are creating a content item that needs to be added to a container. // Render the container id as part of the form. The content type, and the enable ordering setting. @@ -77,9 +71,7 @@ public override async Task UpdateAsync(ContentItem model, IUpdat // The content type must match the value provided in the query string // in order for the ContainedPart to be included on the Content Item. - if (await updater.TryUpdateModelAsync(viewModel, nameof(ListPart)) - && viewModel.ContainerId != null - && viewModel.ContentType == model.ContentType) + if (await updater.TryUpdateModelAsync(viewModel, nameof(ListPart)) && viewModel.ContainerId != null && viewModel.ContentType == model.ContentType) { await model.AlterAsync(async part => { @@ -101,14 +93,17 @@ private async Task BuildViewModelAsync(string containerId, strin { var results = new List() { - Initialize("ListPart_ContainerId", m => - { - m.ContainerId = containerId; - m.ContainerContentType = containerContentType; - m.EnableOrdering = enableOrdering; - m.ContentType = contentType; - }) - .Location("Content"), + Initialize( + "ListPart_ContainerId", + m => + { + m.ContainerId = containerId; + m.ContainerContentType = containerContentType; + m.EnableOrdering = enableOrdering; + m.ContentType = contentType; + } + ) + .Location("Content"), }; if (!string.IsNullOrEmpty(containerContentType)) @@ -127,13 +122,19 @@ private async Task BuildViewModelAsync(string containerId, strin if (container != null) { // Add list part navigation. - results.Add(Initialize("ListPartNavigationAdmin", async model => - { - model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(settings)).ToArray(); - model.Container = container; - model.EnableOrdering = settings.EnableOrdering; - model.ContainerContentTypeDefinition = definition; - }).Location("Content:1.5")); + results.Add( + Initialize( + "ListPartNavigationAdmin", + async model => + { + model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(settings)).ToArray(); + model.Container = container; + model.EnableOrdering = settings.EnableOrdering; + model.ContainerContentTypeDefinition = definition; + } + ) + .Location("Content:1.5") + ); if (settings.ShowHeader) { @@ -147,22 +148,26 @@ private async Task BuildViewModelAsync(string containerId, strin return Combine(results); } - private ShapeResult GetListPartHeader(ContentItem containerContentItem, ListPartSettings listPartSettings) - => Initialize("ListPartHeaderAdmin", async model => - { - model.ContainerContentItem = containerContentItem; + private ShapeResult GetListPartHeader(ContentItem containerContentItem, ListPartSettings listPartSettings) => + Initialize( + "ListPartHeaderAdmin", + async model => + { + model.ContainerContentItem = containerContentItem; - if (listPartSettings != null) - { - model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(listPartSettings)).ToArray(); - model.EnableOrdering = listPartSettings.EnableOrdering; - } - }).Location("Content:1"); + if (listPartSettings != null) + { + model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(listPartSettings)).ToArray(); + model.EnableOrdering = listPartSettings.EnableOrdering; + } + } + ) + .Location("Content:1"); // Initially, attempt to locate a published container. // If none is found, try acquiring the most recent unpublished version. - private async Task GetContainerAsync(string containerId) - => await _contentManager.GetAsync(containerId) ?? await _contentManager.GetAsync(containerId, VersionOptions.Latest); + private async Task GetContainerAsync(string containerId) => + await _contentManager.GetAsync(containerId) ?? await _contentManager.GetAsync(containerId, VersionOptions.Latest); private async Task> GetContainedContentTypesAsync(ListPartSettings settings) { diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Drivers/ListPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Drivers/ListPartDisplayDriver.cs index 5d1da3d7db8..38dfac79d72 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Drivers/ListPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Drivers/ListPartDisplayDriver.cs @@ -22,11 +22,7 @@ public class ListPartDisplayDriver : ContentPartDisplayDriver private readonly IContainerService _containerService; private readonly IUpdateModelAccessor _updateModelAccessor; - public ListPartDisplayDriver( - IContentDefinitionManager contentDefinitionManager, - IContainerService containerService, - IUpdateModelAccessor updateModelAccessor - ) + public ListPartDisplayDriver(IContentDefinitionManager contentDefinitionManager, IContainerService containerService, IUpdateModelAccessor updateModelAccessor) { _contentDefinitionManager = contentDefinitionManager; _containerService = containerService; @@ -37,125 +33,138 @@ public override IDisplayResult Edit(ListPart part, BuildPartEditorContext contex { var settings = context.TypePartDefinition.GetSettings(); - return - Combine( - InitializeEditListPartNavigationAdmin(part, context, settings), - InitializeEditListPartHeaderAdmin(part, context, settings) - ); + return Combine(InitializeEditListPartNavigationAdmin(part, context, settings), InitializeEditListPartHeaderAdmin(part, context, settings)); } public override IDisplayResult Display(ListPart listPart, BuildPartDisplayContext context) { var settings = context.TypePartDefinition.GetSettings(); - return - Combine( - InitializeDisplayListPartDisplayShape(listPart, context), - InitializeDisplayListPartDetailAdminShape(listPart, context), - InitializeDisplayListPartNavigationAdminShape(listPart, context, settings), - InitializeDisplayListPartHeaderAdminShape(listPart, settings), - InitializeDisplayListPartSummaryAdmin(listPart) - ); + return Combine( + InitializeDisplayListPartDisplayShape(listPart, context), + InitializeDisplayListPartDetailAdminShape(listPart, context), + InitializeDisplayListPartNavigationAdminShape(listPart, context, settings), + InitializeDisplayListPartHeaderAdminShape(listPart, settings), + InitializeDisplayListPartSummaryAdmin(listPart) + ); } private ShapeResult InitializeEditListPartHeaderAdmin(ListPart part, BuildPartEditorContext context, ListPartSettings settings) { - return Initialize("ListPartHeaderAdmin", async model => - { - model.ContainerContentItem = part.ContentItem; - model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(settings)).ToArray(); - model.EnableOrdering = settings.EnableOrdering; - }).Location("Content:1") - .RenderWhen(() => Task.FromResult(!context.IsNew && settings.ShowHeader)); + return Initialize( + "ListPartHeaderAdmin", + async model => + { + model.ContainerContentItem = part.ContentItem; + model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(settings)).ToArray(); + model.EnableOrdering = settings.EnableOrdering; + } + ) + .Location("Content:1") + .RenderWhen(() => Task.FromResult(!context.IsNew && settings.ShowHeader)); } private ShapeResult InitializeEditListPartNavigationAdmin(ListPart part, BuildPartEditorContext context, ListPartSettings settings) { - return Initialize("ListPartNavigationAdmin", async model => - { - model.Container = part.ContentItem; - model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(settings)).ToArray(); - model.EnableOrdering = settings.EnableOrdering; - model.ContainerContentTypeDefinition = context.TypePartDefinition.ContentTypeDefinition; - }) + return Initialize( + "ListPartNavigationAdmin", + async model => + { + model.Container = part.ContentItem; + model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(settings)).ToArray(); + model.EnableOrdering = settings.EnableOrdering; + model.ContainerContentTypeDefinition = context.TypePartDefinition.ContentTypeDefinition; + } + ) .Location("Content:1.5") .RenderWhen(() => Task.FromResult(!context.IsNew)); } private ShapeResult InitializeDisplayListPartSummaryAdmin(ListPart listPart) { - return Initialize("ListPartSummaryAdmin", model => model.ContentItem = listPart.ContentItem) - .Location("SummaryAdmin", "Actions:4"); + return Initialize("ListPartSummaryAdmin", model => model.ContentItem = listPart.ContentItem).Location("SummaryAdmin", "Actions:4"); } private ShapeResult InitializeDisplayListPartHeaderAdminShape(ListPart listPart, ListPartSettings settings) { - return Initialize("ListPartHeaderAdmin", async model => - { - model.ContainerContentItem = listPart.ContentItem; - model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(settings)).ToArray(); - model.EnableOrdering = settings.EnableOrdering; - }).Location("DetailAdmin", "Content:1") - .RenderWhen(() => Task.FromResult(settings.ShowHeader)); + return Initialize( + "ListPartHeaderAdmin", + async model => + { + model.ContainerContentItem = listPart.ContentItem; + model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(settings)).ToArray(); + model.EnableOrdering = settings.EnableOrdering; + } + ) + .Location("DetailAdmin", "Content:1") + .RenderWhen(() => Task.FromResult(settings.ShowHeader)); } private ShapeResult InitializeDisplayListPartNavigationAdminShape(ListPart listPart, BuildPartDisplayContext context, ListPartSettings settings) { - return Initialize("ListPartNavigationAdmin", async model => - { - model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(settings)).ToArray(); - model.Container = listPart.ContentItem; - model.EnableOrdering = settings.EnableOrdering; - model.ContainerContentTypeDefinition = context.TypePartDefinition.ContentTypeDefinition; - }).Location("DetailAdmin", "Content:1.5"); + return Initialize( + "ListPartNavigationAdmin", + async model => + { + model.ContainedContentTypeDefinitions = (await GetContainedContentTypesAsync(settings)).ToArray(); + model.Container = listPart.ContentItem; + model.EnableOrdering = settings.EnableOrdering; + model.ContainerContentTypeDefinition = context.TypePartDefinition.ContentTypeDefinition; + } + ) + .Location("DetailAdmin", "Content:1.5"); } private ShapeResult InitializeDisplayListPartDetailAdminShape(ListPart listPart, BuildPartDisplayContext context) { - return Initialize("ListPartDetailAdmin", (Func)(async model => - { - var pager = await GetPagerSlimAsync(context); - var settings = context.TypePartDefinition.GetSettings(); - var listPartFilterViewModel = new ListPartFilterViewModel(); - var containedItemOptions = new ContainedItemOptions(); - - await _updateModelAccessor.ModelUpdater.TryUpdateModelAsync(listPartFilterViewModel, Prefix); - model.ListPart = listPart; - containedItemOptions.DisplayText = listPartFilterViewModel.DisplayText; - containedItemOptions.Status = listPartFilterViewModel.Status; - model.ListPartFilterViewModel = listPartFilterViewModel; - - model.ContentItems = (await _containerService.QueryContainedItemsAsync( - listPart.ContentItem.ContentItemId, - settings.EnableOrdering, - pager, - containedItemOptions)).ToArray(); - - model.ContainedContentTypeDefinitions = await GetContainedContentTypesAsync(settings); - model.Context = context; - model.EnableOrdering = settings.EnableOrdering; - model.Pager = await context.New.PagerSlim(pager); - })) + return Initialize( + "ListPartDetailAdmin", + (Func)( + async model => + { + var pager = await GetPagerSlimAsync(context); + var settings = context.TypePartDefinition.GetSettings(); + var listPartFilterViewModel = new ListPartFilterViewModel(); + var containedItemOptions = new ContainedItemOptions(); + + await _updateModelAccessor.ModelUpdater.TryUpdateModelAsync(listPartFilterViewModel, Prefix); + model.ListPart = listPart; + containedItemOptions.DisplayText = listPartFilterViewModel.DisplayText; + containedItemOptions.Status = listPartFilterViewModel.Status; + model.ListPartFilterViewModel = listPartFilterViewModel; + + model.ContentItems = ( + await _containerService.QueryContainedItemsAsync(listPart.ContentItem.ContentItemId, settings.EnableOrdering, pager, containedItemOptions) + ).ToArray(); + + model.ContainedContentTypeDefinitions = await GetContainedContentTypesAsync(settings); + model.Context = context; + model.EnableOrdering = settings.EnableOrdering; + model.Pager = await context.New.PagerSlim(pager); + } + ) + ) .Location("DetailAdmin", "Content:10"); } private ShapeResult InitializeDisplayListPartDisplayShape(ListPart listPart, BuildPartDisplayContext context) { - return Initialize(GetDisplayShapeType(context), async model => - { - var pager = await GetPagerSlimAsync(context); - var settings = context.TypePartDefinition.GetSettings(); - var containedItemOptions = new ContainedItemOptions(); - model.ContentItems = (await _containerService.QueryContainedItemsAsync( - listPart.ContentItem.ContentItemId, - settings.EnableOrdering, - pager, - containedItemOptions)).ToArray(); - - model.ContainedContentTypeDefinitions = await GetContainedContentTypesAsync(settings); - model.Context = context; - model.Pager = await context.New.PagerSlim(pager); - }) + return Initialize( + GetDisplayShapeType(context), + async model => + { + var pager = await GetPagerSlimAsync(context); + var settings = context.TypePartDefinition.GetSettings(); + var containedItemOptions = new ContainedItemOptions(); + model.ContentItems = ( + await _containerService.QueryContainedItemsAsync(listPart.ContentItem.ContentItemId, settings.EnableOrdering, pager, containedItemOptions) + ).ToArray(); + + model.ContainedContentTypeDefinitions = await GetContainedContentTypesAsync(settings); + model.Context = context; + model.Pager = await context.New.PagerSlim(pager); + } + ) .Location("Detail", "Content:10"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Feeds/ListFeedQuery.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Feeds/ListFeedQuery.cs index 992c05abb13..c14a2c5378a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Feeds/ListFeedQuery.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Feeds/ListFeedQuery.cs @@ -100,14 +100,16 @@ public async Task ExecuteAsync(FeedContext context) IEnumerable items; - items = itemsCount == 0 - ? Enumerable.Empty() - : await _session.Query() - .With(x => x.ListContentItemId == contentItem.ContentItemId) - .With(x => x.Published) - .OrderByDescending(x => x.CreatedUtc) - .Take(itemsCount) - .ListAsync(); + items = + itemsCount == 0 + ? Enumerable.Empty() + : await _session + .Query() + .With(x => x.ListContentItemId == contentItem.ContentItemId) + .With(x => x.Published) + .OrderByDescending(x => x.CreatedUtc) + .Take(itemsCount) + .ListAsync(); foreach (var item in items) { diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Feeds/ListPartFeedDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Feeds/ListPartFeedDisplayDriver.cs index bc0fe693c18..3421137e78e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Feeds/ListPartFeedDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Feeds/ListPartFeedDisplayDriver.cs @@ -11,30 +11,33 @@ public class ListPartFeedDisplayDriver : ContentPartDisplayDriver { public override IDisplayResult Display(ListPart listPart, BuildPartDisplayContext context) { - return Dynamic("ListPartFeed", shape => - { - shape.ContentItem = listPart.ContentItem; - }) - .Location("Detail", "Content"); + return Dynamic( + "ListPartFeed", + shape => + { + shape.ContentItem = listPart.ContentItem; + } + ) + .Location("Detail", "Content"); } public override IDisplayResult Edit(ListPart part) { - return Initialize("ListPartFeed_Edit", m => - { - m.DisableRssFeed = part.ContentItem.Content.ListPart.DisableRssFeed ?? false; - m.FeedProxyUrl = part.ContentItem.Content.ListPart.FeedProxyUrl; - m.FeedItemsCount = part.ContentItem.Content.ListPart.FeedItemsCount ?? 20; - m.ContentItem = part.ContentItem; - }); + return Initialize( + "ListPartFeed_Edit", + m => + { + m.DisableRssFeed = part.ContentItem.Content.ListPart.DisableRssFeed ?? false; + m.FeedProxyUrl = part.ContentItem.Content.ListPart.FeedProxyUrl; + m.FeedItemsCount = part.ContentItem.Content.ListPart.FeedItemsCount ?? 20; + m.ContentItem = part.ContentItem; + } + ); } public override async Task UpdateAsync(ListPart part, IUpdateModel updater) { - var model = new ListFeedEditViewModel - { - ContentItem = part.ContentItem, - }; + var model = new ListFeedEditViewModel { ContentItem = part.ContentItem, }; await updater.TryUpdateModelAsync(model, Prefix, t => t.DisableRssFeed, t => t.FeedProxyUrl, t => t.FeedItemsCount); diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/GraphQL/ListQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Lists/GraphQL/ListQueryObjectType.cs index 246cc35bdb6..7beb9548901 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/GraphQL/ListQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/GraphQL/ListQueryObjectType.cs @@ -35,11 +35,12 @@ public ListQueryObjectType(IStringLocalizer S) var session = serviceProvider.GetService(); var accessor = serviceProvider.GetRequiredService(); - var dataLoader = accessor.Context.GetOrAddCollectionBatchLoader("ContainedPublishedContentItems", x => LoadPublishedContentItemsForListAsync(x, session)); + var dataLoader = accessor.Context.GetOrAddCollectionBatchLoader( + "ContainedPublishedContentItems", + x => LoadPublishedContentItemsForListAsync(x, session) + ); - return ((await dataLoader.LoadAsync(g.Source.ContentItem.ContentItemId).GetResultAsync()) - .Skip(g.GetArgument("skip")) - .Take(g.GetArgument("first"))); + return ((await dataLoader.LoadAsync(g.Source.ContentItem.ContentItemId).GetResultAsync()).Skip(g.GetArgument("skip")).Take(g.GetArgument("first"))); }); } @@ -50,11 +51,12 @@ private static async Task> LoadPublishedContentItem return new Dictionary().ToLookup(k => k.Key, v => v.Value); } - var query = await session.Query() - .With(ci => ci.Published) - .With(cp => cp.ListContentItemId.IsIn(contentItemIds)) - .OrderBy(o => o.Order) - .ListAsync(); + var query = await session + .Query() + .With(ci => ci.Published) + .With(cp => cp.ListContentItemId.IsIn(contentItemIds)) + .OrderBy(o => o.Order) + .ListAsync(); return query.ToLookup(k => k.As().ListContentItemId); } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ContainedPartLocalizationHandler.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ContainedPartLocalizationHandler.cs index 3db3939450d..7711f0f8482 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ContainedPartLocalizationHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ContainedPartLocalizationHandler.cs @@ -27,8 +27,12 @@ public override async Task LocalizingAsync(LocalizationContentContext context, L // todo: remove this check and change the handler to target ContainedPart when issue 3890 is fixed if (containedPart != null) { - var list = await _session.QueryIndex(i => (i.Published || i.Latest) && i.ContentItemId == containedPart.ListContentItemId).FirstOrDefaultAsync(); - var localizedList = await _session.QueryIndex(i => (i.Published || i.Latest) && i.LocalizationSet == list.LocalizationSet && i.Culture == context.Culture).FirstOrDefaultAsync(); + var list = await _session + .QueryIndex(i => (i.Published || i.Latest) && i.ContentItemId == containedPart.ListContentItemId) + .FirstOrDefaultAsync(); + var localizedList = await _session + .QueryIndex(i => (i.Published || i.Latest) && i.LocalizationSet == list.LocalizationSet && i.Culture == context.Culture) + .FirstOrDefaultAsync(); if (localizedList != null) { @@ -42,6 +46,7 @@ public override async Task LocalizingAsync(LocalizationContentContext context, L public class LocalizationContainedPartHandler : ContentPartHandler { private readonly ISession _session; + public LocalizationContainedPartHandler(ISession session) { _session = session; @@ -56,8 +61,12 @@ public override async Task CreatingAsync(CreateContentContext context, Localizat var containedPart = context.ContentItem.As(); if (containedPart != null) { - var list = await _session.QueryIndex(i => (i.Published || i.Latest) && i.ContentItemId == containedPart.ListContentItemId).FirstOrDefaultAsync(); - var localizedList = await _session.QueryIndex(i => (i.Published || i.Latest) && i.LocalizationSet == list.LocalizationSet && i.Culture == instance.Culture).FirstOrDefaultAsync(); + var list = await _session + .QueryIndex(i => (i.Published || i.Latest) && i.ContentItemId == containedPart.ListContentItemId) + .FirstOrDefaultAsync(); + var localizedList = await _session + .QueryIndex(i => (i.Published || i.Latest) && i.LocalizationSet == list.LocalizationSet && i.Culture == instance.Culture) + .FirstOrDefaultAsync(); if (localizedList != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ListPartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ListPartHandler.cs index 9b56cf435e3..2c630ee081c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ListPartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ListPartHandler.cs @@ -14,10 +14,10 @@ public override Task GetContentItemAspectAsync(ContentItemAspectContext context, { contentItemMetadata.AdminRouteValues = new RouteValueDictionary { - {"Area", "OrchardCore.Contents"}, - {"Controller", "Admin"}, - {"Action", "Display"}, - {"ContentItemId", context.ContentItem.ContentItemId} + { "Area", "OrchardCore.Contents" }, + { "Controller", "Admin" }, + { "Action", "Display" }, + { "ContentItemId", context.ContentItem.ContentItemId } }; return Task.CompletedTask; diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ListPartLocalizationHandler.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ListPartLocalizationHandler.cs index ae01e19204f..da4a33ab4b9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ListPartLocalizationHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Handlers/ListPartLocalizationHandler.cs @@ -24,8 +24,7 @@ public ListPartLocalizationHandler(ISession session) /// public override async Task LocalizedAsync(LocalizationContentContext context, ListPart part) { - var containedList = await _session.Query( - x => x.ListContentItemId == context.Original.ContentItemId).ListAsync(); + var containedList = await _session.Query(x => x.ListContentItemId == context.Original.ContentItemId).ListAsync(); if (!containedList.Any()) { diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Helpers/ListOrchardHelperExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Helpers/ListOrchardHelperExtensions.cs index 5ebec9ada86..8eea7d0283a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Helpers/ListOrchardHelperExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Helpers/ListOrchardHelperExtensions.cs @@ -34,7 +34,11 @@ public static Task QueryListItemsCountAsync(this IOrchardHelper orchardHelp /// The list content item id. /// The optional predicate applied to each item. By defult published items only. /// An enumerable of list items satisfying given predicate. - public static Task> QueryListItemsAsync(this IOrchardHelper orchardHelper, string listContentItemId, Expression> itemPredicate = null) + public static Task> QueryListItemsAsync( + this IOrchardHelper orchardHelper, + string listContentItemId, + Expression> itemPredicate = null + ) { var session = orchardHelper.HttpContext.RequestServices.GetService(); diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Helpers/ListQueryHelpers.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Helpers/ListQueryHelpers.cs index 3e536212370..23b3c94b706 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Helpers/ListQueryHelpers.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Helpers/ListQueryHelpers.cs @@ -13,18 +13,24 @@ internal static class ListQueryHelpers { internal static Task QueryListItemsCountAsync(ISession session, string listContentItemId, Expression> itemPredicate = null) { - return session.Query() - .With(x => x.ListContentItemId == listContentItemId) - .With(itemPredicate ?? (x => x.Published)) - .CountAsync(); + return session + .Query() + .With(x => x.ListContentItemId == listContentItemId) + .With(itemPredicate ?? (x => x.Published)) + .CountAsync(); } - internal static Task> QueryListItemsAsync(ISession session, string listContentItemId, Expression> itemPredicate = null) + internal static Task> QueryListItemsAsync( + ISession session, + string listContentItemId, + Expression> itemPredicate = null + ) { - return session.Query() - .With(x => x.ListContentItemId == listContentItemId) - .With(itemPredicate ?? (x => x.Published)) - .ListAsync(); + return session + .Query() + .With(x => x.ListContentItemId == listContentItemId) + .With(itemPredicate ?? (x => x.Published)) + .ListAsync(); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Indexes/ContainedPartContentIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Indexes/ContainedPartContentIndexHandler.cs index 50d0e3b01ba..3cef0e0b429 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Indexes/ContainedPartContentIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Indexes/ContainedPartContentIndexHandler.cs @@ -20,12 +20,10 @@ public Task BuildIndexAsync(BuildIndexContext context) context.DocumentIndex.Set( IndexingConstants.ContainedPartKey + IndexingConstants.IdsKey, parent.ListContentItemId, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + DocumentIndexOptions.Keyword | DocumentIndexOptions.Store + ); - context.DocumentIndex.Set( - IndexingConstants.ContainedPartKey + IndexingConstants.OrderKey, - parent.Order, - DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); + context.DocumentIndex.Set(IndexingConstants.ContainedPartKey + IndexingConstants.OrderKey, parent.Order, DocumentIndexOptions.Keyword | DocumentIndexOptions.Store); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Indexes/ContainedPartIndex.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Indexes/ContainedPartIndex.cs index a48a95b8237..8f7b68efeab 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Indexes/ContainedPartIndex.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Indexes/ContainedPartIndex.cs @@ -25,7 +25,8 @@ public class ContainedPartIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(contentItem => { if (!contentItem.Latest && !contentItem.Published) diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Manifest.cs index 9f648a92b37..4156f7c6a65 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Manifest.cs @@ -1,11 +1,6 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Lists", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Lists", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Lists", diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Migrations.cs index 038c58aec7c..f13d6f03015 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Migrations.cs @@ -19,23 +19,22 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("ListPart", builder => builder - .Attachable() - .WithDescription("Add a list behavior.")); - - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", column => column.WithLength(26)) - .Column("ListContentItemId", column => column.WithLength(26)) - .Column("DisplayText") - .Column("Order") - .Column("ListContentType") - .Column("Published") - .Column("Latest") - + await _contentDefinitionManager.AlterPartDefinitionAsync("ListPart", builder => builder.Attachable().WithDescription("Add a list behavior.")); + + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", column => column.WithLength(26)) + .Column("ListContentItemId", column => column.WithLength(26)) + .Column("DisplayText") + .Column("Order") + .Column("ListContentType") + .Column("Published") + .Column("Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContainedPartIndex_DocumentId", + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex( + "IDX_ContainedPartIndex_DocumentId", "Id", "DocumentId", "ContentItemId", @@ -44,7 +43,8 @@ await SchemaBuilder.AlterIndexTableAsync(table => table "Order", "ListContentType", "Published", - "Latest") + "Latest" + ) ); // Shortcut other migration steps on new content definition schemas. @@ -63,11 +63,8 @@ public async Task UpdateFrom1Async() // This code can be removed in a later version. public async Task UpdateFrom2Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContainedPartIndex_DocumentId", - "DocumentId", - "ListContentItemId", - "Order") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContainedPartIndex_DocumentId", "DocumentId", "ListContentItemId", "Order") ); return 3; @@ -76,31 +73,20 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom3Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("ContentItemId", column => column.WithLength(26)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("ContentItemId", column => column.WithLength(26))); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("ListContentType") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("ListContentType")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("DisplayText") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("DisplayText")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Published") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Published")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Latest") - ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .DropIndex("IDX_ContainedPartIndex_DocumentId") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Latest")); + await SchemaBuilder.AlterIndexTableAsync(table => table.DropIndex("IDX_ContainedPartIndex_DocumentId")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContainedPartIndex_DocumentId", + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex( + "IDX_ContainedPartIndex_DocumentId", "Id", "DocumentId", "ContentItemId", @@ -109,7 +95,8 @@ await SchemaBuilder.AlterIndexTableAsync(table => table "Order", "ListContentType", "Published", - "Latest") + "Latest" + ) ); return 4; diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Models/ListPart.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Models/ListPart.cs index 7dbb2de7cd7..4b951cb058b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Models/ListPart.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Models/ListPart.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Lists.Models { - public class ListPart : ContentPart - { - } + public class ListPart : ContentPart { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/ListMetaWeblogDriver.cs b/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/ListMetaWeblogDriver.cs index 7aaea544d54..5aba62d17a7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/ListMetaWeblogDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/ListMetaWeblogDriver.cs @@ -11,10 +11,14 @@ public class ListMetaWeblogDriver : ContentPartDisplayDriver { public override IDisplayResult Display(ListPart listPart, BuildPartDisplayContext context) { - return Dynamic("ListPart_RemotePublishing", shape => - { - shape.ContentItem = listPart.ContentItem; - }).Location("Content"); + return Dynamic( + "ListPart_RemotePublishing", + shape => + { + shape.ContentItem = listPart.ContentItem; + } + ) + .Location("Content"); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/MetaWeblogHandler.cs b/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/MetaWeblogHandler.cs index 4c76cb2caf0..56f921cea69 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/MetaWeblogHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/MetaWeblogHandler.cs @@ -47,7 +47,8 @@ public MetaWeblogHandler( IContentDefinitionManager contentDefinitionManager, IMediaFileStore mediaFileStore, IEnumerable metaWeblogDrivers, - IStringLocalizer localizer) + IStringLocalizer localizer + ) { _contentManager = contentManager; _contentDefinitionManager = contentDefinitionManager; @@ -65,7 +66,12 @@ public void SetCapabilities(XElement options) foreach (var driver in _metaWeblogDrivers) { - driver.SetCapabilities((name, value) => { options.SetElementValue(XName.Get(name, manifestUri), value); }); + driver.SetCapabilities( + (name, value) => + { + options.SetElementValue(XName.Get(name, manifestUri), value); + } + ); } } @@ -73,9 +79,11 @@ public async Task ProcessAsync(XmlRpcContext context) { if (context.RpcMethodCall.MethodName == "blogger.getUsersBlogs") { - var result = await MetaWeblogGetUserBlogsAsync(context, + var result = await MetaWeblogGetUserBlogsAsync( + context, Convert.ToString(context.RpcMethodCall.Params[1].Value), - Convert.ToString(context.RpcMethodCall.Params[2].Value)); + Convert.ToString(context.RpcMethodCall.Params[2].Value) + ); context.RpcMethodResponse = new XRpcMethodResponse().Add(result); } @@ -88,7 +96,8 @@ public async Task ProcessAsync(XmlRpcContext context) Convert.ToString(context.RpcMethodCall.Params[1].Value), Convert.ToString(context.RpcMethodCall.Params[2].Value), Convert.ToInt32(context.RpcMethodCall.Params[3].Value), - context.Drivers); + context.Drivers + ); context.RpcMethodResponse = new XRpcMethodResponse().Add(result); } @@ -101,7 +110,8 @@ public async Task ProcessAsync(XmlRpcContext context) Convert.ToString(context.RpcMethodCall.Params[2].Value), (XRpcStruct)context.RpcMethodCall.Params[3].Value, Convert.ToBoolean(context.RpcMethodCall.Params[4].Value), - context.Drivers); + context.Drivers + ); context.RpcMethodResponse = new XRpcMethodResponse().Add(result); } @@ -113,7 +123,8 @@ public async Task ProcessAsync(XmlRpcContext context) Convert.ToString(context.RpcMethodCall.Params[0].Value), Convert.ToString(context.RpcMethodCall.Params[1].Value), Convert.ToString(context.RpcMethodCall.Params[2].Value), - context.Drivers); + context.Drivers + ); context.RpcMethodResponse = new XRpcMethodResponse().Add(result); } @@ -125,7 +136,8 @@ public async Task ProcessAsync(XmlRpcContext context) Convert.ToString(context.RpcMethodCall.Params[2].Value), (XRpcStruct)context.RpcMethodCall.Params[3].Value, Convert.ToBoolean(context.RpcMethodCall.Params[4].Value), - context.Drivers); + context.Drivers + ); context.RpcMethodResponse = new XRpcMethodResponse().Add(result); } @@ -135,7 +147,8 @@ public async Task ProcessAsync(XmlRpcContext context) Convert.ToString(context.RpcMethodCall.Params[1].Value), Convert.ToString(context.RpcMethodCall.Params[2].Value), Convert.ToString(context.RpcMethodCall.Params[3].Value), - context.Drivers); + context.Drivers + ); context.RpcMethodResponse = new XRpcMethodResponse().Add(result); } @@ -144,7 +157,8 @@ public async Task ProcessAsync(XmlRpcContext context) var result = await MetaWeblogNewMediaObjectAsync( Convert.ToString(context.RpcMethodCall.Params[1].Value), Convert.ToString(context.RpcMethodCall.Params[2].Value), - (XRpcStruct)context.RpcMethodCall.Params[3].Value); + (XRpcStruct)context.RpcMethodCall.Params[3].Value + ); context.RpcMethodResponse = new XRpcMethodResponse().Add(result); } } @@ -172,10 +186,7 @@ private async Task MetaWeblogNewMediaObjectAsync(string userName, st var publicUrl = _mediaFileStore.MapPathToPublicUrl(filePath); // Some clients require all optional attributes to be declared Wordpress responds in this way as well. - return new XRpcStruct() - .Set("file", publicUrl) - .Set("url", publicUrl) - .Set("type", file.Optional("type")); + return new XRpcStruct().Set("file", publicUrl).Set("url", publicUrl).Set("type", file.Optional("type")); } private async Task MetaWeblogGetUserBlogsAsync(XmlRpcContext context, string userName, string password) @@ -200,10 +211,20 @@ private async Task MetaWeblogGetUserBlogsAsync(XmlRpcContext context, var metadata = await _contentManager.PopulateAspectAsync(list); var displayRouteValues = metadata.DisplayRouteValues; - array.Add(new XRpcStruct() - .Set("url", context.Url.Action(displayRouteValues["action"].ToString(), displayRouteValues["controller"].ToString(), displayRouteValues, context.HttpContext.Request.Scheme)) - .Set("blogid", list.ContentItemId) - .Set("blogName", list.DisplayText)); + array.Add( + new XRpcStruct() + .Set( + "url", + context.Url.Action( + displayRouteValues["action"].ToString(), + displayRouteValues["controller"].ToString(), + displayRouteValues, + context.HttpContext.Request.Scheme + ) + ) + .Set("blogid", list.ContentItemId) + .Set("blogName", list.DisplayText) + ); } } } @@ -217,19 +238,20 @@ private async Task MetaWeblogGetRecentPosts( string userName, string password, int numberOfPosts, - IEnumerable drivers) + IEnumerable drivers + ) { var user = await ValidateUserAsync(userName, password); // User needs to at least have permission to edit its own blog posts to access the service. await CheckAccessAsync(CommonPermissions.EditContent, user, null); - var list = (await _contentManager.GetAsync(contentItemId)) - ?? throw new InvalidOperationException("Could not find content item " + contentItemId); + var list = (await _contentManager.GetAsync(contentItemId)) ?? throw new InvalidOperationException("Could not find content item " + contentItemId); var array = new XRpcArray(); - var contentItems = await _session.Query() + var contentItems = await _session + .Query() .With(x => x.ListContentItemId == contentItemId) .With(x => x.Latest) .OrderByDescending(x => x.CreatedUtc) @@ -257,15 +279,15 @@ private async Task MetaWeblogNewPostAsync( string password, XRpcStruct content, bool publish, - IEnumerable drivers) + IEnumerable drivers + ) { var user = await ValidateUserAsync(userName, password); // User needs permission to edit or publish its own blog posts. await CheckAccessAsync(publish ? CommonPermissions.PublishContent : CommonPermissions.EditContent, user, null); - var list = (await _contentManager.GetAsync(contentItemId)) - ?? throw new InvalidOperationException("Could not find content item " + contentItemId); + var list = (await _contentManager.GetAsync(contentItemId)) ?? throw new InvalidOperationException("Could not find content item " + contentItemId); var postType = (await GetContainedContentTypesAsync(list)).FirstOrDefault(); var contentItem = await _contentManager.NewAsync(postType.Name); @@ -315,17 +337,12 @@ private async Task MetaWeblogNewPostAsync( return contentItem.ContentItemId; } - private async Task MetaWeblogGetPostAsync( - XmlRpcContext context, - string contentItemId, - string userName, - string password, - IEnumerable drivers) + private async Task MetaWeblogGetPostAsync(XmlRpcContext context, string contentItemId, string userName, string password, IEnumerable drivers) { var user = await ValidateUserAsync(userName, password); - var contentItem = (await _contentManager.GetAsync(contentItemId, VersionOptions.Latest)) - ?? throw new InvalidOperationException("Could not find content item " + contentItemId); + var contentItem = + (await _contentManager.GetAsync(contentItemId, VersionOptions.Latest)) ?? throw new InvalidOperationException("Could not find content item " + contentItemId); await CheckAccessAsync(CommonPermissions.EditContent, user, contentItem); @@ -350,11 +367,13 @@ private async Task MetaWeblogEditPostAsync( string password, XRpcStruct content, bool publish, - IEnumerable drivers) + IEnumerable drivers + ) { var user = await ValidateUserAsync(userName, password); - var contentItem = (await _contentManager.GetAsync(contentItemId, VersionOptions.DraftRequired)) + var contentItem = + (await _contentManager.GetAsync(contentItemId, VersionOptions.DraftRequired)) ?? throw new Exception(S["The specified Blog Post doesn't exist anymore. Please create a new Blog Post."]); await CheckAccessAsync(publish ? CommonPermissions.PublishContent : CommonPermissions.EditContent, user, contentItem); @@ -399,16 +418,12 @@ private async Task MetaWeblogEditPostAsync( return true; } - private async Task MetaWeblogDeletePostAsync( - string contentItemId, - string userName, - string password, - IEnumerable drivers) + private async Task MetaWeblogDeletePostAsync(string contentItemId, string userName, string password, IEnumerable drivers) { var user = await ValidateUserAsync(userName, password); - var contentItem = (await _contentManager.GetAsync(contentItemId, VersionOptions.Latest)) - ?? throw new InvalidOperationException("Could not find content item " + contentItemId); + var contentItem = + (await _contentManager.GetAsync(contentItemId, VersionOptions.Latest)) ?? throw new InvalidOperationException("Could not find content item " + contentItemId); if (!await _authorizationService.AuthorizeAsync(user, CommonPermissions.DeleteContent, contentItem)) { @@ -449,17 +464,15 @@ private async Task CreateBlogStructAsync(XmlRpcContext context, Cont metadata.DisplayRouteValues["action"].ToString(), metadata.DisplayRouteValues["controller"].ToString(), metadata.DisplayRouteValues, - context.HttpContext.Request.Scheme); + context.HttpContext.Request.Scheme + ); if (contentItem.HasDraft()) { url = context.Url.Action("Preview", "Item", new { area = "OrchardCore.Contents", contentItemId = contentItem.ContentItemId }); } - var blogStruct = new XRpcStruct() - .Set("postid", contentItem.ContentItemId) - .Set("link", url) - .Set("permaLink", url); + var blogStruct = new XRpcStruct().Set("postid", contentItem.ContentItemId).Set("link", url).Set("permaLink", url); if (contentItem.PublishedUtc != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/RemotePublishingStartup.cs b/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/RemotePublishingStartup.cs index 2f3d71de787..c361655f8c8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/RemotePublishingStartup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/RemotePublishing/RemotePublishingStartup.cs @@ -16,8 +16,7 @@ public class RemotePublishingStartup : StartupBase public override void ConfigureServices(IServiceCollection services) { services.AddScoped(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); } public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Services/ContainerService.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Services/ContainerService.cs index 676ce9d25f3..444e946dd36 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Services/ContainerService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Services/ContainerService.cs @@ -21,10 +21,7 @@ public class ContainerService : IContainerService private readonly IContentManager _contentManager; private readonly IHttpContextAccessor _httpContextAccessor; - public ContainerService( - YesSql.ISession session, - IContentManager contentManager, - IHttpContextAccessor httpContextAccessor) + public ContainerService(YesSql.ISession session, IContentManager contentManager, IHttpContextAccessor httpContextAccessor) { _session = session; _contentManager = contentManager; @@ -33,9 +30,7 @@ public ContainerService( public async Task GetNextOrderNumberAsync(string contentItemId) { - var index = await _session.QueryIndex(x => x.ListContentItemId == contentItemId) - .OrderByDescending(x => x.Order) - .FirstOrDefaultAsync(); + var index = await _session.QueryIndex(x => x.ListContentItemId == contentItemId).OrderByDescending(x => x.Order).FirstOrDefaultAsync(); if (index != null) { @@ -90,7 +85,8 @@ public async Task SetInitialOrder(string contentType) // Reduce duplicates to only set order for the published container item and the draft item if it has not been published. var containerContentItemIds = containerContentItems.Select(x => x.ContentItemId).Distinct(); - var containedItemsQuery = _session.Query() + var containedItemsQuery = _session + .Query() .With(x => x.ListContentItemId.IsIn(containerContentItemIds)) .With(ci => ci.Latest || ci.Published) .OrderByDescending(x => x.CreatedUtc); @@ -151,11 +147,7 @@ public async Task SetInitialOrder(string contentType) } } - public async Task> QueryContainedItemsAsync( - string contentItemId, - bool enableOrdering, - PagerSlim pager, - ContainedItemOptions containedItemOptions) + public async Task> QueryContainedItemsAsync(string contentItemId, bool enableOrdering, PagerSlim pager, ContainedItemOptions containedItemOptions) { ArgumentNullException.ThrowIfNull(containedItemOptions); @@ -165,15 +157,12 @@ public async Task> QueryContainedItemsAsync( if (enableOrdering) { var beforeValue = int.Parse(pager.Before); - query = _session.Query() - .With(CreateOrderedContainedPartIndexFilter(beforeValue, null, contentItemId)) - .OrderByDescending(x => x.Order); + query = _session.Query().With(CreateOrderedContainedPartIndexFilter(beforeValue, null, contentItemId)).OrderByDescending(x => x.Order); } else { var beforeValue = new DateTime(long.Parse(pager.Before)); - query = _session.Query() - .With(x => x.ListContentItemId == contentItemId); + query = _session.Query().With(x => x.ListContentItemId == contentItemId); ApplyPagingContentIndexFilter(beforeValue, null, true, query); } @@ -224,15 +213,12 @@ public async Task> QueryContainedItemsAsync( if (enableOrdering) { var afterValue = int.Parse(pager.After); - query = _session.Query() - .With(CreateOrderedContainedPartIndexFilter(null, afterValue, contentItemId)) - .OrderBy(x => x.Order); + query = _session.Query().With(CreateOrderedContainedPartIndexFilter(null, afterValue, contentItemId)).OrderBy(x => x.Order); } else { var afterValue = new DateTime(long.Parse(pager.After)); - query = _session.Query() - .With(CreateOrderedContainedPartIndexFilter(null, null, contentItemId)); + query = _session.Query().With(CreateOrderedContainedPartIndexFilter(null, null, contentItemId)); ApplyPagingContentIndexFilter(null, afterValue, false, query); } @@ -279,14 +265,11 @@ public async Task> QueryContainedItemsAsync( { if (enableOrdering) { - query = _session.Query() - .With(CreateOrderedContainedPartIndexFilter(null, null, contentItemId)) - .OrderBy(x => x.Order); + query = _session.Query().With(CreateOrderedContainedPartIndexFilter(null, null, contentItemId)).OrderBy(x => x.Order); } else { - query = _session.Query() - .With(x => x.ListContentItemId == contentItemId); + query = _session.Query().With(x => x.ListContentItemId == contentItemId); ApplyPagingContentIndexFilter(null, null, false, query); } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Services/ListPartContentsAdminListFilter.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Services/ListPartContentsAdminListFilter.cs index 09fe7b0601e..1e7a4d78af3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Services/ListPartContentsAdminListFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Services/ListPartContentsAdminListFilter.cs @@ -32,14 +32,11 @@ public async Task FilterAsync(ContentOptionsViewModel model, IQuery if (viewModel.ShowListContentTypes) { var listableTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(x => - x.Parts.Any(p => - p.PartDefinition.Name == nameof(ListPart))) + .Where(x => x.Parts.Any(p => p.PartDefinition.Name == nameof(ListPart))) .Select(x => x.Name); query.With(x => x.ContentType.IsIn(listableTypes)); } - // Show contained elements for the specified list else if (viewModel.ListContentItemId != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Settings/ListPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Settings/ListPartSettingsDisplayDriver.cs index f8c1231c365..a81aa087846 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Settings/ListPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Settings/ListPartSettingsDisplayDriver.cs @@ -20,7 +20,8 @@ public class ListPartSettingsDisplayDriver : ContentTypePartDefinitionDisplayDri public ListPartSettingsDisplayDriver( IContentDefinitionManager contentDefinitionManager, IContainerService containerService, - IStringLocalizer localizer) + IStringLocalizer localizer + ) { _contentDefinitionManager = contentDefinitionManager; _containerService = containerService; @@ -29,20 +30,24 @@ public ListPartSettingsDisplayDriver( public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("ListPartSettings_Edit", async model => - { - model.ListPartSettings = contentTypePartDefinition.GetSettings(); - model.PageSize = model.ListPartSettings.PageSize; - model.EnableOrdering = model.ListPartSettings.EnableOrdering; - model.ContainedContentTypes = model.ListPartSettings.ContainedContentTypes; - model.ShowHeader = model.ListPartSettings.ShowHeader; - model.ContentTypes = []; + return Initialize( + "ListPartSettings_Edit", + async model => + { + model.ListPartSettings = contentTypePartDefinition.GetSettings(); + model.PageSize = model.ListPartSettings.PageSize; + model.EnableOrdering = model.ListPartSettings.EnableOrdering; + model.ContainedContentTypes = model.ListPartSettings.ContainedContentTypes; + model.ShowHeader = model.ListPartSettings.ShowHeader; + model.ContentTypes = []; - foreach (var contentTypeDefinition in await _contentDefinitionManager.ListTypeDefinitionsAsync()) - { - model.ContentTypes.Add(contentTypeDefinition.Name, contentTypeDefinition.DisplayName); - } - }).Location("Content"); + foreach (var contentTypeDefinition in await _contentDefinitionManager.ListTypeDefinitionsAsync()) + { + model.ContentTypes.Add(contentTypeDefinition.Name, contentTypeDefinition.DisplayName); + } + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) @@ -59,13 +64,15 @@ public override async Task UpdateAsync(ContentTypePartDefinition } else { - context.Builder.WithSettings(new ListPartSettings - { - PageSize = model.PageSize, - EnableOrdering = model.EnableOrdering, - ContainedContentTypes = model.ContainedContentTypes, - ShowHeader = model.ShowHeader, - }); + context.Builder.WithSettings( + new ListPartSettings + { + PageSize = model.PageSize, + EnableOrdering = model.EnableOrdering, + ContainedContentTypes = model.ContainedContentTypes, + ShowHeader = model.ShowHeader, + } + ); // Update order of existing content if enable ordering has been turned on if (settings.EnableOrdering != model.EnableOrdering && model.EnableOrdering == true) diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Startup.cs index c2c99f1bc04..548727fa2dd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Startup.cs @@ -38,13 +38,14 @@ public class Startup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.Configure(o => - { - o.MemberAccessStrategy.Register(); - }) - .AddLiquidFilter("list_count") - .AddLiquidFilter("list_items") - .AddLiquidFilter("container"); + services + .Configure(o => + { + o.MemberAccessStrategy.Register(); + }) + .AddLiquidFilter("list_count") + .AddLiquidFilter("list_items") + .AddLiquidFilter("container"); services.AddIndexProvider(); services.AddScoped(); @@ -54,9 +55,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped, ListPartContentsAdminListDisplayDriver>(); // List Part - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddDataMigration(); @@ -81,8 +80,7 @@ public override void ConfigureServices(IServiceCollection services) { services.AddScoped(); services.AddScoped(); - services.AddContentPart() - .AddHandler(); + services.AddContentPart().AddHandler(); } } @@ -94,17 +92,21 @@ public override void ConfigureServices(IServiceCollection services) // Feeds services.AddScoped(); - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); } + public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { routes.MapAreaControllerRoute( name: "ListFeed", areaName: "OrchardCore.Feeds", pattern: "Contents/Lists/{contentItemId}/rss", - defaults: new { controller = "Feed", action = "Index", format = "rss" } + defaults: new + { + controller = "Feed", + action = "Index", + format = "rss" + } ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Localization/AdminCookieCultureProvider.cs b/src/OrchardCore.Modules/OrchardCore.Localization/AdminCookieCultureProvider.cs index c6bc96a255c..12dadec635e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Localization/AdminCookieCultureProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Localization/AdminCookieCultureProvider.cs @@ -31,7 +31,5 @@ public override Task DetermineProviderCultureResult(HttpC public static string MakeCookieName(ShellSettings shellSettings) => CookieNamePrefix + shellSettings.VersionId; - public static string MakeCookiePath(HttpContext httpContext) => httpContext.Request.PathBase.HasValue - ? httpContext.Request.PathBase.ToString() - : "/"; + public static string MakeCookiePath(HttpContext httpContext) => httpContext.Request.PathBase.HasValue ? httpContext.Request.PathBase.ToString() : "/"; } diff --git a/src/OrchardCore.Modules/OrchardCore.Localization/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Localization/AdminMenu.cs index 9833e105353..356790ae00e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Localization/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Localization/AdminMenu.cs @@ -11,11 +11,7 @@ namespace OrchardCore.Localization /// public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", LocalizationSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", LocalizationSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -36,22 +32,32 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Localization"], localization => localization - .AddClass("localization") - .Id("localization") - .Add(S["Cultures"], S["Cultures"].PrefixPosition(), cultures => cultures - .AddClass("cultures") - .Id("cultures") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageCultures) - .LocalNav() + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Localization"], + localization => + localization + .AddClass("localization") + .Id("localization") + .Add( + S["Cultures"], + S["Cultures"].PrefixPosition(), + cultures => + cultures + .AddClass("cultures") + .Id("cultures") + .Action("Index", "Admin", _routeValues) + .Permission(Permissions.ManageCultures) + .LocalNav() + ) ) - ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Localization/Drivers/AdminCulturePickerNavbarDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Localization/Drivers/AdminCulturePickerNavbarDisplayDriver.cs index f4855ec7568..b0e4f710815 100644 --- a/src/OrchardCore.Modules/OrchardCore.Localization/Drivers/AdminCulturePickerNavbarDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Localization/Drivers/AdminCulturePickerNavbarDisplayDriver.cs @@ -15,9 +15,7 @@ public class AdminCulturePickerNavbarDisplayDriver : DisplayDriver private readonly IHttpContextAccessor _httpContextAccessor; private readonly ILocalizationService _localizationService; - public AdminCulturePickerNavbarDisplayDriver( - IHttpContextAccessor httpContextAccessor, - ILocalizationService localizationService) + public AdminCulturePickerNavbarDisplayDriver(IHttpContextAccessor httpContextAccessor, ILocalizationService localizationService) { _httpContextAccessor = httpContextAccessor; _localizationService = localizationService; @@ -27,15 +25,15 @@ public override async Task DisplayAsync(Navbar model, BuildDispl { var supportedCultures = (await _localizationService.GetSupportedCulturesAsync()).Select(c => CultureInfo.GetCultureInfo(c)); - return Initialize("AdminCulturePicker", model => - { - model.SupportedCultures = supportedCultures; - model.CurrentCulture = _httpContextAccessor - .HttpContext - .Features - .Get()?.RequestCulture?.Culture ?? CultureInfo.CurrentUICulture; - - }).RenderWhen(() => Task.FromResult(supportedCultures.Count() > 1)) - .Location("DetailAdmin", "Content:5"); + return Initialize( + "AdminCulturePicker", + model => + { + model.SupportedCultures = supportedCultures; + model.CurrentCulture = _httpContextAccessor.HttpContext.Features.Get()?.RequestCulture?.Culture ?? CultureInfo.CurrentUICulture; + } + ) + .RenderWhen(() => Task.FromResult(supportedCultures.Count() > 1)) + .Location("DetailAdmin", "Content:5"); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Localization/Drivers/LocalizationSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Localization/Drivers/LocalizationSettingsDisplayDriver.cs index 1242dc28e7b..e223063aa4c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Localization/Drivers/LocalizationSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Localization/Drivers/LocalizationSettingsDisplayDriver.cs @@ -66,24 +66,31 @@ public override async Task EditAsync(LocalizationSettings settin return null; } - return Initialize("LocalizationSettings_Edit", model => - { - model.Cultures = ILocalizationService.GetAllCulturesAndAliases() - .Select(cultureInfo => + return Initialize( + "LocalizationSettings_Edit", + model => { - return new CultureEntry + model.Cultures = ILocalizationService + .GetAllCulturesAndAliases() + .Select(cultureInfo => + { + return new CultureEntry + { + Supported = settings.SupportedCultures.Contains(cultureInfo.Name, StringComparer.OrdinalIgnoreCase), + CultureInfo = cultureInfo, + IsDefault = string.Equals(settings.DefaultCulture, cultureInfo.Name, StringComparison.OrdinalIgnoreCase) + }; + }) + .ToArray(); + + if (!model.Cultures.Any(x => x.IsDefault)) { - Supported = settings.SupportedCultures.Contains(cultureInfo.Name, StringComparer.OrdinalIgnoreCase), - CultureInfo = cultureInfo, - IsDefault = string.Equals(settings.DefaultCulture, cultureInfo.Name, StringComparison.OrdinalIgnoreCase) - }; - }).ToArray(); - - if (!model.Cultures.Any(x => x.IsDefault)) - { - model.Cultures[0].IsDefault = true; - } - }).Location("Content:2").OnGroup(GroupId); + model.Cultures[0].IsDefault = true; + } + } + ) + .Location("Content:2") + .OnGroup(GroupId); } /// diff --git a/src/OrchardCore.Modules/OrchardCore.Localization/GraphQL/SiteCulturesQuery.cs b/src/OrchardCore.Modules/OrchardCore.Localization/GraphQL/SiteCulturesQuery.cs index a6c76859b2c..0c782da99ac 100644 --- a/src/OrchardCore.Modules/OrchardCore.Localization/GraphQL/SiteCulturesQuery.cs +++ b/src/OrchardCore.Modules/OrchardCore.Localization/GraphQL/SiteCulturesQuery.cs @@ -26,10 +26,8 @@ public class SiteCulturesQuery : ISchemaBuilder /// /// The . /// The . - /// - public SiteCulturesQuery( - IStringLocalizer localizer, - IOptions graphQLContentOptions) + /// + public SiteCulturesQuery(IStringLocalizer localizer, IOptions graphQLContentOptions) { S = localizer; _graphQLContentOptions = graphQLContentOptions.Value; @@ -65,13 +63,11 @@ private async ValueTask> ResolveAsync(IResolveFieldCont var defaultCulture = await localizationService.GetDefaultCultureAsync(); var supportedCultures = await localizationService.GetSupportedCulturesAsync(); - var cultures = supportedCultures.Select(culture => - new SiteCulture - { - Culture = culture, - IsDefault = string.Equals(defaultCulture, culture, StringComparison.OrdinalIgnoreCase), - } - ); + var cultures = supportedCultures.Select(culture => new SiteCulture + { + Culture = culture, + IsDefault = string.Equals(defaultCulture, culture, StringComparison.OrdinalIgnoreCase), + }); return cultures; } diff --git a/src/OrchardCore.Modules/OrchardCore.Localization/ModularPoFileLocationProvider.cs b/src/OrchardCore.Modules/OrchardCore.Localization/ModularPoFileLocationProvider.cs index f5b07929a0f..6b03f5314d9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Localization/ModularPoFileLocationProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Localization/ModularPoFileLocationProvider.cs @@ -37,7 +37,8 @@ public ModularPoFileLocationProvider( IHostEnvironment hostingEnvironment, IOptions shellOptions, IOptions localizationOptions, - ShellSettings shellSettings) + ShellSettings shellSettings + ) { _extensionsManager = extensionsManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Localization/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Localization/Permissions.cs index 40d80c5a8f6..99593b9878d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Localization/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Localization/Permissions.cs @@ -14,20 +14,9 @@ public class Permissions : IPermissionProvider /// public static readonly Permission ManageCultures = new("ManageCultures", "Manage supported culture"); - private readonly IEnumerable _allPermissions = - [ - ManageCultures, - ]; + private readonly IEnumerable _allPermissions = [ManageCultures,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Localization/Services/LocalizationService.cs b/src/OrchardCore.Modules/OrchardCore.Localization/Services/LocalizationService.cs index 7285b30bc05..495524a4f04 100644 --- a/src/OrchardCore.Modules/OrchardCore.Localization/Services/LocalizationService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Localization/Services/LocalizationService.cs @@ -41,8 +41,7 @@ public async Task GetSupportedCulturesAsync() return _localizationSettings.SupportedCultures == null || _localizationSettings.SupportedCultures.Length == 0 ? _supportedCultures - : _localizationSettings.SupportedCultures - ; + : _localizationSettings.SupportedCultures; } private async Task InitializeLocalizationSettingsAsync() diff --git a/src/OrchardCore.Modules/OrchardCore.Localization/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Localization/Startup.cs index 99326bc1d16..499e24fc0a0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Localization/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Localization/Startup.cs @@ -35,8 +35,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); - services.AddPortableObjectLocalization(options => options.ResourcesPath = "Localization"). - AddDataAnnotationsPortableObjectLocalization(); + services.AddPortableObjectLocalization(options => options.ResourcesPath = "Localization").AddDataAnnotationsPortableObjectLocalization(); services.Replace(ServiceDescriptor.Singleton()); } @@ -53,10 +52,7 @@ public override async ValueTask ConfigureAsync(IApplicationBuilder app, IEndpoin var localizationOptions = serviceProvider.GetService>().Value; localizationOptions.CultureInfoUseUserOverride = !cultureOptions.IgnoreSystemSettings; - localizationOptions - .SetDefaultCulture(defaultCulture) - .AddSupportedCultures(supportedCultures) - .AddSupportedUICultures(supportedCultures); + localizationOptions.SetDefaultCulture(defaultCulture).AddSupportedCultures(supportedCultures).AddSupportedUICultures(supportedCultures); app.UseRequestLocalization(localizationOptions); } @@ -67,7 +63,10 @@ public class LocalizationDeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddSiteSettingsPropertyDeploymentStep(S => S["Culture settings"], S => S["Exports the culture settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Culture settings"], + S => S["Exports the culture settings."] + ); } } @@ -96,8 +95,7 @@ public override void ConfigureServices(IServiceCollection services) { services.AddScoped, AdminCulturePickerNavbarDisplayDriver>(); - services.Configure(options => - options.AddInitialRequestCultureProvider(new AdminCookieCultureProvider(_shellSettings, _adminOptions))); + services.Configure(options => options.AddInitialRequestCultureProvider(new AdminCookieCultureProvider(_shellSettings, _adminOptions))); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Markdown/Drivers/MarkdownBodyPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Markdown/Drivers/MarkdownBodyPartDisplayDriver.cs index 95acec8ad01..93d41f505e2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Markdown/Drivers/MarkdownBodyPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Markdown/Drivers/MarkdownBodyPartDisplayDriver.cs @@ -29,12 +29,14 @@ public class MarkdownBodyPartDisplayDriver : ContentPartDisplayDriver localizer) + IStringLocalizer localizer + ) { _liquidTemplateManager = liquidTemplateManager; _htmlEncoder = htmlEncoder; @@ -53,13 +55,16 @@ public override IDisplayResult Display(MarkdownBodyPart markdownBodyPart, BuildP public override IDisplayResult Edit(MarkdownBodyPart markdownBodyPart, BuildPartEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.Markdown = markdownBodyPart.Markdown; - model.ContentItem = markdownBodyPart.ContentItem; - model.MarkdownBodyPart = markdownBodyPart; - model.TypePartDefinition = context.TypePartDefinition; - }); + return Initialize( + GetEditorShapeType(context), + model => + { + model.Markdown = markdownBodyPart.Markdown; + model.ContentItem = markdownBodyPart.ContentItem; + model.MarkdownBodyPart = markdownBodyPart; + model.TypePartDefinition = context.TypePartDefinition; + } + ); } public override async Task UpdateAsync(MarkdownBodyPart model, IUpdateModel updater, UpdatePartEditorContext context) @@ -71,7 +76,11 @@ public override async Task UpdateAsync(MarkdownBodyPart model, I if (!string.IsNullOrEmpty(viewModel.Markdown) && !_liquidTemplateManager.Validate(viewModel.Markdown, out var errors)) { var partName = context.TypePartDefinition.DisplayName(); - updater.ModelState.AddModelError(Prefix, nameof(viewModel.Markdown), S["{0} doesn't contain a valid Liquid expression. Details: {1}", partName, string.Join(" ", errors)]); + updater.ModelState.AddModelError( + Prefix, + nameof(viewModel.Markdown), + S["{0} doesn't contain a valid Liquid expression. Details: {1}", partName, string.Join(" ", errors)] + ); } else { @@ -97,16 +106,18 @@ private async ValueTask BuildViewModel(MarkdownBodyPartViewModel model, Markdown // The liquid rendering is for backwards compatibility and can be removed in a future version. if (!settings.SanitizeHtml) { - model.Html = await _liquidTemplateManager.RenderStringAsync(model.Html, _htmlEncoder, model, - new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) }); + model.Html = await _liquidTemplateManager.RenderStringAsync( + model.Html, + _htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); } - model.Html = await _shortcodeService.ProcessAsync(model.Html, - new Context - { - ["ContentItem"] = markdownBodyPart.ContentItem, - ["TypePartDefinition"] = context.TypePartDefinition - }); + model.Html = await _shortcodeService.ProcessAsync( + model.Html, + new Context { ["ContentItem"] = markdownBodyPart.ContentItem, ["TypePartDefinition"] = context.TypePartDefinition } + ); if (settings.SanitizeHtml) { diff --git a/src/OrchardCore.Modules/OrchardCore.Markdown/Drivers/MarkdownFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Markdown/Drivers/MarkdownFieldDisplayDriver.cs index c5062afbe04..590aec2ac8a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Markdown/Drivers/MarkdownFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Markdown/Drivers/MarkdownFieldDisplayDriver.cs @@ -29,12 +29,14 @@ public class MarkdownFieldDisplayDriver : ContentFieldDisplayDriver localizer) + IStringLocalizer localizer + ) { _liquidTemplateManager = liquidTemplateManager; _htmlEncoder = htmlEncoder; @@ -46,51 +48,58 @@ public MarkdownFieldDisplayDriver(ILiquidTemplateManager liquidTemplateManager, public override IDisplayResult Display(MarkdownField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), async model => - { - - var settings = context.PartFieldDefinition.GetSettings(); - model.Markdown = field.Markdown; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; + return Initialize( + GetDisplayShapeType(context), + async model => + { + var settings = context.PartFieldDefinition.GetSettings(); + model.Markdown = field.Markdown; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; - // The default Markdown option is to entity escape html - // so filters must be run after the markdown has been processed. - model.Html = _markdownService.ToHtml(model.Markdown ?? ""); + // The default Markdown option is to entity escape html + // so filters must be run after the markdown has been processed. + model.Html = _markdownService.ToHtml(model.Markdown ?? ""); - // The liquid rendering is for backwards compatability and can be removed in a future version. - if (!settings.SanitizeHtml) - { - model.Markdown = await _liquidTemplateManager.RenderStringAsync(model.Html, _htmlEncoder, model, - new Dictionary() { ["ContentItem"] = new ObjectValue(field.ContentItem) }); - } + // The liquid rendering is for backwards compatability and can be removed in a future version. + if (!settings.SanitizeHtml) + { + model.Markdown = await _liquidTemplateManager.RenderStringAsync( + model.Html, + _htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(field.ContentItem) } + ); + } - model.Html = await _shortcodeService.ProcessAsync(model.Html, - new Context - { - ["ContentItem"] = field.ContentItem, - ["PartFieldDefinition"] = context.PartFieldDefinition - }); + model.Html = await _shortcodeService.ProcessAsync( + model.Html, + new Context { ["ContentItem"] = field.ContentItem, ["PartFieldDefinition"] = context.PartFieldDefinition } + ); - if (settings.SanitizeHtml) - { - model.Html = _htmlSanitizerService.Sanitize(model.Html ?? ""); - } - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + if (settings.SanitizeHtml) + { + model.Html = _htmlSanitizerService.Sanitize(model.Html ?? ""); + } + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(MarkdownField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.Markdown = field.Markdown; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + return Initialize( + GetEditorShapeType(context), + model => + { + model.Markdown = field.Markdown; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(MarkdownField field, IUpdateModel updater, UpdateFieldEditorContext context) @@ -102,7 +111,11 @@ public override async Task UpdateAsync(MarkdownField field, IUpd if (!string.IsNullOrEmpty(viewModel.Markdown) && !_liquidTemplateManager.Validate(viewModel.Markdown, out var errors)) { var fieldName = context.PartFieldDefinition.DisplayName(); - updater.ModelState.AddModelError(Prefix, nameof(viewModel.Markdown), S["{0} field doesn't contain a valid Liquid expression. Details: {1}", fieldName, string.Join(" ", errors)]); + updater.ModelState.AddModelError( + Prefix, + nameof(viewModel.Markdown), + S["{0} field doesn't contain a valid Liquid expression. Details: {1}", fieldName, string.Join(" ", errors)] + ); } else { diff --git a/src/OrchardCore.Modules/OrchardCore.Markdown/GraphQL/MarkdownBodyQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Markdown/GraphQL/MarkdownBodyQueryObjectType.cs index 9614f1a2ee2..56bed75e8a1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Markdown/GraphQL/MarkdownBodyQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Markdown/GraphQL/MarkdownBodyQueryObjectType.cs @@ -27,11 +27,8 @@ public MarkdownBodyQueryObjectType(IStringLocalizer Name = nameof(MarkdownBodyPart); Description = S["Content stored as Markdown. You can also query the HTML interpreted version of Markdown."]; - Field("markdown", x => x.Markdown, nullable: true) - .Description(S["the markdown value"]); - Field("html") - .Description(S["the HTML representation of the markdown content"]) - .ResolveLockedAsync(ToHtml); + Field("markdown", x => x.Markdown, nullable: true).Description(S["the markdown value"]); + Field("html").Description(S["the HTML representation of the markdown content"]).ResolveLockedAsync(ToHtml); } private static async ValueTask ToHtml(IResolveFieldContext ctx) @@ -67,16 +64,15 @@ private static async ValueTask ToHtml(IResolveFieldContext() { ["ContentItem"] = new ObjectValue(model.ContentItem) }); + html = await liquidTemplateManager.RenderStringAsync( + html, + htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); } - html = await shortcodeService.ProcessAsync(html, - new Context - { - ["ContentItem"] = ctx.Source.ContentItem, - ["PartFieldDefinition"] = contentTypePartDefinition - }); + html = await shortcodeService.ProcessAsync(html, new Context { ["ContentItem"] = ctx.Source.ContentItem, ["PartFieldDefinition"] = contentTypePartDefinition }); if (settings.SanitizeHtml) { diff --git a/src/OrchardCore.Modules/OrchardCore.Markdown/GraphQL/MarkdownFieldQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Markdown/GraphQL/MarkdownFieldQueryObjectType.cs index 48a9a0db63a..2797865328e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Markdown/GraphQL/MarkdownFieldQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Markdown/GraphQL/MarkdownFieldQueryObjectType.cs @@ -29,11 +29,8 @@ public MarkdownFieldQueryObjectType(IStringLocalizer x.Markdown, nullable: true) - .Description(S["the markdown value"]); - Field("html") - .Description(S["the HTML representation of the markdown content"]) - .ResolveLockedAsync(ToHtml); + Field("markdown", x => x.Markdown, nullable: true).Description(S["the markdown value"]); + Field("html").Description(S["the HTML representation of the markdown content"]).ResolveLockedAsync(ToHtml); } private static async ValueTask ToHtml(IResolveFieldContext ctx) @@ -80,16 +77,15 @@ private static async ValueTask ToHtml(IResolveFieldContext() { ["ContentItem"] = new ObjectValue(ctx.Source.ContentItem) }); + html = await liquidTemplateManager.RenderStringAsync( + html, + htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(ctx.Source.ContentItem) } + ); } - html = await shortcodeService.ProcessAsync(html, - new Context - { - ["ContentItem"] = ctx.Source.ContentItem, - ["PartFieldDefinition"] = contentPartFieldDefinition - }); + html = await shortcodeService.ProcessAsync(html, new Context { ["ContentItem"] = ctx.Source.ContentItem, ["PartFieldDefinition"] = contentPartFieldDefinition }); if (settings.SanitizeHtml) { diff --git a/src/OrchardCore.Modules/OrchardCore.Markdown/Handlers/MarkdownBodyPartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Markdown/Handlers/MarkdownBodyPartHandler.cs index 4937def4904..2c5e8558704 100644 --- a/src/OrchardCore.Modules/OrchardCore.Markdown/Handlers/MarkdownBodyPartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Markdown/Handlers/MarkdownBodyPartHandler.cs @@ -27,12 +27,14 @@ public class MarkdownBodyPartHandler : ContentPartHandler private readonly ILiquidTemplateManager _liquidTemplateManager; private readonly HtmlEncoder _htmlEncoder; - public MarkdownBodyPartHandler(IContentDefinitionManager contentDefinitionManager, + public MarkdownBodyPartHandler( + IContentDefinitionManager contentDefinitionManager, IShortcodeService shortcodeService, IMarkdownService markdownService, IHtmlSanitizerService htmlSanitizerService, ILiquidTemplateManager liquidTemplateManager, - HtmlEncoder htmlEncoder) + HtmlEncoder htmlEncoder + ) { _contentDefinitionManager = contentDefinitionManager; _shortcodeService = shortcodeService; @@ -67,16 +69,15 @@ public override Task GetContentItemAspectAsync(ContentItemAspectContext context, ContentItem = part.ContentItem, }; - html = await _liquidTemplateManager.RenderStringAsync(html, _htmlEncoder, model, - new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) }); + html = await _liquidTemplateManager.RenderStringAsync( + html, + _htmlEncoder, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); } - html = await _shortcodeService.ProcessAsync(html, - new Context - { - ["ContentItem"] = part.ContentItem, - ["TypePartDefinition"] = contentTypePartDefinition - }); + html = await _shortcodeService.ProcessAsync(html, new Context { ["ContentItem"] = part.ContentItem, ["TypePartDefinition"] = contentTypePartDefinition }); if (settings.SanitizeHtml) { diff --git a/src/OrchardCore.Modules/OrchardCore.Markdown/Media/MediaShapes.cs b/src/OrchardCore.Modules/OrchardCore.Markdown/Media/MediaShapes.cs index 937a540786c..e4b03b6fa65 100644 --- a/src/OrchardCore.Modules/OrchardCore.Markdown/Media/MediaShapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.Markdown/Media/MediaShapes.cs @@ -9,7 +9,8 @@ public class MediaShapes : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("MarkdownBodyPart_Edit") + builder + .Describe("MarkdownBodyPart_Edit") .OnDisplaying(displaying => { var editor = displaying.Shape; @@ -20,7 +21,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("MarkdownField_Edit") + builder + .Describe("MarkdownField_Edit") .OnDisplaying(displaying => { var editor = displaying.Shape; diff --git a/src/OrchardCore.Modules/OrchardCore.Markdown/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Markdown/Migrations.cs index 66ec22a6e86..6436675814b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Markdown/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Markdown/Migrations.cs @@ -19,9 +19,10 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("MarkdownBodyPart", builder => builder - .Attachable() - .WithDescription("Provides a Markdown formatted body for your content item.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "MarkdownBodyPart", + builder => builder.Attachable().WithDescription("Provides a Markdown formatted body for your content item.") + ); // Shortcut other migration steps on new content definition schemas. return 4; @@ -44,10 +45,17 @@ public async Task UpdateFrom2Async() { if (contentType.Parts.Any(x => x.PartDefinition.Name == "MarkdownBodyPart")) { - await _contentDefinitionManager.AlterTypeDefinitionAsync(contentType.Name, x => x.WithPart("MarkdownBodyPart", part => - { - part.MergeSettings(x => x.SanitizeHtml = false); - })); + await _contentDefinitionManager.AlterTypeDefinitionAsync( + contentType.Name, + x => + x.WithPart( + "MarkdownBodyPart", + part => + { + part.MergeSettings(x => x.SanitizeHtml = false); + } + ) + ); } } @@ -63,16 +71,22 @@ public async Task UpdateFrom3Async() { if (partDefinition.Fields.Any(x => x.FieldDefinition.Name == "MarkdownField")) { - await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, partBuilder => - { - foreach (var fieldDefinition in partDefinition.Fields.Where(x => x.FieldDefinition.Name == "MarkdownField")) + await _contentDefinitionManager.AlterPartDefinitionAsync( + partDefinition.Name, + partBuilder => { - partBuilder.WithField(fieldDefinition.Name, fieldBuilder => + foreach (var fieldDefinition in partDefinition.Fields.Where(x => x.FieldDefinition.Name == "MarkdownField")) { - fieldBuilder.MergeSettings(s => s.SanitizeHtml = false); - }); + partBuilder.WithField( + fieldDefinition.Name, + fieldBuilder => + { + fieldBuilder.MergeSettings(s => s.SanitizeHtml = false); + } + ); + } } - }); + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Markdown/Settings/MarkdownBodyPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Markdown/Settings/MarkdownBodyPartSettingsDisplayDriver.cs index c1e80881c81..5c929176da0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Markdown/Settings/MarkdownBodyPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Markdown/Settings/MarkdownBodyPartSettingsDisplayDriver.cs @@ -12,12 +12,15 @@ public class MarkdownBodyPartSettingsDisplayDriver : ContentTypePartDefinitionDi { public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("MarkdownBodyPartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + "MarkdownBodyPartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); - model.SanitizeHtml = settings.SanitizeHtml; - }) + model.SanitizeHtml = settings.SanitizeHtml; + } + ) .Location("Content:20"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Markdown/Settings/MarkdownFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.Markdown/Settings/MarkdownFieldSettingsDriver.cs index 5deba7bb77c..7c3249aeb18 100644 --- a/src/OrchardCore.Modules/OrchardCore.Markdown/Settings/MarkdownFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Markdown/Settings/MarkdownFieldSettingsDriver.cs @@ -11,14 +11,17 @@ public class MarkdownFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriv { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("MarkdownFieldSettings_Edit", model => - { - - var settings = partFieldDefinition.GetSettings(); + return Initialize( + "MarkdownFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.GetSettings(); - model.SanitizeHtml = settings.SanitizeHtml; - model.Hint = settings.Hint; - }).Location("Content:20"); + model.SanitizeHtml = settings.SanitizeHtml; + model.Hint = settings.Hint; + } + ) + .Location("Content:20"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Markdown/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Markdown/Startup.cs index 615decbd63f..6ca60ec8ba9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Markdown/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Markdown/Startup.cs @@ -35,35 +35,35 @@ public Startup(IShellConfiguration shellConfiguration) public override void ConfigureServices(IServiceCollection services) { - services.Configure(o => - { - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - }) - .AddLiquidFilter("markdownify"); + services + .Configure(o => + { + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); + }) + .AddLiquidFilter("markdownify"); // Markdown Part - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddDataMigration(); services.AddScoped(); // Markdown Field - services.AddContentField() - .UseDisplayDriver(); + services.AddContentField().UseDisplayDriver(); services.AddScoped(); services.AddScoped(); services.AddOptions(); - services.ConfigureMarkdownPipeline((pipeline) => - { - var extensions = _shellConfiguration.GetValue("OrchardCore_Markdown:Extensions", DefaultMarkdownExtensions); - pipeline.Configure(extensions); - }); + services.ConfigureMarkdownPipeline( + (pipeline) => + { + var extensions = _shellConfiguration.GetValue("OrchardCore_Markdown:Extensions", DefaultMarkdownExtensions); + pipeline.Configure(extensions); + } + ); services.AddScoped(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AdminMenu.cs index c0d1515c551..39f8a711aed 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AdminMenu.cs @@ -20,14 +20,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder.Add(S["Configuration"], configuration => configuration - .Add(S["Media"], S["Media"].PrefixPosition(), media => media - .Add(S["Amazon S3 Options"], S["Amazon S3 Options"].PrefixPosition(), options => options - .Action("Options", "Admin", "OrchardCore.Media.AmazonS3") - .Permission(Permissions.ViewAmazonS3MediaOptions) - .LocalNav() + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Media"], + S["Media"].PrefixPosition(), + media => + media.Add( + S["Amazon S3 Options"], + S["Amazon S3 Options"].PrefixPosition(), + options => options.Action("Options", "Admin", "OrchardCore.Media.AmazonS3").Permission(Permissions.ViewAmazonS3MediaOptions).LocalNav() + ) ) - ) ); return Task.CompletedTask; diff --git a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AwsStorageOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AwsStorageOptionsConfiguration.cs index 7c3229a4b56..4d350b00fbe 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AwsStorageOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AwsStorageOptionsConfiguration.cs @@ -17,10 +17,7 @@ public class AwsStorageOptionsConfiguration : IConfigureOptions logger) + public AwsStorageOptionsConfiguration(IShellConfiguration shellConfiguration, ShellSettings shellSettings, ILogger logger) { _shellConfiguration = shellConfiguration; _shellSettings = shellSettings; @@ -48,11 +45,7 @@ private void ParseBucketName(AwsStorageOptions options, TemplateContext template { var template = _fluidParser.Parse(options.BucketName); - options.BucketName = template - .Render(templateContext, NullEncoder.Default) - .Replace("\r", string.Empty) - .Replace("\n", string.Empty) - .Trim(); + options.BucketName = template.Render(templateContext, NullEncoder.Default).Replace("\r", string.Empty).Replace("\n", string.Empty).Trim(); } catch (Exception e) { @@ -66,11 +59,7 @@ private void ParseBasePath(AwsStorageOptions options, TemplateContext templateCo { var template = _fluidParser.Parse(options.BasePath); - options.BasePath = template - .Render(templateContext, NullEncoder.Default) - .Replace("\r", string.Empty) - .Replace("\n", string.Empty) - .Trim(); + options.BasePath = template.Render(templateContext, NullEncoder.Default).Replace("\r", string.Empty).Replace("\n", string.Empty).Trim(); } catch (Exception e) { diff --git a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AwsStorageOptionsExtension.cs b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AwsStorageOptionsExtension.cs index 4c45b3d30e2..2abf6755dd2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AwsStorageOptionsExtension.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/AwsStorageOptionsExtension.cs @@ -54,8 +54,7 @@ public static AwsStorageOptions BindConfiguration(this AwsStorageOptions options var secretKey = credentials.GetValue(Constants.AwsCredentialParamNames.SecretKey, string.Empty); var accessKey = credentials.GetValue(Constants.AwsCredentialParamNames.AccessKey, string.Empty); - if (!string.IsNullOrWhiteSpace(accessKey) || - !string.IsNullOrWhiteSpace(secretKey)) + if (!string.IsNullOrWhiteSpace(accessKey) || !string.IsNullOrWhiteSpace(secretKey)) { var awsCredentials = new BasicAWSCredentials(accessKey, secretKey); options.AwsOptions.Credentials = awsCredentials; diff --git a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Controllers/AdminController.cs index 31c67894a66..f363ac986ac 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Controllers/AdminController.cs @@ -19,11 +19,7 @@ public class AdminController : Controller private readonly INotifier _notifier; protected readonly IHtmlLocalizer H; - public AdminController( - IAuthorizationService authorizationService, - IOptions options, - INotifier notifier, - IHtmlLocalizer htmlLocalizer) + public AdminController(IAuthorizationService authorizationService, IOptions options, INotifier notifier, IHtmlLocalizer htmlLocalizer) { _authorizationService = authorizationService; _notifier = notifier; @@ -37,7 +33,7 @@ public async Task Options() { return Forbid(); } - + if (_options.Validate().Any()) { await _notifier.ErrorAsync(H["The Amazon S3 Media feature is enabled, but it was not configured with appsettings.json."]); diff --git a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Manifest.cs index 8b80f659975..836581f5e0a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Manifest.cs @@ -11,9 +11,6 @@ Id = "OrchardCore.Media.AmazonS3", Name = "Amazon Media Storage", Description = "Enables support for storing media files in Amazon S3 Bucket.", - Dependencies = - [ - "OrchardCore.Media.Cache" - ], + Dependencies = ["OrchardCore.Media.Cache"], Category = "Hosting" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/MediaS3BucketTenantEvents.cs b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/MediaS3BucketTenantEvents.cs index bed1647e533..fcbf8413b10 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/MediaS3BucketTenantEvents.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/MediaS3BucketTenantEvents.cs @@ -25,7 +25,8 @@ public MediaS3BucketTenantEvents( IAmazonS3 amazonS3Client, IOptions options, IStringLocalizer localizer, - ILogger logger) + ILogger logger + ) { _shellSettings = shellSettings; _amazonS3Client = amazonS3Client; @@ -36,9 +37,7 @@ public MediaS3BucketTenantEvents( public override async Task ActivatingAsync() { - if (!_options.CreateBucket || - _shellSettings.IsUninitialized() || - string.IsNullOrEmpty(_options.BucketName)) + if (!_options.CreateBucket || _shellSettings.IsUninitialized() || string.IsNullOrEmpty(_options.BucketName)) { return; } @@ -55,11 +54,7 @@ public override async Task ActivatingAsync() return; } - var bucketRequest = new PutBucketRequest - { - BucketName = _options.BucketName, - UseClientRegion = true - }; + var bucketRequest = new PutBucketRequest { BucketName = _options.BucketName, UseClientRegion = true }; // Trying to create bucket. var response = await _amazonS3Client.PutBucketAsync(bucketRequest); @@ -80,11 +75,9 @@ public override async Task ActivatingAsync() RestrictPublicBuckets = true }; - await _amazonS3Client.PutPublicAccessBlockAsync(new PutPublicAccessBlockRequest - { - PublicAccessBlockConfiguration = blockConfiguration, - BucketName = _options.BucketName - }); + await _amazonS3Client.PutPublicAccessBlockAsync( + new PutPublicAccessBlockRequest { PublicAccessBlockConfiguration = blockConfiguration, BucketName = _options.BucketName } + ); _logger.LogDebug("Amazon S3 Bucket {BucketName} created.", _options.BucketName); } @@ -109,11 +102,7 @@ public override async Task RemovingAsync(ShellRemovingContext context) return; } - var bucketRequest = new DeleteBucketRequest - { - BucketName = _options.BucketName, - UseClientRegion = true - }; + var bucketRequest = new DeleteBucketRequest { BucketName = _options.BucketName, UseClientRegion = true }; // Trying to delete bucket. var response = await _amazonS3Client.DeleteBucketAsync(bucketRequest); diff --git a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Permissions.cs index 443b56a25ee..491ea4ea08e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ViewAmazonS3MediaOptions = new("ViewAmazonS3MediaOptions", "View Amazon S3 Media Options"); - private readonly IEnumerable _allPermissions = - [ - ViewAmazonS3MediaOptions, - ]; + private readonly IEnumerable _allPermissions = [ViewAmazonS3MediaOptions,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Startup.cs index 3a30f3a99de..2f5a9890fab 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Startup.cs @@ -27,10 +27,7 @@ public class Startup : Modules.StartupBase private readonly ILogger _logger; private readonly IShellConfiguration _configuration; - public Startup(IShellConfiguration configuration, - ILogger logger) - => (_configuration, _logger) - = (configuration, logger); + public Startup(IShellConfiguration configuration, ILogger logger) => (_configuration, _logger) = (configuration, logger); public override void ConfigureServices(IServiceCollection services) { @@ -53,8 +50,7 @@ public override void ConfigureServices(IServiceCollection services) } else { - _logger.LogInformation( - "Starting with S3 Media Configuration. BucketName: {BucketName}; BasePath: {BasePath}", storeOptions.BucketName, storeOptions.BasePath); + _logger.LogInformation("Starting with S3 Media Configuration. BucketName: {BucketName}; BasePath: {BasePath}", storeOptions.BucketName, storeOptions.BasePath); services.AddSingleton(serviceProvider => { @@ -69,8 +65,7 @@ public override void ConfigureServices(IServiceCollection services) var shellSettings = serviceProvider.GetRequiredService(); var logger = serviceProvider.GetRequiredService>(); - var mediaCachePath = GetMediaCachePath( - hostingEnvironment, shellSettings, DefaultMediaFileStoreCacheFileProvider.AssetsCachePath); + var mediaCachePath = GetMediaCachePath(hostingEnvironment, shellSettings, DefaultMediaFileStoreCacheFileProvider.AssetsCachePath); if (!Directory.Exists(mediaCachePath)) { @@ -81,47 +76,41 @@ public override void ConfigureServices(IServiceCollection services) }); // Replace the default media file provider with the media cache file provider. - services.Replace(ServiceDescriptor.Singleton(serviceProvider => - serviceProvider.GetRequiredService())); + services.Replace(ServiceDescriptor.Singleton(serviceProvider => serviceProvider.GetRequiredService())); // Register the media cache file provider as a file store cache provider. - services.AddSingleton(serviceProvider => - serviceProvider.GetRequiredService()); + services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService()); // Registering IAmazonS3 client using AWS registration factory. services.AddAWSService(storeOptions.AwsOptions); - services.Replace(ServiceDescriptor.Singleton(serviceProvider => - { - var shellSettings = serviceProvider.GetRequiredService(); - var mediaOptions = serviceProvider.GetRequiredService>().Value; - var mediaEventHandlers = serviceProvider.GetServices(); - var mediaCreatingEventHandlers = serviceProvider.GetServices(); - var clock = serviceProvider.GetRequiredService(); - var logger = serviceProvider.GetRequiredService>(); - var amazonS3Client = serviceProvider.GetService(); + services.Replace( + ServiceDescriptor.Singleton(serviceProvider => + { + var shellSettings = serviceProvider.GetRequiredService(); + var mediaOptions = serviceProvider.GetRequiredService>().Value; + var mediaEventHandlers = serviceProvider.GetServices(); + var mediaCreatingEventHandlers = serviceProvider.GetServices(); + var clock = serviceProvider.GetRequiredService(); + var logger = serviceProvider.GetRequiredService>(); + var amazonS3Client = serviceProvider.GetService(); - var options = serviceProvider.GetRequiredService>(); - var fileStore = new AwsFileStore(clock, options.Value, amazonS3Client); + var options = serviceProvider.GetRequiredService>(); + var fileStore = new AwsFileStore(clock, options.Value, amazonS3Client); - var mediaUrlBase = $"/{fileStore.Combine(shellSettings.RequestUrlPrefix, mediaOptions.AssetsRequestPath)}"; + var mediaUrlBase = $"/{fileStore.Combine(shellSettings.RequestUrlPrefix, mediaOptions.AssetsRequestPath)}"; - var originalPathBase = serviceProvider.GetRequiredService().HttpContext - ?.Features.Get() - ?.OriginalPathBase ?? PathString.Empty; + var originalPathBase = + serviceProvider.GetRequiredService().HttpContext?.Features.Get()?.OriginalPathBase ?? PathString.Empty; - if (originalPathBase.HasValue) - { - mediaUrlBase = fileStore.Combine(originalPathBase.Value, mediaUrlBase); - } + if (originalPathBase.HasValue) + { + mediaUrlBase = fileStore.Combine(originalPathBase.Value, mediaUrlBase); + } - return new DefaultMediaFileStore(fileStore, - mediaUrlBase, - mediaOptions.CdnBaseUrl, - mediaEventHandlers, - mediaCreatingEventHandlers, - logger); - })); + return new DefaultMediaFileStore(fileStore, mediaUrlBase, mediaOptions.CdnBaseUrl, mediaEventHandlers, mediaCreatingEventHandlers, logger); + }) + ); services.AddSingleton(); @@ -129,6 +118,6 @@ public override void ConfigureServices(IServiceCollection services) } } - private static string GetMediaCachePath(IWebHostEnvironment hostingEnvironment, ShellSettings shellSettings, string assetsPath) - => PathExtensions.Combine(hostingEnvironment.WebRootPath, shellSettings.Name, assetsPath); + private static string GetMediaCachePath(IWebHostEnvironment hostingEnvironment, ShellSettings shellSettings, string assetsPath) => + PathExtensions.Combine(hostingEnvironment.WebRootPath, shellSettings.Name, assetsPath); } diff --git a/src/OrchardCore.Modules/OrchardCore.Media.Azure/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Media.Azure/AdminMenu.cs index 0a1cb02248f..4a7ddc4c982 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.Azure/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.Azure/AdminMenu.cs @@ -20,14 +20,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder.Add(S["Configuration"], configuration => configuration - .Add(S["Media"], S["Media"].PrefixPosition(), media => media - .Add(S["Azure Blob Options"], S["Azure Blob Options"].PrefixPosition(), options => options - .Action("Options", "Admin", "OrchardCore.Media.Azure") - .Permission(Permissions.ViewAzureMediaOptions) - .LocalNav() + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Media"], + S["Media"].PrefixPosition(), + media => + media.Add( + S["Azure Blob Options"], + S["Azure Blob Options"].PrefixPosition(), + options => options.Action("Options", "Admin", "OrchardCore.Media.Azure").Permission(Permissions.ViewAzureMediaOptions).LocalNav() + ) ) - ) ); return Task.CompletedTask; diff --git a/src/OrchardCore.Modules/OrchardCore.Media.Azure/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Media.Azure/Controllers/AdminController.cs index 4a641df0d2c..efb425370dc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.Azure/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.Azure/Controllers/AdminController.cs @@ -15,9 +15,7 @@ public class AdminController : Controller private readonly IAuthorizationService _authorizationService; private readonly MediaBlobStorageOptions _options; - public AdminController( - IAuthorizationService authorizationService, - IOptions options) + public AdminController(IAuthorizationService authorizationService, IOptions options) { _authorizationService = authorizationService; _options = options.Value; diff --git a/src/OrchardCore.Modules/OrchardCore.Media.Azure/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Media.Azure/Manifest.cs index 0449bb985a8..50656679854 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.Azure/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.Azure/Manifest.cs @@ -11,9 +11,6 @@ Id = "OrchardCore.Media.Azure.Storage", Name = "Azure Media Storage", Description = "Enables support for storing media files in Microsoft Azure Blob Storage.", - Dependencies = - [ - "OrchardCore.Media.Cache" - ], + Dependencies = ["OrchardCore.Media.Cache"], Category = "Hosting" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Media.Azure/MediaBlobContainerTenantEvents.cs b/src/OrchardCore.Modules/OrchardCore.Media.Azure/MediaBlobContainerTenantEvents.cs index 8d9905048f4..dd69b5ae95c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.Azure/MediaBlobContainerTenantEvents.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.Azure/MediaBlobContainerTenantEvents.cs @@ -23,7 +23,7 @@ public MediaBlobContainerTenantEvents( ShellSettings shellSettings, IStringLocalizer localizer, ILogger logger - ) + ) { _options = options.Value; _shellSettings = shellSettings; @@ -34,11 +34,7 @@ ILogger logger public override async Task ActivatingAsync() { // Only create container if options are valid. - if (_shellSettings.IsUninitialized() || - string.IsNullOrEmpty(_options.ConnectionString) || - string.IsNullOrEmpty(_options.ContainerName) || - !_options.CreateContainer - ) + if (_shellSettings.IsUninitialized() || string.IsNullOrEmpty(_options.ConnectionString) || string.IsNullOrEmpty(_options.ContainerName) || !_options.CreateContainer) { return; } @@ -61,9 +57,7 @@ public override async Task ActivatingAsync() public override async Task RemovingAsync(ShellRemovingContext context) { // Only remove container if options are valid. - if (!_options.RemoveContainer || - string.IsNullOrEmpty(_options.ConnectionString) || - string.IsNullOrEmpty(_options.ContainerName)) + if (!_options.RemoveContainer || string.IsNullOrEmpty(_options.ConnectionString) || string.IsNullOrEmpty(_options.ContainerName)) { return; } diff --git a/src/OrchardCore.Modules/OrchardCore.Media.Azure/MediaBlobStorageOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Media.Azure/MediaBlobStorageOptionsConfiguration.cs index 522b5b5db25..d9024c282e8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.Azure/MediaBlobStorageOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.Azure/MediaBlobStorageOptionsConfiguration.cs @@ -17,11 +17,7 @@ public class MediaBlobStorageOptionsConfiguration : IConfigureOptions logger - ) + public MediaBlobStorageOptionsConfiguration(IShellConfiguration shellConfiguration, ShellSettings shellSettings, ILogger logger) { _shellConfiguration = shellConfiguration; _shellSettings = shellSettings; diff --git a/src/OrchardCore.Modules/OrchardCore.Media.Azure/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Media.Azure/Permissions.cs index a92526b37be..fff06ea35c8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.Azure/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.Azure/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ViewAzureMediaOptions = new("ViewAzureMediaOptions", "View Azure Media Options"); - private readonly IEnumerable _allPermissions = - [ - ViewAzureMediaOptions, - ]; + private readonly IEnumerable _allPermissions = [ViewAzureMediaOptions,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Media.Azure/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Media.Azure/Startup.cs index 513fc37613a..fe6fcb2a49b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.Azure/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.Azure/Startup.cs @@ -65,8 +65,7 @@ public override void ConfigureServices(IServiceCollection services) var shellSettings = serviceProvider.GetRequiredService(); var logger = serviceProvider.GetRequiredService>(); - var mediaCachePath = GetMediaCachePath( - hostingEnvironment, shellSettings, DefaultMediaFileStoreCacheFileProvider.AssetsCachePath); + var mediaCachePath = GetMediaCachePath(hostingEnvironment, shellSettings, DefaultMediaFileStoreCacheFileProvider.AssetsCachePath); if (!Directory.Exists(mediaCachePath)) { @@ -77,40 +76,39 @@ public override void ConfigureServices(IServiceCollection services) }); // Replace the default media file provider with the media cache file provider. - services.Replace(ServiceDescriptor.Singleton(serviceProvider => - serviceProvider.GetRequiredService())); + services.Replace(ServiceDescriptor.Singleton(serviceProvider => serviceProvider.GetRequiredService())); // Register the media cache file provider as a file store cache provider. - services.AddSingleton(serviceProvider => - serviceProvider.GetRequiredService()); + services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService()); // Replace the default media file store with a blob file store. - services.Replace(ServiceDescriptor.Singleton(serviceProvider => - { - var blobStorageOptions = serviceProvider.GetRequiredService>().Value; - var shellOptions = serviceProvider.GetRequiredService>(); - var shellSettings = serviceProvider.GetRequiredService(); - var mediaOptions = serviceProvider.GetRequiredService>().Value; - var clock = serviceProvider.GetRequiredService(); - var contentTypeProvider = serviceProvider.GetRequiredService(); - var mediaEventHandlers = serviceProvider.GetServices(); - var mediaCreatingEventHandlers = serviceProvider.GetServices(); - var logger = serviceProvider.GetRequiredService>(); - - var fileStore = new BlobFileStore(blobStorageOptions, clock, contentTypeProvider); - var mediaUrlBase = "/" + fileStore.Combine(shellSettings.RequestUrlPrefix, mediaOptions.AssetsRequestPath); - - var originalPathBase = serviceProvider.GetRequiredService().HttpContext - ?.Features.Get() - ?.OriginalPathBase ?? PathString.Empty; - - if (originalPathBase.HasValue) + services.Replace( + ServiceDescriptor.Singleton(serviceProvider => { - mediaUrlBase = fileStore.Combine(originalPathBase.Value, mediaUrlBase); - } - - return new DefaultMediaFileStore(fileStore, mediaUrlBase, mediaOptions.CdnBaseUrl, mediaEventHandlers, mediaCreatingEventHandlers, logger); - })); + var blobStorageOptions = serviceProvider.GetRequiredService>().Value; + var shellOptions = serviceProvider.GetRequiredService>(); + var shellSettings = serviceProvider.GetRequiredService(); + var mediaOptions = serviceProvider.GetRequiredService>().Value; + var clock = serviceProvider.GetRequiredService(); + var contentTypeProvider = serviceProvider.GetRequiredService(); + var mediaEventHandlers = serviceProvider.GetServices(); + var mediaCreatingEventHandlers = serviceProvider.GetServices(); + var logger = serviceProvider.GetRequiredService>(); + + var fileStore = new BlobFileStore(blobStorageOptions, clock, contentTypeProvider); + var mediaUrlBase = "/" + fileStore.Combine(shellSettings.RequestUrlPrefix, mediaOptions.AssetsRequestPath); + + var originalPathBase = + serviceProvider.GetRequiredService().HttpContext?.Features.Get()?.OriginalPathBase ?? PathString.Empty; + + if (originalPathBase.HasValue) + { + mediaUrlBase = fileStore.Combine(originalPathBase.Value, mediaUrlBase); + } + + return new DefaultMediaFileStore(fileStore, mediaUrlBase, mediaOptions.CdnBaseUrl, mediaEventHandlers, mediaCreatingEventHandlers, logger); + }) + ); services.AddSingleton(); @@ -118,8 +116,8 @@ public override void ConfigureServices(IServiceCollection services) } } - private static string GetMediaCachePath(IWebHostEnvironment hostingEnvironment, ShellSettings shellSettings, string assetsPath) - => PathExtensions.Combine(hostingEnvironment.WebRootPath, shellSettings.Name, assetsPath); + private static string GetMediaCachePath(IWebHostEnvironment hostingEnvironment, ShellSettings shellSettings, string assetsPath) => + PathExtensions.Combine(hostingEnvironment.WebRootPath, shellSettings.Name, assetsPath); private static bool CheckOptions(string connectionString, string containerName, ILogger logger) { diff --git a/src/OrchardCore.Modules/OrchardCore.Media.Indexing.OpenXML/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Media.Indexing.OpenXML/Manifest.cs index 404c84a7698..f7111af27e1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.Indexing.OpenXML/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.Indexing.OpenXML/Manifest.cs @@ -3,10 +3,7 @@ [assembly: Module( Name = "OpenXML Media Indexing", Description = "Provides a way to index Office files such as Word and Power Point in search providers", - Dependencies = - [ - "OrchardCore.Media.Indexing" - ], + Dependencies = ["OrchardCore.Media.Indexing"], Category = "Search", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, diff --git a/src/OrchardCore.Modules/OrchardCore.Media.Indexing.Pdf/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Media.Indexing.Pdf/Manifest.cs index eeb3db0054c..e543a77e6a0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.Indexing.Pdf/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.Indexing.Pdf/Manifest.cs @@ -3,10 +3,7 @@ [assembly: Module( Name = "PDF Media Indexing", Description = "Provides a way to index PDF files in search providers.", - Dependencies = - [ - "OrchardCore.Media.Indexing" - ], + Dependencies = ["OrchardCore.Media.Indexing"], Category = "Search", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, diff --git a/src/OrchardCore.Modules/OrchardCore.Media/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Media/AdminMenu.cs index 1ccb1514413..9c51e7de147 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/AdminMenu.cs @@ -20,30 +20,38 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Content"], content => content - .AddClass("media") - .Id("media") - .Add(S["Media Library"], S["Media Library"].PrefixPosition(), media => media - .Permission(Permissions.ManageMedia) - .Action("Index", "Admin", "OrchardCore.Media") - .LocalNav() - ) - ); + builder.Add( + S["Content"], + content => + content + .AddClass("media") + .Id("media") + .Add( + S["Media Library"], + S["Media Library"].PrefixPosition(), + media => media.Permission(Permissions.ManageMedia).Action("Index", "Admin", "OrchardCore.Media").LocalNav() + ) + ); - builder.Add(S["Configuration"], configuration => configuration - .Add(S["Media"], S["Media"].PrefixPosition(), media => media - .Add(S["Media Options"], S["Media Options"].PrefixPosition(), options => options - .Action("Options", "Admin", "OrchardCore.Media") - .Permission(Permissions.ViewMediaOptions) - .LocalNav() - ) - .Add(S["Media Profiles"], S["Media Profiles"].PrefixPosition(), mediaProfiles => mediaProfiles - .Action("Index", "MediaProfiles", "OrchardCore.Media") - .Permission(Permissions.ManageMediaProfiles) - .LocalNav() + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Media"], + S["Media"].PrefixPosition(), + media => + media + .Add( + S["Media Options"], + S["Media Options"].PrefixPosition(), + options => options.Action("Options", "Admin", "OrchardCore.Media").Permission(Permissions.ViewMediaOptions).LocalNav() + ) + .Add( + S["Media Profiles"], + S["Media Profiles"].PrefixPosition(), + mediaProfiles => mediaProfiles.Action("Index", "MediaProfiles", "OrchardCore.Media").Permission(Permissions.ManageMediaProfiles).LocalNav() + ) ) - ) ); return Task.CompletedTask; @@ -66,13 +74,20 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder.Add(S["Configuration"], configuration => configuration - .Add(S["Media"], S["Media"].PrefixPosition(), media => media - .Add(S["Media Cache"], S["Media Cache"].PrefixPosition(), cache => cache - .Action("Index", "MediaCache", "OrchardCore.Media") - .Permission(MediaCachePermissions.ManageAssetCache) - .LocalNav()) - )); + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Media"], + S["Media"].PrefixPosition(), + media => + media.Add( + S["Media Cache"], + S["Media Cache"].PrefixPosition(), + cache => cache.Action("Index", "MediaCache", "OrchardCore.Media").Permission(MediaCachePermissions.ManageAssetCache).LocalNav() + ) + ) + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Media/Controllers/AdminController.cs index 9fbc57b66c0..32592d21fb3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Controllers/AdminController.cs @@ -43,7 +43,7 @@ public AdminController( IStringLocalizer stringLocalizer, IUserAssetFolderNameProvider userAssetFolderNameProvider, IChunkFileUploadService chunkFileUploadService - ) + ) { _mediaFileStore = mediaFileStore; _mediaNameNormalizerService = mediaNameNormalizerService; @@ -85,13 +85,17 @@ public async Task>> GetFolders(string } // create default folders if not exist - if (await _authorizationService.AuthorizeAsync(User, Permissions.ManageOwnMedia) - && await _mediaFileStore.GetDirectoryInfoAsync(_mediaFileStore.Combine(_mediaOptions.AssetsUsersFolder, _userAssetFolderNameProvider.GetUserAssetFolderName(User))) == null) + if ( + await _authorizationService.AuthorizeAsync(User, Permissions.ManageOwnMedia) + && await _mediaFileStore.GetDirectoryInfoAsync(_mediaFileStore.Combine(_mediaOptions.AssetsUsersFolder, _userAssetFolderNameProvider.GetUserAssetFolderName(User))) + == null + ) { await _mediaFileStore.TryCreateDirectoryAsync(_mediaFileStore.Combine(_mediaOptions.AssetsUsersFolder, _userAssetFolderNameProvider.GetUserAssetFolderName(User))); } - var allowed = _mediaFileStore.GetDirectoryContentAsync(path) + var allowed = _mediaFileStore + .GetDirectoryContentAsync(path) .WhereAwait(async e => e.IsDirectory && await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)e.Path)); return Ok(await allowed.ToListAsync()); @@ -104,8 +108,10 @@ public async Task>> GetMediaItems(string path, path = string.Empty; } - if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) - || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)path)) + if ( + !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) + || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)path) + ) { return Forbid(); } @@ -117,8 +123,13 @@ public async Task>> GetMediaItems(string path, var allowedExtensions = GetRequestedExtensions(extensions, false); - var allowed = _mediaFileStore.GetDirectoryContentAsync(path) - .WhereAwait(async e => !e.IsDirectory && (allowedExtensions.Count == 0 || allowedExtensions.Contains(Path.GetExtension(e.Path))) && await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)e.Path)) + var allowed = _mediaFileStore + .GetDirectoryContentAsync(path) + .WhereAwait(async e => + !e.IsDirectory + && (allowedExtensions.Count == 0 || allowedExtensions.Contains(Path.GetExtension(e.Path))) + && await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)e.Path) + ) .Select(e => CreateFileResult(e)); return Ok(await allowed.ToListAsync()); @@ -159,7 +170,6 @@ public async Task Upload(string path, string extensions) return await _chunkFileUploadService.ProcessRequestAsync( Request, - // We need this empty object because the frontend expects a JSON object in the response. (_, _, _) => Task.FromResult(Ok(new { })), async (files) => @@ -178,13 +188,15 @@ public async Task Upload(string path, string extensions) if (!allowedExtensions.Contains(extension)) { - result.Add(new - { - name = file.FileName, - size = file.Length, - folder = path, - error = S["This file extension is not allowed: {0}", extension].ToString() - }); + result.Add( + new + { + name = file.FileName, + size = file.Length, + folder = path, + error = S["This file extension is not allowed: {0}", extension].ToString() + } + ); if (_logger.IsEnabled(LogLevel.Information)) { @@ -211,13 +223,15 @@ public async Task Upload(string path, string extensions) { _logger.LogError(ex, "An error occurred while uploading a media"); - result.Add(new - { - name = fileName, - size = file.Length, - folder = path, - error = ex.Message - }); + result.Add( + new + { + name = fileName, + size = file.Length, + folder = path, + error = ex.Message + } + ); } finally { @@ -226,14 +240,17 @@ public async Task Upload(string path, string extensions) } return Ok(new { files = result.ToArray() }); - }); + } + ); } [HttpPost] public async Task DeleteFolder(string path) { - if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) - || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)path)) + if ( + !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) + || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)path) + ) { return Forbid(); } @@ -260,8 +277,10 @@ public async Task DeleteFolder(string path) [HttpPost] public async Task DeleteMedia(string path) { - if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) - || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)path)) + if ( + !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) + || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)path) + ) { return Forbid(); } @@ -282,8 +301,10 @@ public async Task DeleteMedia(string path) [HttpPost] public async Task MoveMedia(string oldPath, string newPath) { - if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) - || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)oldPath)) + if ( + !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) + || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)oldPath) + ) { return Forbid(); } @@ -350,16 +371,16 @@ public async Task DeleteMediaList(string[] paths) [HttpPost] public async Task MoveMediaList(string[] mediaNames, string sourceFolder, string targetFolder) { - if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) + if ( + !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)sourceFolder) - || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)targetFolder)) + || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)targetFolder) + ) { return Forbid(); } - if ((mediaNames == null) || (mediaNames.Length < 1) - || string.IsNullOrEmpty(sourceFolder) - || string.IsNullOrEmpty(targetFolder)) + if ((mediaNames == null) || (mediaNames.Length < 1) || string.IsNullOrEmpty(sourceFolder) || string.IsNullOrEmpty(targetFolder)) { return NotFound(); } @@ -392,9 +413,7 @@ public async Task MoveMediaList(string[] mediaNames, string sourc } [HttpPost] - public async Task> CreateFolder( - string path, string name, - [FromServices] IAuthorizationService authorizationService) + public async Task> CreateFolder(string path, string name, [FromServices] IAuthorizationService authorizationService) { if (string.IsNullOrEmpty(path)) { @@ -410,8 +429,10 @@ public async Task> CreateFolder( var newPath = _mediaFileStore.Combine(path, name); - if (!await authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) - || !await authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)newPath)) + if ( + !await authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) + || !await authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)newPath) + ) { return Forbid(); } @@ -475,9 +496,7 @@ private HashSet GetRequestedExtensions(string exts, bool fallback) { var extensions = exts.Split(_extensionSeperator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - var requestedExtensions = _mediaOptions.AllowedFileExtensions - .Intersect(extensions) - .ToHashSet(StringComparer.OrdinalIgnoreCase); + var requestedExtensions = _mediaOptions.AllowedFileExtensions.Intersect(extensions).ToHashSet(StringComparer.OrdinalIgnoreCase); if (requestedExtensions.Count > 0) { @@ -487,8 +506,7 @@ private HashSet GetRequestedExtensions(string exts, bool fallback) if (fallback) { - return _mediaOptions.AllowedFileExtensions - .ToHashSet(StringComparer.OrdinalIgnoreCase); + return _mediaOptions.AllowedFileExtensions.ToHashSet(StringComparer.OrdinalIgnoreCase); } return []; diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaCacheController.cs b/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaCacheController.cs index 2f7399159d5..976ebba60f4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaCacheController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaCacheController.cs @@ -25,7 +25,7 @@ public MediaCacheController( IServiceProvider serviceProvider, INotifier notifier, IHtmlLocalizer htmlLocalizer - ) + ) { _authorizationService = authorizationService; // Resolve from service provider as the service will not be registered if configuration is invalid. @@ -41,10 +41,7 @@ public async Task Index() { return Forbid(); } - var model = new MediaCacheViewModel - { - IsConfigured = _mediaFileStoreCache != null - }; + var model = new MediaCacheViewModel { IsConfigured = _mediaFileStoreCache != null }; return View(model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaProfilesController.cs b/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaProfilesController.cs index 172502aad50..f5fc8401353 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaProfilesController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaProfilesController.cs @@ -45,7 +45,7 @@ public MediaProfilesController( IShapeFactory shapeFactory, IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer - ) + ) { _authorizationService = authorizationService; _mediaProfilesManager = mediaProfilesManager; @@ -77,10 +77,7 @@ public async Task Index(ContentOptions options, PagerParameters p var count = mediaProfiles.Count; - mediaProfiles = mediaProfiles.OrderBy(x => x.Key) - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize) - .ToList(); + mediaProfiles = mediaProfiles.OrderBy(x => x.Key).Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -98,21 +95,15 @@ public async Task Index(ContentOptions options, PagerParameters p Pager = pagerShape }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(MediaProfileIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(MediaProfileIndexViewModel model) => + RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Create() { @@ -356,7 +347,6 @@ private void BuildViewModel(MediaProfileViewModel model) model.AvailableResizeModes.Add(new SelectListItem() { Text = S["Min"], Value = ((int)ResizeMode.Min).ToString() }); model.AvailableResizeModes.Add(new SelectListItem() { Text = S["Stretch"], Value = ((int)ResizeMode.Stretch).ToString() }); - model.AvailableFormats.Add(new SelectListItem() { Text = S["Default"], Value = ((int)Format.Undefined).ToString() }); model.AvailableFormats.Add(new SelectListItem() { Text = S["Bmp"], Value = ((int)Format.Bmp).ToString() }); model.AvailableFormats.Add(new SelectListItem() { Text = S["Gif"], Value = ((int)Format.Gif).ToString() }); diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Deployment/AllMediaProfilesDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Media/Deployment/AllMediaProfilesDeploymentSource.cs index 6c88cdf7683..1c73b9a7c4b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Deployment/AllMediaProfilesDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Deployment/AllMediaProfilesDeploymentSource.cs @@ -25,11 +25,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan var mediaProfiles = await _mediaProfilesManager.GetMediaProfilesDocumentAsync(); - result.Steps.Add(new JsonObject - { - ["name"] = "MediaProfiles", - ["MediaProfiles"] = JObject.FromObject(mediaProfiles.MediaProfiles), - }); + result.Steps.Add(new JsonObject { ["name"] = "MediaProfiles", ["MediaProfiles"] = JObject.FromObject(mediaProfiles.MediaProfiles), }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Deployment/AllMediaProfilesDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Media/Deployment/AllMediaProfilesDeploymentStepDriver.cs index 847d358c302..4b7e649ef5e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Deployment/AllMediaProfilesDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Deployment/AllMediaProfilesDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class AllMediaProfilesDeploymentStepDriver : DisplayDriver("MediaDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.FilePaths = step.FilePaths; - model.DirectoryPaths = step.DirectoryPaths; - model.Entries = await GetMediaStoreEntries(); - }).Location("Content"); + return Initialize( + "MediaDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.FilePaths = step.FilePaths; + model.DirectoryPaths = step.DirectoryPaths; + model.Entries = await GetMediaStoreEntries(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(MediaDeploymentStep step, IUpdateModel updater) @@ -44,11 +47,7 @@ public override async Task UpdateAsync(MediaDeploymentStep step, step.FilePaths = []; step.DirectoryPaths = []; - await updater.TryUpdateModelAsync(step, - Prefix, - x => x.FilePaths, - x => x.DirectoryPaths, - x => x.IncludeAll); + await updater.TryUpdateModelAsync(step, Prefix, x => x.FilePaths, x => x.DirectoryPaths, x => x.IncludeAll); // don't have the selected option if include all if (step.IncludeAll) @@ -62,7 +61,8 @@ await updater.TryUpdateModelAsync(step, private async Task> GetMediaStoreEntries(string path = null, MediaStoreEntryViewModel parent = null) { - var mediaStoreEntries = await _mediaFileStore.GetDirectoryContentAsync(path) + var mediaStoreEntries = await _mediaFileStore + .GetDirectoryContentAsync(path) .SelectAwait(async e => { var mediaStoreEntry = new MediaStoreEntryViewModel @@ -72,12 +72,11 @@ private async Task> GetMediaStoreEntries(string Parent = parent }; - mediaStoreEntry.Entries = e.IsDirectory - ? await GetMediaStoreEntries(e.Path, mediaStoreEntry) - : Array.Empty(); + mediaStoreEntry.Entries = e.IsDirectory ? await GetMediaStoreEntries(e.Path, mediaStoreEntry) : Array.Empty(); return mediaStoreEntry; - }).ToListAsync(); + }) + .ToListAsync(); return mediaStoreEntries; } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Drivers/MediaFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Media/Drivers/MediaFieldDisplayDriver.cs index 54e575dd037..0f1ca31dc47 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Drivers/MediaFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Drivers/MediaFieldDisplayDriver.cs @@ -25,9 +25,11 @@ public class MediaFieldDisplayDriver : ContentFieldDisplayDriver protected readonly IStringLocalizer S; private readonly ILogger _logger; - public MediaFieldDisplayDriver(AttachedMediaFieldFileService attachedMediaFieldFileService, + public MediaFieldDisplayDriver( + AttachedMediaFieldFileService attachedMediaFieldFileService, IStringLocalizer localizer, - ILogger logger) + ILogger logger + ) { _attachedMediaFieldFileService = attachedMediaFieldFileService; S = localizer; @@ -36,55 +38,61 @@ public MediaFieldDisplayDriver(AttachedMediaFieldFileService attachedMediaFieldF public override IDisplayResult Display(MediaField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(MediaField field, BuildFieldEditorContext context) { var itemPaths = field.Paths?.ToList().Select(p => new EditMediaFieldItemInfo { Path = p }).ToArray() ?? []; - return Initialize(GetEditorShapeType(context), model => - { - var settings = context.PartFieldDefinition.GetSettings(); - - for (var i = 0; i < itemPaths.Length; i++) + return Initialize( + GetEditorShapeType(context), + model => { - if (settings.AllowMediaText && i < field.MediaTexts?.Length) - { - itemPaths[i].MediaText = field.MediaTexts[i]; - } + var settings = context.PartFieldDefinition.GetSettings(); - if (settings.AllowAnchors) + for (var i = 0; i < itemPaths.Length; i++) { - var anchors = field.GetAnchors(); - if (anchors != null && i < anchors.Length) + if (settings.AllowMediaText && i < field.MediaTexts?.Length) { - itemPaths[i].Anchor = anchors[i]; + itemPaths[i].MediaText = field.MediaTexts[i]; } - } - var filenames = field.GetAttachedFileNames(); - if (filenames != null && i < filenames.Length) - { - itemPaths[i].AttachedFileName = filenames[i]; + if (settings.AllowAnchors) + { + var anchors = field.GetAnchors(); + if (anchors != null && i < anchors.Length) + { + itemPaths[i].Anchor = anchors[i]; + } + } + + var filenames = field.GetAttachedFileNames(); + if (filenames != null && i < filenames.Length) + { + itemPaths[i].AttachedFileName = filenames[i]; + } } - } - model.Paths = JConvert.SerializeObject(itemPaths, JOptions.CamelCase); - model.TempUploadFolder = _attachedMediaFieldFileService.MediaFieldsTempSubFolder; - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - model.AllowMediaText = settings.AllowMediaText; - model.AllowedExtensions = settings.AllowedExtensions ?? []; - }); + model.Paths = JConvert.SerializeObject(itemPaths, JOptions.CamelCase); + model.TempUploadFolder = _attachedMediaFieldFileService.MediaFieldsTempSubFolder; + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + model.AllowMediaText = settings.AllowMediaText; + model.AllowedExtensions = settings.AllowedExtensions ?? []; + } + ); } public override async Task UpdateAsync(MediaField field, IUpdateModel updater, UpdateFieldEditorContext context) @@ -94,9 +102,7 @@ public override async Task UpdateAsync(MediaField field, IUpdate if (await updater.TryUpdateModelAsync(model, Prefix, f => f.Paths)) { // Deserializing an empty string doesn't return an array - var items = string.IsNullOrWhiteSpace(model.Paths) - ? [] - : JConvert.DeserializeObject>(model.Paths, JOptions.CamelCase); + var items = string.IsNullOrWhiteSpace(model.Paths) ? [] : JConvert.DeserializeObject>(model.Paths, JOptions.CamelCase); // If it's an attached media field editor the files are automatically handled by _attachedMediaFieldFileService. if (string.Equals(context.PartFieldDefinition.Editor(), "Attached", StringComparison.OrdinalIgnoreCase)) @@ -125,7 +131,11 @@ public override async Task UpdateAsync(MediaField field, IUpdate if (!settings.AllowedExtensions.Contains(extension)) { - updater.ModelState.AddModelError(Prefix, nameof(model.Paths), S["Media extension is not allowed. Only media with '{0}' extensions are allowed.", string.Join(", ", settings.AllowedExtensions)]); + updater.ModelState.AddModelError( + Prefix, + nameof(model.Paths), + S["Media extension is not allowed. Only media with '{0}' extensions are allowed.", string.Join(", ", settings.AllowedExtensions)] + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Fields/MediaFieldAnchorExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Media/Fields/MediaFieldAnchorExtensions.cs index 2a35ce75c30..9614051e3a2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Fields/MediaFieldAnchorExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Fields/MediaFieldAnchorExtensions.cs @@ -21,6 +21,5 @@ public static void SetAnchors(this MediaField mediaField, Anchor[] anchors) { mediaField.Content["Anchors"] = JArray.FromObject(anchors); } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Fields/MediaFieldAttachedFileNameExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Media/Fields/MediaFieldAttachedFileNameExtensions.cs index 623368b566e..73d398aed8b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Fields/MediaFieldAttachedFileNameExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Fields/MediaFieldAttachedFileNameExtensions.cs @@ -11,9 +11,7 @@ public static string[] GetAttachedFileNames(this MediaField mediaField) { var filenames = (JsonArray)mediaField.Content["AttachedFileNames"]; - return filenames != null - ? filenames.ToObject() - : []; + return filenames != null ? filenames.ToObject() : []; } /// @@ -23,6 +21,5 @@ public static void SetAttachedFileNames(this MediaField mediaField, string[] fil { mediaField.Content["AttachedFileNames"] = JArray.FromObject(filenames); } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Filters/ResizeUrlFilter.cs b/src/OrchardCore.Modules/OrchardCore.Media/Filters/ResizeUrlFilter.cs index 210aaff6cc4..53a297e6b31 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Filters/ResizeUrlFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Filters/ResizeUrlFilter.cs @@ -70,7 +70,6 @@ public async ValueTask ProcessAsync(FluidValue input, FilterArgument var resizedUrl = QueryHelpers.AddQueryString(url, queryStringParams); - if (_options.UseTokenizedQueryString) { resizedUrl = _mediaTokenService.AddTokenToPath(resizedUrl); @@ -79,7 +78,16 @@ public async ValueTask ProcessAsync(FluidValue input, FilterArgument return new StringValue(resizedUrl); } - private static void ApplyQueryStringParams(IDictionary queryStringParams, FluidValue width, FluidValue height, FluidValue mode, FluidValue quality, FluidValue format, FluidValue anchorValue, FluidValue bgcolor) + private static void ApplyQueryStringParams( + IDictionary queryStringParams, + FluidValue width, + FluidValue height, + FluidValue mode, + FluidValue quality, + FluidValue format, + FluidValue anchorValue, + FluidValue bgcolor + ) { if (!width.IsNil()) { diff --git a/src/OrchardCore.Modules/OrchardCore.Media/GraphQL/MediaAssetObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Media/GraphQL/MediaAssetObjectType.cs index 467c5478e47..0406c4bf396 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/GraphQL/MediaAssetObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/GraphQL/MediaAssetObjectType.cs @@ -22,9 +22,7 @@ public MediaAssetObjectType() }); Field(file => file.Length).Description("The length of the file."); - Field("lastModifiedUtc") - .Description("The date and time in UTC when the asset was last modified.") - .Resolve(file => file.Source.LastModifiedUtc); + Field("lastModifiedUtc").Description("The date and time in UTC when the asset was last modified.").Resolve(file => file.Source.LastModifiedUtc); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/GraphQL/MediaAssetQuery.cs b/src/OrchardCore.Modules/OrchardCore.Media/GraphQL/MediaAssetQuery.cs index 0880bed5c83..544f2dc2cde 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/GraphQL/MediaAssetQuery.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/GraphQL/MediaAssetQuery.cs @@ -18,9 +18,7 @@ public class MediaAssetQuery : ISchemaBuilder protected readonly IStringLocalizer S; private readonly GraphQLContentOptions _graphQLContentOptions; - public MediaAssetQuery( - IStringLocalizer localizer, - IOptions graphQLContentOptions) + public MediaAssetQuery(IStringLocalizer localizer, IOptions graphQLContentOptions) { S = localizer; _graphQLContentOptions = graphQLContentOptions.Value; @@ -41,11 +39,7 @@ public Task BuildAsync(ISchema schema) Description = S["Media assets are items that are part of your media library."], Type = typeof(ListGraphType), Arguments = new QueryArguments( - new QueryArgument - { - Name = "path", - Description = S["Media asset path."] - }, + new QueryArgument { Name = "path", Description = S["Media asset path."] }, new QueryArgument { Name = "includeSubDirectories", diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Indexing/MediaFieldIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Media/Indexing/MediaFieldIndexHandler.cs index 37859eee99c..736cf6c15d9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Indexing/MediaFieldIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Indexing/MediaFieldIndexHandler.cs @@ -20,17 +20,14 @@ public class MediaFieldIndexHandler : ContentFieldIndexHandler private readonly MediaFileIndexingOptions _mediaFileIndexingOptions; private readonly IServiceProvider _serviceProvider; - public MediaFieldIndexHandler( - IMediaFileStore mediaFileStore, - IOptions mediaFileIndexingOptions, - IServiceProvider serviceProvider) + public MediaFieldIndexHandler(IMediaFileStore mediaFileStore, IOptions mediaFileIndexingOptions, IServiceProvider serviceProvider) { _mediaFileStore = mediaFileStore; _mediaFileIndexingOptions = mediaFileIndexingOptions.Value; _serviceProvider = serviceProvider; } - public async override Task BuildIndexAsync(MediaField field, BuildFieldIndexContext context) + public override async Task BuildIndexAsync(MediaField field, BuildFieldIndexContext context) { var options = context.Settings.ToOptions(); var settings = context.ContentPartFieldDefinition.GetSettings(); @@ -89,8 +86,7 @@ public async override Task BuildIndexAsync(MediaField field, BuildFieldIndexCont continue; } - var fileText = await _serviceProvider.CreateInstance(providerType) - .GetTextAsync(path, fileStream); + var fileText = await _serviceProvider.CreateInstance(providerType).GetTextAsync(path, fileStream); foreach (var key in context.Keys) { diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Liquid/MediaAnchorTag.cs b/src/OrchardCore.Modules/OrchardCore.Media/Liquid/MediaAnchorTag.cs index 4944592094c..45535e184fd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Liquid/MediaAnchorTag.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Liquid/MediaAnchorTag.cs @@ -23,14 +23,21 @@ public bool Match(List argumentsList) { switch (argument.Name) { - case "asset-href": return true; + case "asset-href": + return true; } } return false; } - public async ValueTask WriteToAsync(List argumentsList, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, LiquidTemplateContext context) + public async ValueTask WriteToAsync( + List argumentsList, + IReadOnlyList statements, + TextWriter writer, + TextEncoder encoder, + LiquidTemplateContext context + ) { var services = context.Services; var mediaFileStore = services.GetRequiredService(); @@ -46,8 +53,12 @@ public async ValueTask WriteToAsync(List argumentsLi { switch (argument.Name) { - case "asset_href": assetHref = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "append_version": appendVersion = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "asset_href": + assetHref = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "append_version": + appendVersion = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; default: diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Media/Manifest.cs index a38b240905e..b1cbfd044cf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Manifest.cs @@ -1,20 +1,12 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Media", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Media", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Media", Name = "Media", Description = "The media module adds media management support.", - Dependencies = - [ - "OrchardCore.ContentTypes" - ], + Dependencies = ["OrchardCore.ContentTypes"], Category = "Content Management" )] @@ -22,10 +14,7 @@ Id = "OrchardCore.Media.Indexing", Name = "Media Indexing", Description = "Provides a way to index media files with common format in search providers.", - Dependencies = - [ - "OrchardCore.Media" - ], + Dependencies = ["OrchardCore.Media"], Category = "Search", EnabledByDependencyOnly = true )] @@ -34,10 +23,7 @@ Id = "OrchardCore.Media.Indexing.Text", Name = "Text Media Indexing", Description = "Provides a way to index common text files like (.txt and .md) in search providers.", - Dependencies = - [ - "OrchardCore.Media.Indexing" - ], + Dependencies = ["OrchardCore.Media.Indexing"], Category = "Search" )] @@ -45,10 +31,7 @@ Id = "OrchardCore.Media.Cache", Name = "Media Cache", Description = "The media cache module adds remote file store cache support.", - Dependencies = - [ - "OrchardCore.Media" - ], + Dependencies = ["OrchardCore.Media"], Category = "Content Management" )] @@ -56,9 +39,6 @@ Id = "OrchardCore.Media.Slugify", Name = "Media Slugify", Description = "The media slugify module transforms newly created folders and files into SEO-friendly versions by generating slugs.", - Dependencies = - [ - "OrchardCore.Media" - ], + Dependencies = ["OrchardCore.Media"], Category = "Content Management" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Media/MediaCachePermissions.cs b/src/OrchardCore.Modules/OrchardCore.Media/MediaCachePermissions.cs index 2a01e042761..2306c9d88d8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/MediaCachePermissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/MediaCachePermissions.cs @@ -8,20 +8,9 @@ public class MediaCachePermissions : IPermissionProvider { public static readonly Permission ManageAssetCache = new("ManageAssetCache", "Manage Asset Cache Folder"); - private readonly IEnumerable _allPermissions = - [ - ManageAssetCache, - ]; + private readonly IEnumerable _allPermissions = [ManageAssetCache,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Media/Permissions.cs index b41e2877360..6383074869e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Permissions.cs @@ -25,44 +25,15 @@ public class Permissions : IPermissionProvider ViewMediaOptions, ]; - private readonly IEnumerable _generalPermissions = - [ - ManageOwnMedia, - ]; + private readonly IEnumerable _generalPermissions = [ManageOwnMedia,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = - [ - ManageMediaFolder, - ManageMediaProfiles, - ViewMediaOptions, - ], - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = - [ - ManageMedia, - ManageOwnMedia, - ], - }, - new PermissionStereotype - { - Name = "Author", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Contributor", - Permissions = _generalPermissions, - }, - ]; + [ + new PermissionStereotype { Name = "Administrator", Permissions = [ManageMediaFolder, ManageMediaProfiles, ViewMediaOptions,], }, + new PermissionStereotype { Name = "Editor", Permissions = [ManageMedia, ManageOwnMedia,], }, + new PermissionStereotype { Name = "Author", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Contributor", Permissions = _generalPermissions, }, + ]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Processing/BackwardsCompatibleCacheKey.cs b/src/OrchardCore.Modules/OrchardCore.Media/Processing/BackwardsCompatibleCacheKey.cs index 7ab6c0e45e6..5e4ede65895 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Processing/BackwardsCompatibleCacheKey.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Processing/BackwardsCompatibleCacheKey.cs @@ -13,7 +13,6 @@ public class BackwardsCompatibleCacheKey : ICacheKey /// public string Create(HttpContext context, CommandCollection commands) { - var pathBase = context.Request.PathBase; if (pathBase.HasValue) { @@ -27,7 +26,13 @@ public string Create(HttpContext context, CommandCollection commands) pathBase = new PathString(pathBase + "//"); } - return CaseHandlingUriBuilder.BuildAbsolute(CaseHandlingUriBuilder.CaseHandling.LowerInvariant, context.Request.Host, pathBase, context.Request.Path, QueryString.Create(commands)); + return CaseHandlingUriBuilder.BuildAbsolute( + CaseHandlingUriBuilder.CaseHandling.LowerInvariant, + context.Request.Host, + pathBase, + context.Request.Path, + QueryString.Create(commands) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Processing/ImageSharpUrlFormatter.cs b/src/OrchardCore.Modules/OrchardCore.Media/Processing/ImageSharpUrlFormatter.cs index 6edffe6614a..fa9c4554bb5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Processing/ImageSharpUrlFormatter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Processing/ImageSharpUrlFormatter.cs @@ -29,7 +29,17 @@ public enum Format internal class ImageSharpUrlFormatter { - public static string GetImageResizeUrl(string path, IDictionary queryStringParams = null, int? width = null, int? height = null, ResizeMode resizeMode = ResizeMode.Undefined, int? quality = null, Format format = Format.Undefined, Anchor anchor = null, string bgcolor = null) + public static string GetImageResizeUrl( + string path, + IDictionary queryStringParams = null, + int? width = null, + int? height = null, + ResizeMode resizeMode = ResizeMode.Undefined, + int? quality = null, + Format format = Format.Undefined, + Anchor anchor = null, + string bgcolor = null + ) { if (string.IsNullOrEmpty(path) || (!width.HasValue && !height.HasValue && queryStringParams == null)) { @@ -53,7 +63,7 @@ public static string GetImageResizeUrl(string path, IDictionary queryStringParams["rmode"] = resizeMode.ToString().ToLower(); } - // The format is set before quality such that the quality is not + // The format is set before quality such that the quality is not // invalidated when the url is generated. if (format != Format.Undefined) { diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Processing/ImageVersionProcessor.cs b/src/OrchardCore.Modules/OrchardCore.Media/Processing/ImageVersionProcessor.cs index 6b939abbf81..f723720c59e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Processing/ImageVersionProcessor.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Processing/ImageVersionProcessor.cs @@ -21,10 +21,8 @@ public class ImageVersionProcessor : IImageWebProcessor public IEnumerable Commands => _versionCommands; - public FormattedImage Process(FormattedImage image, ILogger logger, CommandCollection commands, CommandParser parser, CultureInfo culture) - => image; + public FormattedImage Process(FormattedImage image, ILogger logger, CommandCollection commands, CommandParser parser, CultureInfo culture) => image; - public bool RequiresTrueColorPixelFormat(CommandCollection commands, CommandParser parser, CultureInfo culture) - => false; + public bool RequiresTrueColorPixelFormat(CommandCollection commands, CommandParser parser, CultureInfo culture) => false; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaResizingFileProvider.cs b/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaResizingFileProvider.cs index 1d0eba6f35d..158c08d4876 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaResizingFileProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaResizingFileProvider.cs @@ -22,11 +22,7 @@ public class MediaResizingFileProvider : IImageProvider /// private Func _match; - public MediaResizingFileProvider( - IMediaFileProvider mediaFileProvider, - IOptions imageSharpOptions, - IOptions mediaOptions - ) + public MediaResizingFileProvider(IMediaFileProvider mediaFileProvider, IOptions imageSharpOptions, IOptions mediaOptions) { _mediaFileProvider = mediaFileProvider; _formatUtilities = new FormatUtilities(imageSharpOptions); @@ -43,8 +39,7 @@ public Func Match public ProcessingBehavior ProcessingBehavior => ProcessingBehavior.CommandOnly; /// - public bool IsValidRequest(HttpContext context) - => _formatUtilities.TryGetExtensionFromUri(context.Request.GetDisplayUrl(), out _); + public bool IsValidRequest(HttpContext context) => _formatUtilities.TryGetExtensionFromUri(context.Request.GetDisplayUrl(), out _); /// public Task GetAsync(HttpContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenOptionsConfiguration.cs index 19302b3b138..88630ab5e4a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenOptionsConfiguration.cs @@ -14,10 +14,7 @@ public MediaTokenOptionsConfiguration(ISiteService siteService) public void Configure(MediaTokenOptions options) { - options.HashKey = _siteService.GetSiteSettingsAsync() - .GetAwaiter().GetResult() - .As() - .HashKey; + options.HashKey = _siteService.GetSiteSettingsAsync().GetAwaiter().GetResult().As().HashKey; } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenService.cs b/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenService.cs index 0d37c51b804..047e5d78819 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenService.cs @@ -21,10 +21,7 @@ public class MediaTokenService : IMediaTokenService private readonly HashSet _knownCommands = new(12); private readonly byte[] _hashKey; - public MediaTokenService( - IMemoryCache memoryCache, - IOptions options, - IEnumerable processors) + public MediaTokenService(IMemoryCache memoryCache, IOptions options, IEnumerable processors) { _memoryCache = memoryCache; @@ -52,9 +49,11 @@ public string AddTokenToPath(string path) } // If no commands or only a version command don't bother tokenizing. - if (processingCommands is null + if ( + processingCommands is null || processingCommands.Count == 0 - || processingCommands.Count == 1 && processingCommands.ContainsKey(ImageVersionProcessor.VersionCommand)) + || processingCommands.Count == 1 && processingCommands.ContainsKey(ImageVersionProcessor.VersionCommand) + ) { return path; } @@ -77,10 +76,7 @@ public string AddTokenToPath(string path) return AddQueryString(path.AsSpan(0, pathIndex), processingCommands); } - private void ParseQuery( - string queryString, - out Dictionary processingCommands, - out Dictionary otherCommands) + private void ParseQuery(string queryString, out Dictionary processingCommands, out Dictionary otherCommands) { processingCommands = null; otherCommands = null; @@ -172,9 +168,7 @@ private string GetHash(string queryStringTokenKey) // Only allocate on stack if it's small enough. var requiredLength = Encoding.UTF8.GetByteCount(chars); - var stringBytes = requiredLength < 1024 - ? stackalloc byte[requiredLength] - : new byte[requiredLength]; + var stringBytes = requiredLength < 1024 ? stackalloc byte[requiredLength] : new byte[requiredLength]; // 256 for SHA-256, fits in stack nicely. Span hashBytes = stackalloc byte[hmac.HashSize]; @@ -193,9 +187,7 @@ private string GetHash(string queryStringTokenKey) /// Custom version of that takes our pre-built /// dictionary, uri as ReadOnlySpan<char> and uses ZString. Otherwise same logic. /// - private static string AddQueryString( - ReadOnlySpan uri, - Dictionary queryString) + private static string AddQueryString(ReadOnlySpan uri, Dictionary queryString) { var anchorIndex = uri.IndexOf('#'); var uriToBeAppended = uri; diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenSettingsUpdater.cs b/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenSettingsUpdater.cs index 22dfe2ea6b2..05b86d17096 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenSettingsUpdater.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Processing/MediaTokenSettingsUpdater.cs @@ -49,8 +49,11 @@ public async Task ActivatedAsync() } public Task ActivatingAsync() => Task.CompletedTask; + public Task RemovingAsync(ShellRemovingContext context) => Task.CompletedTask; + public Task TerminatedAsync() => Task.CompletedTask; + public Task TerminatingAsync() => Task.CompletedTask; public override Task EnabledAsync(IFeatureInfo feature) => SetMediaTokenSettingsAsync(feature); diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Processing/TokenCommandProcessor.cs b/src/OrchardCore.Modules/OrchardCore.Media/Processing/TokenCommandProcessor.cs index 62139dfa808..19580670759 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Processing/TokenCommandProcessor.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Processing/TokenCommandProcessor.cs @@ -19,13 +19,10 @@ public class TokenCommandProcessor : IImageWebProcessor private static readonly IEnumerable _tokenCommands = new[] { TokenCommand }; - public IEnumerable Commands - => _tokenCommands; + public IEnumerable Commands => _tokenCommands; - public FormattedImage Process(FormattedImage image, ILogger logger, CommandCollection commands, CommandParser parser, CultureInfo culture) - => image; + public FormattedImage Process(FormattedImage image, ILogger logger, CommandCollection commands, CommandParser parser, CultureInfo culture) => image; - public bool RequiresTrueColorPixelFormat(CommandCollection commands, CommandParser parser, CultureInfo culture) - => false; + public bool RequiresTrueColorPixelFormat(CommandCollection commands, CommandParser parser, CultureInfo culture) => false; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Razor/OrchardRazorHelperExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Media/Razor/OrchardRazorHelperExtensions.cs index a0946cbd0aa..29498a3cdb0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Razor/OrchardRazorHelperExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Razor/OrchardRazorHelperExtensions.cs @@ -15,7 +15,18 @@ public static class OrchardRazorHelperExtensions /// /// Returns the relative URL of the specified asset path with optional resizing parameters. /// - public static string AssetUrl(this IOrchardHelper orchardHelper, string assetPath, int? width = null, int? height = null, ResizeMode resizeMode = ResizeMode.Undefined, bool appendVersion = false, int? quality = null, Format format = Format.Undefined, Anchor anchor = null, string bgcolor = null) + public static string AssetUrl( + this IOrchardHelper orchardHelper, + string assetPath, + int? width = null, + int? height = null, + ResizeMode resizeMode = ResizeMode.Undefined, + bool appendVersion = false, + int? quality = null, + Format format = Format.Undefined, + Anchor anchor = null, + string bgcolor = null + ) { var mediaFileStore = orchardHelper.HttpContext.RequestServices.GetService(); @@ -39,7 +50,19 @@ public static string AssetUrl(this IOrchardHelper orchardHelper, string assetPat /// /// Returns the relative URL of the specified asset path for a media profile with optional resizing parameters. /// - public static Task AssetProfileUrlAsync(this IOrchardHelper orchardHelper, string assetPath, string imageProfile, int? width = null, int? height = null, ResizeMode resizeMode = ResizeMode.Undefined, bool appendVersion = false, int? quality = null, Format format = Format.Undefined, Anchor anchor = null, string bgcolor = null) + public static Task AssetProfileUrlAsync( + this IOrchardHelper orchardHelper, + string assetPath, + string imageProfile, + int? width = null, + int? height = null, + ResizeMode resizeMode = ResizeMode.Undefined, + bool appendVersion = false, + int? quality = null, + Format format = Format.Undefined, + Anchor anchor = null, + string bgcolor = null + ) { var mediaFileStore = orchardHelper.HttpContext.RequestServices.GetService(); @@ -63,7 +86,17 @@ public static Task AssetProfileUrlAsync(this IOrchardHelper orchardHelpe /// /// Returns a URL with custom resizing parameters for an existing image path. /// - public static string ImageResizeUrl(this IOrchardHelper orchardHelper, string imagePath, int? width = null, int? height = null, ResizeMode resizeMode = ResizeMode.Undefined, int? quality = null, Format format = Format.Undefined, Anchor anchor = null, string bgcolor = null) + public static string ImageResizeUrl( + this IOrchardHelper orchardHelper, + string imagePath, + int? width = null, + int? height = null, + ResizeMode resizeMode = ResizeMode.Undefined, + int? quality = null, + Format format = Format.Undefined, + Anchor anchor = null, + string bgcolor = null + ) { var resizedUrl = ImageSharpUrlFormatter.GetImageResizeUrl(imagePath, null, width, height, resizeMode, quality, format, anchor, bgcolor); @@ -73,7 +106,18 @@ public static string ImageResizeUrl(this IOrchardHelper orchardHelper, string im /// /// Returns a URL with custom resizing parameters for a media profile for an existing image path. /// - public static async Task ImageProfileResizeUrlAsync(this IOrchardHelper orchardHelper, string imagePath, string imageProfile, int? width = null, int? height = null, ResizeMode resizeMode = ResizeMode.Undefined, int? quality = null, Format format = Format.Undefined, Anchor anchor = null, string bgcolor = null) + public static async Task ImageProfileResizeUrlAsync( + this IOrchardHelper orchardHelper, + string imagePath, + string imageProfile, + int? width = null, + int? height = null, + ResizeMode resizeMode = ResizeMode.Undefined, + int? quality = null, + Format format = Format.Undefined, + Anchor anchor = null, + string bgcolor = null + ) { var mediaProfileService = orchardHelper.HttpContext.RequestServices.GetRequiredService(); var queryStringParams = await mediaProfileService.GetMediaProfileCommands(imageProfile); diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Recipes/MediaStep.cs b/src/OrchardCore.Modules/OrchardCore.Media/Recipes/MediaStep.cs index e6d5b5407f5..8dcd1452274 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Recipes/MediaStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Recipes/MediaStep.cs @@ -23,11 +23,7 @@ public class MediaStep : IRecipeStepHandler private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; - public MediaStep( - IMediaFileStore mediaFileStore, - IOptions options, - IHttpClientFactory httpClientFactory, - ILogger logger) + public MediaStep(IMediaFileStore mediaFileStore, IOptions options, IHttpClientFactory httpClientFactory, ILogger logger) { _mediaFileStore = mediaFileStore; _allowedFileExtensions = options.Value.AllowedFileExtensions; @@ -105,7 +101,11 @@ private class MediaStepFile /// Path where the content will be written. /// Use inter-changeably with . /// - public string Path { get => TargetPath; set => TargetPath = value; } + public string Path + { + get => TargetPath; + set => TargetPath = value; + } /// /// Path where the content will be written. diff --git a/src/OrchardCore.Modules/OrchardCore.Media/ResourceManifestOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Media/ResourceManifestOptionsConfiguration.cs index eae94c79189..ed866e9530b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/ResourceManifestOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/ResourceManifestOptionsConfiguration.cs @@ -17,11 +17,7 @@ static ResourceManagementOptionsConfiguration() .SetDependencies("vuejs", "sortable", "vuedraggable", "jQuery-ui") .SetVersion("1.0.0"); - _manifest - .DefineStyle("media") - .SetUrl("~/OrchardCore.Media/Styles/media.min.css", "~/OrchardCore.Media/Styles/media.css") - .SetVersion("1.0.0"); - + _manifest.DefineStyle("media").SetUrl("~/OrchardCore.Media/Styles/media.min.css", "~/OrchardCore.Media/Styles/media.css").SetVersion("1.0.0"); } public void Configure(ResourceManagementOptions options) diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/AttachedMediaFieldFileService.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/AttachedMediaFieldFileService.cs index 9ba785eb228..f51611cb6c0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/AttachedMediaFieldFileService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/AttachedMediaFieldFileService.cs @@ -22,10 +22,7 @@ public class AttachedMediaFieldFileService private readonly IHttpContextAccessor _httpContextAccessor; private readonly ILogger _logger; - public AttachedMediaFieldFileService( - IMediaFileStore fileStore, - IHttpContextAccessor httpContextAccessor, - ILogger logger) + public AttachedMediaFieldFileService(IMediaFileStore fileStore, IHttpContextAccessor httpContextAccessor, ILogger logger) { _fileStore = fileStore; _httpContextAccessor = httpContextAccessor; diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/ChunkFileUploadBackgroundTask.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/ChunkFileUploadBackgroundTask.cs index dc1e589e9a8..415c9b0a484 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/ChunkFileUploadBackgroundTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/ChunkFileUploadBackgroundTask.cs @@ -10,8 +10,7 @@ public class ChunkFileUploadBackgroundTask : IBackgroundTask { private readonly IChunkFileUploadService _chunkFileUploadService; - public ChunkFileUploadBackgroundTask(IChunkFileUploadService chunkFileUploadService) => - _chunkFileUploadService = chunkFileUploadService; + public ChunkFileUploadBackgroundTask(IChunkFileUploadService chunkFileUploadService) => _chunkFileUploadService = chunkFileUploadService; public Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken) { diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/ChunkFileUploadService.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/ChunkFileUploadService.cs index 2a92961dabb..eadf3eaddfa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/ChunkFileUploadService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/ChunkFileUploadService.cs @@ -25,11 +25,7 @@ public class ChunkFileUploadService : IChunkFileUploadService private readonly IOptions _options; private readonly string _tempFileNamePrefix; - public ChunkFileUploadService( - ShellSettings shellSettings, - IClock clock, - ILogger logger, - IOptions options) + public ChunkFileUploadService(ShellSettings shellSettings, IClock clock, ILogger logger, IOptions options) { _clock = clock; _logger = logger; @@ -41,33 +37,31 @@ public ChunkFileUploadService( public async Task ProcessRequestAsync( HttpRequest request, Func> chunkAsync, - Func, Task> completedAsync) + Func, Task> completedAsync + ) { var contentRangeHeader = request.Headers.ContentRange; - if (_options.Value.MaxUploadChunkSize <= 0 || - contentRangeHeader.Count is 0 || - !request.Form.TryGetValue(UploadIdFormKey, out var uploadIdValue)) + if (_options.Value.MaxUploadChunkSize <= 0 || contentRangeHeader.Count is 0 || !request.Form.TryGetValue(UploadIdFormKey, out var uploadIdValue)) { return await completedAsync(request.Form.Files); } - if (request.Form.Files.Count != 1 || - !ContentRangeHeaderValue.TryParse(contentRangeHeader, out var contentRange) || - !Guid.TryParse(uploadIdValue, out var uploadId) || - !contentRange.HasLength || - !contentRange.HasRange || - contentRange.Length > _options.Value.MaxFileSize || - contentRange.To - contentRange.From > _options.Value.MaxUploadChunkSize) + if ( + request.Form.Files.Count != 1 + || !ContentRangeHeaderValue.TryParse(contentRangeHeader, out var contentRange) + || !Guid.TryParse(uploadIdValue, out var uploadId) + || !contentRange.HasLength + || !contentRange.HasRange + || contentRange.Length > _options.Value.MaxFileSize + || contentRange.To - contentRange.From > _options.Value.MaxUploadChunkSize + ) { return new BadRequestResult(); } var formFile = request.Form.Files[0]; - using (var fileStream = GetOrCreateTemporaryFile( - uploadId, - formFile, - contentRange.Length.Value)) + using (var fileStream = GetOrCreateTemporaryFile(uploadId, formFile, contentRange.Length.Value)) { fileStream.Seek(contentRange.From.Value, SeekOrigin.Begin); await formFile.CopyToAsync(fileStream, request.HttpContext.RequestAborted); @@ -78,10 +72,7 @@ contentRangeHeader.Count is 0 || : await chunkAsync(uploadId, formFile, contentRange); } - private async Task CompleteUploadAsync( - Guid uploadId, - IFormFile formFile, - Func, Task> completedAsync) + private async Task CompleteUploadAsync(Guid uploadId, IFormFile formFile, Func, Task> completedAsync) { try { @@ -98,13 +89,13 @@ private async Task CompleteUploadAsync( public void PurgeTempDirectory() { var tempFolderPath = GetTempFolderPath(); - if (_options.Value.TemporaryFileLifetime <= TimeSpan.Zero || - !Directory.Exists(tempFolderPath)) + if (_options.Value.TemporaryFileLifetime <= TimeSpan.Zero || !Directory.Exists(tempFolderPath)) { return; } - var tempFiles = Directory.GetFiles(tempFolderPath, $"{_tempFileNamePrefix}*") + var tempFiles = Directory + .GetFiles(tempFolderPath, $"{_tempFileNamePrefix}*") .Select(filePath => new FileInfo(filePath)) .Where(fileInfo => fileInfo.LastWriteTimeUtc + _options.Value.TemporaryFileLifetime < _clock.UtcNow) .ToArray(); @@ -118,8 +109,7 @@ public void PurgeTempDirectory() } } - private bool DeleteTemporaryFile(Guid uploadId, IFormFile formFile) => - DeleteTemporaryFile(GetTempFilePath(uploadId, formFile)); + private bool DeleteTemporaryFile(Guid uploadId, IFormFile formFile) => DeleteTemporaryFile(GetTempFilePath(uploadId, formFile)); private bool DeleteTemporaryFile(string tempFilePath) { @@ -131,17 +121,11 @@ private bool DeleteTemporaryFile(string tempFilePath) } catch (Exception exception) when (exception.IsFileSharingViolation()) { - _logger.LogError( - exception, - "Sharing violation while deleting the temporary file '{TempFilePath}'.", - tempFilePath); + _logger.LogError(exception, "Sharing violation while deleting the temporary file '{TempFilePath}'.", tempFilePath); } catch (Exception exception) { - _logger.LogError( - exception, - "An error occurred while deleting the temporary file '{TempFilePath}'.", - tempFilePath); + _logger.LogError(exception, "An error occurred while deleting the temporary file '{TempFilePath}'.", tempFilePath); } return false; @@ -179,13 +163,10 @@ private ChunkedFormFile GetTemporaryFileForRead(Guid uploadId, IFormFile formFil }; } - private static string GetTempFolderPath() => - Path.Combine(Path.GetTempPath(), TempFolderPrefix); + private static string GetTempFolderPath() => Path.Combine(Path.GetTempPath(), TempFolderPrefix); private string GetTempFilePath(Guid uploadId, IFormFile formFile) => - Path.Combine( - GetTempFolderPath(), - $"{_tempFileNamePrefix}{CalculateHash(uploadId.ToString(), formFile.FileName, formFile.Name)}"); + Path.Combine(GetTempFolderPath(), $"{_tempFileNamePrefix}{CalculateHash(uploadId.ToString(), formFile.FileName, formFile.Name)}"); private static FileStream CreateTemporaryFile(string tempPath, long size) { @@ -222,17 +203,13 @@ private sealed class ChunkedFormFile : IFormFile, IDisposable public string FileName { get; set; } - public ChunkedFormFile(Stream stream) => - _stream = stream; + public ChunkedFormFile(Stream stream) => _stream = stream; - public void CopyTo(Stream target) => - _stream.CopyTo(target); + public void CopyTo(Stream target) => _stream.CopyTo(target); - public Task CopyToAsync(Stream target, CancellationToken cancellationToken = default) => - _stream.CopyToAsync(target, cancellationToken); + public Task CopyToAsync(Stream target, CancellationToken cancellationToken = default) => _stream.CopyToAsync(target, cancellationToken); - public Stream OpenReadStream() => - _stream; + public Stream OpenReadStream() => _stream; public void Dispose() { diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/ManageMediaFolderAuthorizationHandler.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/ManageMediaFolderAuthorizationHandler.cs index dfd98c889e2..ada7d379c5a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/ManageMediaFolderAuthorizationHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/ManageMediaFolderAuthorizationHandler.cs @@ -22,11 +22,13 @@ public class ManageMediaFolderAuthorizationHandler : AuthorizationHandler options, - IUserAssetFolderNameProvider userAssetFolderNameProvider) + IUserAssetFolderNameProvider userAssetFolderNameProvider + ) { _serviceProvider = serviceProvider; _attachedMediaFieldFileService = attachedMediaFieldFileService; @@ -56,17 +58,15 @@ protected override async Task HandleRequirementAsync(AuthorizationHandlerContext _pathSeparator = _fileStore.Combine("a", "b").Contains('/') ? '/' : '\\'; // ensure end trailing slash - _mediaFieldsFolder = _fileStore.NormalizePath(_attachedMediaFieldFileService.MediaFieldsFolder) - .TrimEnd(_pathSeparator) + _pathSeparator; + _mediaFieldsFolder = _fileStore.NormalizePath(_attachedMediaFieldFileService.MediaFieldsFolder).TrimEnd(_pathSeparator) + _pathSeparator; - _usersFolder = _fileStore.NormalizePath(_mediaOptions.AssetsUsersFolder) - .TrimEnd(_pathSeparator) + _pathSeparator; + _usersFolder = _fileStore.NormalizePath(_mediaOptions.AssetsUsersFolder).TrimEnd(_pathSeparator) + _pathSeparator; var path = context.Resource as string; - var userOwnFolder = _fileStore.NormalizePath( - _fileStore.Combine(_usersFolder, _userAssetFolderNameProvider.GetUserAssetFolderName(context.User))) - .TrimEnd(_pathSeparator) + _pathSeparator; + var userOwnFolder = + _fileStore.NormalizePath(_fileStore.Combine(_usersFolder, _userAssetFolderNameProvider.GetUserAssetFolderName(context.User))).TrimEnd(_pathSeparator) + + _pathSeparator; var permission = Permissions.ManageMedia; @@ -98,8 +98,7 @@ protected override async Task HandleRequirementAsync(AuthorizationHandlerContext private bool IsAuthorizedFolder(string authorizedFolder, string childPath) { // Ensure end trailing slash. - childPath = _fileStore.NormalizePath(childPath) - .TrimEnd(_pathSeparator) + _pathSeparator; + childPath = _fileStore.NormalizePath(childPath).TrimEnd(_pathSeparator) + _pathSeparator; return childPath.Equals(authorizedFolder); } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaFileProvider.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaFileProvider.cs index e21a7847d7a..46ba81e1a62 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaFileProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaFileProvider.cs @@ -6,12 +6,14 @@ namespace OrchardCore.Media.Services { public class MediaFileProvider : PhysicalFileProvider, IMediaFileProvider { - public MediaFileProvider(PathString virtualPathBase, string root) : base(root) + public MediaFileProvider(PathString virtualPathBase, string root) + : base(root) { VirtualPathBase = virtualPathBase; } - public MediaFileProvider(PathString virtualPathBase, string root, ExclusionFilters filters) : base(root, filters) + public MediaFileProvider(PathString virtualPathBase, string root, ExclusionFilters filters) + : base(root, filters) { VirtualPathBase = virtualPathBase; } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaFileStoreResolverMiddleware.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaFileStoreResolverMiddleware.cs index 2df251d0655..aed7860749d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaFileStoreResolverMiddleware.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaFileStoreResolverMiddleware.cs @@ -29,7 +29,7 @@ public MediaFileStoreResolverMiddleware( IMediaFileStoreCache mediaFileStoreCache, IMediaFileStore mediaFileStore, IOptions mediaOptions - ) + ) { _next = next; _logger = logger; @@ -79,30 +79,38 @@ public async Task Invoke(HttpContext context) // When multiple requests occur for the same file we use a Lazy // to initialize the file store request once. - await _workers.GetOrAdd(subPathValue, path => new Lazy(async () => - { - try - { - var fileStoreEntry = await _mediaFileStore.GetFileInfoAsync(path); + await _workers + .GetOrAdd( + subPathValue, + path => new Lazy( + async () => + { + try + { + var fileStoreEntry = await _mediaFileStore.GetFileInfoAsync(path); - if (fileStoreEntry != null) - { - using var stream = await _mediaFileStore.GetFileStreamAsync(fileStoreEntry); - await _mediaFileStoreCache.SetCacheAsync(stream, fileStoreEntry, context.RequestAborted); - } - } - catch (Exception ex) - { - // Log the error, and pass to pipeline to handle as 404. - // Multiple requests at the same time will all receive the same 404 - // as we use LazyThreadSafetyMode.ExecutionAndPublication. - _logger.LogError(ex, "Error retrieving file from media file store for request path {Path}", path); - } - finally - { - _workers.TryRemove(path, out var writeTask); - } - }, LazyThreadSafetyMode.ExecutionAndPublication)).Value; + if (fileStoreEntry != null) + { + using var stream = await _mediaFileStore.GetFileStreamAsync(fileStoreEntry); + await _mediaFileStoreCache.SetCacheAsync(stream, fileStoreEntry, context.RequestAborted); + } + } + catch (Exception ex) + { + // Log the error, and pass to pipeline to handle as 404. + // Multiple requests at the same time will all receive the same 404 + // as we use LazyThreadSafetyMode.ExecutionAndPublication. + _logger.LogError(ex, "Error retrieving file from media file store for request path {Path}", path); + } + finally + { + _workers.TryRemove(path, out var writeTask); + } + }, + LazyThreadSafetyMode.ExecutionAndPublication + ) + ) + .Value; // Always call next, this middleware always passes. await _next(context); diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaOptionsConfiguration.cs index c0fceea468d..41caae71324 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaOptionsConfiguration.cs @@ -13,7 +13,8 @@ public class MediaOptionsConfiguration : IConfigureOptions { private static readonly int[] _defaultSupportedSizes = [16, 32, 50, 100, 160, 240, 480, 600, 1024, 2048]; - private static readonly string[] _defaultAllowedFileExtensions = [ + private static readonly string[] _defaultAllowedFileExtensions = + [ // Images ".jpg", ".jpeg", @@ -22,7 +23,6 @@ public class MediaOptionsConfiguration : IConfigureOptions ".ico", ".svg", ".webp", - // Documents ".pdf", // (Portable Document Format; Adobe Acrobat) ".doc", @@ -35,13 +35,11 @@ public class MediaOptionsConfiguration : IConfigureOptions ".xls", ".xlsx", // (Microsoft Excel Document) ".psd", // (Adobe Photoshop Document) - // Audio ".mp3", ".m4a", ".ogg", ".wav", - // Video ".mp4", ".m4v", // (MPEG-4) @@ -84,12 +82,12 @@ public void Configure(MediaOptions options) // Because IShellConfiguration treats arrays as key value pairs, we replace the array value, // rather than letting Configure merge the default array with the appsettings value. - options.SupportedSizes = section.GetSection("SupportedSizes") - .Get()?.OrderBy(s => s).ToArray() ?? _defaultSupportedSizes; + options.SupportedSizes = section.GetSection("SupportedSizes").Get()?.OrderBy(s => s).ToArray() ?? _defaultSupportedSizes; options.AllowedFileExtensions = new HashSet( section.GetSection("AllowedFileExtensions").Get() ?? _defaultAllowedFileExtensions, - StringComparer.OrdinalIgnoreCase); + StringComparer.OrdinalIgnoreCase + ); options.MaxBrowserCacheDays = section.GetValue("MaxBrowserCacheDays", DefaultMaxBrowserCacheDays); options.MaxCacheDays = section.GetValue("MaxCacheDays", DefaultMaxCacheDays); diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaProfileService.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaProfileService.cs index 07772fa1485..6a12bf86f19 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaProfileService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/MediaProfileService.cs @@ -56,7 +56,6 @@ public async Task> GetMediaProfileCommands(string na else { return _nullProfile; - } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/RemoteMediaCacheBackgroundTask.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/RemoteMediaCacheBackgroundTask.cs index baf6541e18b..03078cda187 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/RemoteMediaCacheBackgroundTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/RemoteMediaCacheBackgroundTask.cs @@ -29,14 +29,12 @@ public RemoteMediaCacheBackgroundTask( IMediaFileStore mediaFileStore, IWebHostEnvironment webHostEnvironment, IOptions mediaOptions, - ILogger logger) + ILogger logger + ) { _mediaFileStore = mediaFileStore; - _cachePath = Path.Combine( - webHostEnvironment.WebRootPath, - shellSettings.Name, - DefaultMediaFileStoreCacheFileProvider.AssetsCachePath); + _cachePath = Path.Combine(webHostEnvironment.WebRootPath, shellSettings.Name, DefaultMediaFileStoreCacheFileProvider.AssetsCachePath); _cacheMaxStale = mediaOptions.Value.RemoteCacheMaxStale; _logger = logger; @@ -97,34 +95,23 @@ public async Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToke // Check if the remote media doesn't exist or was updated. var entry = await _mediaFileStore.GetFileInfoAsync(path); - if (entry is null || - (entry.LastModifiedUtc > fileInfo.LastWriteTimeUtc && - entry.LastModifiedUtc < minWriteTimeUtc)) + if (entry is null || (entry.LastModifiedUtc > fileInfo.LastWriteTimeUtc && entry.LastModifiedUtc < minWriteTimeUtc)) { File.Delete(fileInfo.FullName); } } } - catch (Exception ex) when (ex is DirectoryNotFoundException) - { - } + catch (Exception ex) when (ex is DirectoryNotFoundException) { } catch (Exception ex) when (ex.IsFileSharingViolation()) { if (_logger.IsEnabled(LogLevel.Warning)) { - _logger.LogWarning( - ex, - "Sharing violation while cleaning the remote media cache at '{CachePath}'.", - _cachePath); + _logger.LogWarning(ex, "Sharing violation while cleaning the remote media cache at '{CachePath}'.", _cachePath); } } catch (Exception ex) { - _logger.LogError( - ex, - "Failed to clean the remote media cache at '{CachePath}'.", - _cachePath); + _logger.LogError(ex, "Failed to clean the remote media cache at '{CachePath}'.", _cachePath); } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/ResizedMediaCacheBackgroundTask.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/ResizedMediaCacheBackgroundTask.cs index 485e02a4e4f..4529a8bf4b0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/ResizedMediaCacheBackgroundTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/ResizedMediaCacheBackgroundTask.cs @@ -30,7 +30,8 @@ public ResizedMediaCacheBackgroundTask( IOptions mediaOptions, IOptions middlewareOptions, IOptions cacheOptions, - ILogger logger) + ILogger logger + ) { _cachePath = Path.Combine(webHostEnvironment.WebRootPath, cacheOptions.Value.CacheFolder); _cacheFolder = Path.GetFileName(cacheOptions.Value.CacheFolder); @@ -79,25 +80,17 @@ public Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken canc } } } - catch (Exception ex) when (ex is DirectoryNotFoundException) - { - } + catch (Exception ex) when (ex is DirectoryNotFoundException) { } catch (Exception ex) when (ex.IsFileSharingViolation()) { if (_logger.IsEnabled(LogLevel.Warning)) { - _logger.LogWarning( - ex, - "Sharing violation while cleaning the resized media cache at '{CachePath}'.", - _cachePath); + _logger.LogWarning(ex, "Sharing violation while cleaning the resized media cache at '{CachePath}'.", _cachePath); } } catch (Exception ex) { - _logger.LogError( - ex, - "Failed to clean the resized media cache at '{CachePath}'.", - _cachePath); + _logger.LogError(ex, "Failed to clean the resized media cache at '{CachePath}'.", _cachePath); } return Task.CompletedTask; diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Services/TempDirCleanerService.cs b/src/OrchardCore.Modules/OrchardCore.Media/Services/TempDirCleanerService.cs index abcecb5b2f8..0f8f7c798b1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Services/TempDirCleanerService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Services/TempDirCleanerService.cs @@ -13,10 +13,12 @@ public class TempDirCleanerService : ModularTenantEvents private readonly ShellSettings _shellSettings; private readonly ILogger _logger; - public TempDirCleanerService(IMediaFileStore fileStore, + public TempDirCleanerService( + IMediaFileStore fileStore, AttachedMediaFieldFileService attachedMediaFieldFileService, ShellSettings shellSettings, - ILogger logger) + ILogger logger + ) { _fileStore = fileStore; _attachedMediaFieldFileService = attachedMediaFieldFileService; @@ -39,9 +41,7 @@ public override async Task ActivatedAsync() await foreach (var c in _fileStore.GetDirectoryContentAsync(tempDir)) { - var result = c.IsDirectory ? - await _fileStore.TryDeleteDirectoryAsync(c.Path) - : await _fileStore.TryDeleteFileAsync(c.Path); + var result = c.IsDirectory ? await _fileStore.TryDeleteDirectoryAsync(c.Path) : await _fileStore.TryDeleteFileAsync(c.Path); if (!result) { diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Settings/MediaFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.Media/Settings/MediaFieldSettingsDriver.cs index f8db6dbbe2d..56ae232e1e9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Settings/MediaFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Settings/MediaFieldSettingsDriver.cs @@ -20,10 +20,7 @@ public class MediaFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriver< private readonly MediaOptions _mediaOptions; protected readonly IStringLocalizer S; - public MediaFieldSettingsDriver( - IContentTypeProvider contentTypeProvider, - IOptions mediaOptions, - IStringLocalizer stringLocalizer) + public MediaFieldSettingsDriver(IContentTypeProvider contentTypeProvider, IOptions mediaOptions, IStringLocalizer stringLocalizer) { _contentTypeProvider = contentTypeProvider; _mediaOptions = mediaOptions.Value; @@ -32,44 +29,45 @@ public MediaFieldSettingsDriver( public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("MediaFieldSettings_Edit", model => - { - var settings = partFieldDefinition.GetSettings(); - - model.Hint = settings.Hint; - model.Required = settings.Required; - model.Multiple = settings.Multiple; - model.AllowMediaText = settings.AllowMediaText; - model.AllowAnchors = settings.AllowAnchors; - model.AllowAllDefaultMediaTypes = settings.AllowedExtensions?.Length == 0; - - var items = new List(); - foreach (var extension in _mediaOptions.AllowedFileExtensions) - { - if (_contentTypeProvider.TryGetContentType(extension, out var contentType)) + return Initialize( + "MediaFieldSettings_Edit", + model => { - var item = new MediaTypeViewModel() - { - Extension = extension, - ContentType = contentType, - IsSelected = settings.AllowedExtensions != null && settings.AllowedExtensions.Contains(extension) - }; + var settings = partFieldDefinition.GetSettings(); - var index = contentType.IndexOf('/'); + model.Hint = settings.Hint; + model.Required = settings.Required; + model.Multiple = settings.Multiple; + model.AllowMediaText = settings.AllowMediaText; + model.AllowAnchors = settings.AllowAnchors; + model.AllowAllDefaultMediaTypes = settings.AllowedExtensions?.Length == 0; - if (index > -1) + var items = new List(); + foreach (var extension in _mediaOptions.AllowedFileExtensions) { - item.Type = contentType[..index]; + if (_contentTypeProvider.TryGetContentType(extension, out var contentType)) + { + var item = new MediaTypeViewModel() + { + Extension = extension, + ContentType = contentType, + IsSelected = settings.AllowedExtensions != null && settings.AllowedExtensions.Contains(extension) + }; + + var index = contentType.IndexOf('/'); + + if (index > -1) + { + item.Type = contentType[..index]; + } + + items.Add(item); + } } - - items.Add(item); + model.MediaTypes = items.OrderBy(vm => vm.ContentType).ToArray(); } - } - model.MediaTypes = items - .OrderBy(vm => vm.ContentType) - .ToArray(); - - }).Location("Content"); + ) + .Location("Content"); } public override async Task UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) @@ -89,7 +87,8 @@ public override async Task UpdateAsync(ContentPartFieldDefinitio if (!model.AllowAllDefaultMediaTypes) { - var selectedExtensions = model.MediaTypes.Where(vm => vm.IsSelected && _mediaOptions.AllowedFileExtensions.Contains(vm.Extension)) + var selectedExtensions = model + .MediaTypes.Where(vm => vm.IsSelected && _mediaOptions.AllowedFileExtensions.Contains(vm.Extension)) .Select(x => x.Extension) .ToArray(); diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Shortcodes/AssetUrlShortcodeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Media/Shortcodes/AssetUrlShortcodeProvider.cs index 6ab8093d15d..ab2122f8825 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Shortcodes/AssetUrlShortcodeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Shortcodes/AssetUrlShortcodeProvider.cs @@ -15,10 +15,7 @@ public class AssetUrlShortcodeProvider : IShortcodeProvider private readonly IHttpContextAccessor _httpContextAccessor; private readonly ResourceManagementOptions _options; - public AssetUrlShortcodeProvider( - IMediaFileStore mediaFileStore, - IHttpContextAccessor httpContextAccessor, - IOptions options) + public AssetUrlShortcodeProvider(IMediaFileStore mediaFileStore, IHttpContextAccessor httpContextAccessor, IOptions options) { _mediaFileStore = mediaFileStore; _httpContextAccessor = httpContextAccessor; diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Shortcodes/ImageShortcodeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Media/Shortcodes/ImageShortcodeProvider.cs index 6d58f73b7c1..76902f2c3a4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Shortcodes/ImageShortcodeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Shortcodes/ImageShortcodeProvider.cs @@ -15,11 +15,12 @@ public class ImageShortcodeProvider : IShortcodeProvider { private static ValueTask Null => new((string)null); private static ValueTask ImageShortcode => new("[image]"); - private static readonly HashSet _shortcodes = new(StringComparer.OrdinalIgnoreCase) - { - "image", - "media" // [media] is a deprecated shortcode, and can be removed in a future release. - }; + private static readonly HashSet _shortcodes = + new(StringComparer.OrdinalIgnoreCase) + { + "image", + "media" // [media] is a deprecated shortcode, and can be removed in a future release. + }; private readonly IMediaFileStore _mediaFileStore; private readonly IHtmlSanitizerService _htmlSanitizerService; @@ -32,7 +33,8 @@ public ImageShortcodeProvider( IHtmlSanitizerService htmlSanitizerService, IHttpContextAccessor httpContextAccessor, IOptions options, - IFileVersionProvider fileVersionProvider) + IFileVersionProvider fileVersionProvider + ) { _mediaFileStore = mediaFileStore; _htmlSanitizerService = htmlSanitizerService; diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Media/Startup.cs index aabbd807d39..c7235266a43 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Startup.cs @@ -1,3 +1,5 @@ +using System; +using System.IO; using Fluid; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; @@ -48,8 +50,6 @@ using SixLabors.ImageSharp.Web.DependencyInjection; using SixLabors.ImageSharp.Web.Middleware; using SixLabors.ImageSharp.Web.Providers; -using System; -using System.IO; namespace OrchardCore.Media { @@ -74,15 +74,16 @@ public override void ConfigureServices(IServiceCollection services) services.AddSingleton(); services.AddSingleton(); - services.Configure(o => - { - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); + services + .Configure(o => + { + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); - o.Filters.AddFilter("img_tag", MediaFilters.ImgTag); - }) - .AddLiquidFilter("asset_url") - .AddLiquidFilter("resize_url"); + o.Filters.AddFilter("img_tag", MediaFilters.ImgTag); + }) + .AddLiquidFilter("asset_url") + .AddLiquidFilter("resize_url"); services.AddTransient, ResourceManagementOptionsConfiguration>(); @@ -104,9 +105,7 @@ public override void ConfigureServices(IServiceCollection services) return new MediaFileProvider(options.AssetsRequestPath, mediaPath); }); - services.AddSingleton(serviceProvider => - serviceProvider.GetRequiredService() - ); + services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService()); services.AddSingleton(serviceProvider => { @@ -122,9 +121,8 @@ public override void ConfigureServices(IServiceCollection services) var mediaUrlBase = "/" + fileStore.Combine(shellSettings.RequestUrlPrefix, mediaOptions.AssetsRequestPath); - var originalPathBase = serviceProvider.GetRequiredService().HttpContext - ?.Features.Get() - ?.OriginalPathBase ?? PathString.Empty; + var originalPathBase = + serviceProvider.GetRequiredService().HttpContext?.Features.Get()?.OriginalPathBase ?? PathString.Empty; if (originalPathBase.HasValue) { @@ -164,8 +162,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(sp => sp.GetRequiredService()); // Media Field - services.AddContentField() - .UseDisplayDriver(); + services.AddContentField().UseDisplayDriver(); services.AddScoped(); services.AddScoped(); services.AddScoped(); @@ -276,12 +273,14 @@ public class ShortcodesStartup : StartupBase public override void ConfigureServices(IServiceCollection services) { // Only add image as a descriptor as [media] is deprecated. - services.AddShortcode("image", d => - { - d.DefaultValue = "[image] [/image]"; - d.Hint = "Add a image from the media library."; - d.Usage = -@"[image]foo.jpg[/image]
+ services.AddShortcode( + "image", + d => + { + d.DefaultValue = "[image] [/image]"; + d.Hint = "Add a image from the media library."; + d.Usage = + @"[image]foo.jpg[/image]
@@ -292,23 +291,27 @@ public override void ConfigureServices(IServiceCollection services)
Args:class, alt
"; - d.Categories = ["HTML Content", "Media"]; - }); + d.Categories = ["HTML Content", "Media"]; + } + ); - services.AddShortcode("asset_url", d => - { - d.DefaultValue = "[asset_url] [/asset_url]"; - d.Hint = "Return a url from the media library."; - d.Usage = -@"[asset_url]foo.jpg[/asset_url]
+ services.AddShortcode( + "asset_url", + d => + { + d.DefaultValue = "[asset_url] [/asset_url]"; + d.Hint = "Return a url from the media library."; + d.Usage = + @"[asset_url]foo.jpg[/asset_url]
Args: width, height, mode
"; - d.Categories = ["HTML Content", "Media"]; - }); + d.Categories = ["HTML Content", "Media"]; + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/AnchorTagHelper.cs b/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/AnchorTagHelper.cs index 8826a27997f..6c231922be4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/AnchorTagHelper.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/AnchorTagHelper.cs @@ -30,11 +30,7 @@ public class AnchorTagHelper : TagHelper [HtmlAttributeName(AppendVersionAttributeName)] public bool AppendVersion { get; set; } - public AnchorTagHelper( - IMediaFileStore mediaFileStore, - IHttpContextAccessor httpContextAccessor, - IFileVersionProvider fileVersionProvider - ) + public AnchorTagHelper(IMediaFileStore mediaFileStore, IHttpContextAccessor httpContextAccessor, IFileVersionProvider fileVersionProvider) { _mediaFileStore = mediaFileStore; _httpContextAccessor = httpContextAccessor; diff --git a/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/ImageResizeTagHelper.cs b/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/ImageResizeTagHelper.cs index 828abd326b0..7d10a95fa28 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/ImageResizeTagHelper.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/ImageResizeTagHelper.cs @@ -29,7 +29,6 @@ public class ImageResizeTagHelper : TagHelper private readonly MediaOptions _mediaOptions; private readonly IMediaTokenService _mediaTokenService; - [HtmlAttributeName(ImageSizeWidthAttributeName)] public int? ImageWidth { get; set; } @@ -57,10 +56,7 @@ public class ImageResizeTagHelper : TagHelper [HtmlAttributeName("src")] public string Src { get; set; } - public ImageResizeTagHelper( - IMediaProfileService mediaProfileService, - IOptions mediaOptions, - IMediaTokenService mediaTokenService) + public ImageResizeTagHelper(IMediaProfileService mediaProfileService, IOptions mediaOptions, IMediaTokenService mediaTokenService) { _mediaProfileService = mediaProfileService; _mediaOptions = mediaOptions.Value; @@ -88,7 +84,17 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu queryStringParams = await _mediaProfileService.GetMediaProfileCommands(ImageProfile); } - var resizedSrc = ImageSharpUrlFormatter.GetImageResizeUrl(imgSrc, queryStringParams, ImageWidth, ImageHeight, ResizeMode, ImageQuality, ImageFormat, ImageAnchor, ImageBackgroundColor); + var resizedSrc = ImageSharpUrlFormatter.GetImageResizeUrl( + imgSrc, + queryStringParams, + ImageWidth, + ImageHeight, + ResizeMode, + ImageQuality, + ImageFormat, + ImageAnchor, + ImageBackgroundColor + ); if (_mediaOptions.UseTokenizedQueryString) { diff --git a/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/ImageTagHelper.cs b/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/ImageTagHelper.cs index f57ef8c0ae7..ae9caccf3c2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/ImageTagHelper.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/TagHelpers/ImageTagHelper.cs @@ -35,11 +35,7 @@ public class ImageTagHelper : TagHelper [HtmlAttributeName(AppendVersionAttributeName)] public bool AppendVersion { get; set; } - public ImageTagHelper( - IMediaFileStore mediaFileStore, - IHttpContextAccessor httpContextAccessor, - IFileVersionProvider fileVersionProvider - ) + public ImageTagHelper(IMediaFileStore mediaFileStore, IHttpContextAccessor httpContextAccessor, IFileVersionProvider fileVersionProvider) { _mediaFileStore = mediaFileStore; _httpContextAccessor = httpContextAccessor; diff --git a/src/OrchardCore.Modules/OrchardCore.Media/ViewModels/MediaProfileViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Media/ViewModels/MediaProfileViewModel.cs index 6f4be6fef2a..c56872dace0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/ViewModels/MediaProfileViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/ViewModels/MediaProfileViewModel.cs @@ -27,6 +27,7 @@ public class MediaProfileViewModel [BindNever] public List AvailableResizeModes { get; set; } = []; + [BindNever] public List AvailableFormats { get; set; } = []; } diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Menu/AdminMenu.cs index d1626a1000d..be0d05bf3f2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/AdminMenu.cs @@ -7,13 +7,14 @@ namespace OrchardCore.Menu { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "contentTypeId", "Menu" }, - { "Area", "OrchardCore.Contents" }, - { "Options.SelectedContentType", "Menu" }, - { "Options.CanCreateSelectedContentType", true } - }; + private static readonly RouteValueDictionary _routeValues = + new() + { + { "contentTypeId", "Menu" }, + { "Area", "OrchardCore.Contents" }, + { "Options.SelectedContentType", "Menu" }, + { "Options.CanCreateSelectedContentType", true } + }; protected readonly IStringLocalizer S; @@ -29,14 +30,10 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Content"], design => design - .Add(S["Menus"], S["Menus"].PrefixPosition(), menus => menus - .Permission(Permissions.ManageMenu) - .Action("List", "Admin", _routeValues) - .LocalNav() - ) - ); + builder.Add( + S["Content"], + design => design.Add(S["Menus"], S["Menus"].PrefixPosition(), menus => menus.Permission(Permissions.ManageMenu).Action("List", "Admin", _routeValues).LocalNav()) + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Menu/Controllers/AdminController.cs index 5e2763c1d03..6629a32e23f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/Controllers/AdminController.cs @@ -37,7 +37,8 @@ public AdminController( IContentDefinitionManager contentDefinitionManager, INotifier notifier, IHtmlLocalizer localizer, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _contentManager = contentManager; _authorizationService = authorizationService; @@ -130,10 +131,7 @@ public async Task CreatePost(string id, string menuContentItemId, if (menuItems == null) { - parentMenuItem["MenuItemsListPart"] = new JsonObject - { - ["MenuItems"] = menuItems = [], - }; + parentMenuItem["MenuItemsListPart"] = new JsonObject { ["MenuItems"] = menuItems = [], }; } menuItems.Add(JObject.FromObject(contentItem)); @@ -230,11 +228,10 @@ public async Task EditPost(string menuContentItemId, string menuI return View(model); } - menuItem.Merge((JsonObject)contentItem.Content, new JsonMergeSettings - { - MergeArrayHandling = MergeArrayHandling.Replace, - MergeNullValueHandling = MergeNullValueHandling.Merge - }); + menuItem.Merge( + (JsonObject)contentItem.Content, + new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge } + ); // Merge doesn't copy the properties. menuItem[nameof(ContentItem.DisplayText)] = contentItem.DisplayText; diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/ContentMenuItemPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/ContentMenuItemPartDisplayDriver.cs index 5d07cc7748f..1ed0ca3f515 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/ContentMenuItemPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/ContentMenuItemPartDisplayDriver.cs @@ -13,26 +13,35 @@ public class ContentMenuItemPartDisplayDriver : ContentPartDisplayDriver - { - shape.MenuItemPart = part; - }) - .Location("Admin", "Content:10"), - Dynamic("ContentMenuItemPart_Thumbnail", shape => - { - shape.MenuItemPart = part; - }) - .Location("Thumbnail", "Content:10") + Dynamic( + "ContentMenuItemPart_Admin", + shape => + { + shape.MenuItemPart = part; + } + ) + .Location("Admin", "Content:10"), + Dynamic( + "ContentMenuItemPart_Thumbnail", + shape => + { + shape.MenuItemPart = part; + } + ) + .Location("Thumbnail", "Content:10") ); } public override IDisplayResult Edit(ContentMenuItemPart part) { - return Initialize("ContentMenuItemPart_Edit", model => - { - model.Name = part.ContentItem.DisplayText; - model.MenuItemPart = part; - }); + return Initialize( + "ContentMenuItemPart_Edit", + model => + { + model.Name = part.ContentItem.DisplayText; + model.MenuItemPart = part; + } + ); } public override async Task UpdateAsync(ContentMenuItemPart part, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/HtmlMenuItemPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/HtmlMenuItemPartDisplayDriver.cs index c10348387e4..65f7eaa0bfa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/HtmlMenuItemPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/HtmlMenuItemPartDisplayDriver.cs @@ -29,7 +29,7 @@ public HtmlMenuItemPartDisplayDriver( IStringLocalizer localizer, IHtmlSanitizerService htmlSanitizerService, HtmlEncoder htmlencoder - ) + ) { _urlHelperFactory = urlHelperFactory; _actionContextAccessor = actionContextAccessor; @@ -48,28 +48,37 @@ public override IDisplayResult Display(HtmlMenuItemPart part, BuildPartDisplayCo } return Combine( - Dynamic("HtmlMenuItemPart_Admin", shape => - { - shape.MenuItemPart = part; - }) - .Location("Admin", "Content:10"), - Dynamic("HtmlMenuItemPart_Thumbnail", shape => - { - shape.MenuItemPart = part; - }) - .Location("Thumbnail", "Content:10") + Dynamic( + "HtmlMenuItemPart_Admin", + shape => + { + shape.MenuItemPart = part; + } + ) + .Location("Admin", "Content:10"), + Dynamic( + "HtmlMenuItemPart_Thumbnail", + shape => + { + shape.MenuItemPart = part; + } + ) + .Location("Thumbnail", "Content:10") ); } public override IDisplayResult Edit(HtmlMenuItemPart part) { - return Initialize("HtmlMenuItemPart_Edit", model => - { - model.Name = part.ContentItem.DisplayText; - model.Url = part.Url; - model.Html = part.Html; - model.MenuItemPart = part; - }); + return Initialize( + "HtmlMenuItemPart_Edit", + model => + { + model.Name = part.ContentItem.DisplayText; + model.Url = part.Url; + model.Html = part.Html; + model.MenuItemPart = part; + } + ); } public override async Task UpdateAsync(HtmlMenuItemPart part, IUpdateModel updater, UpdatePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/LinkMenuItemPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/LinkMenuItemPartDisplayDriver.cs index 1fee2baa094..86815cb1a21 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/LinkMenuItemPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/LinkMenuItemPartDisplayDriver.cs @@ -28,7 +28,7 @@ public LinkMenuItemPartDisplayDriver( IStringLocalizer localizer, IHtmlSanitizerService htmlSanitizerService, HtmlEncoder htmlencoder - ) + ) { _urlHelperFactory = urlHelperFactory; _actionContextAccessor = actionContextAccessor; @@ -40,27 +40,36 @@ HtmlEncoder htmlencoder public override IDisplayResult Display(LinkMenuItemPart part, BuildPartDisplayContext context) { return Combine( - Dynamic("LinkMenuItemPart_Admin", shape => - { - shape.MenuItemPart = part; - }) - .Location("Admin", "Content:10"), - Dynamic("LinkMenuItemPart_Thumbnail", shape => - { - shape.MenuItemPart = part; - }) - .Location("Thumbnail", "Content:10") + Dynamic( + "LinkMenuItemPart_Admin", + shape => + { + shape.MenuItemPart = part; + } + ) + .Location("Admin", "Content:10"), + Dynamic( + "LinkMenuItemPart_Thumbnail", + shape => + { + shape.MenuItemPart = part; + } + ) + .Location("Thumbnail", "Content:10") ); } public override IDisplayResult Edit(LinkMenuItemPart part) { - return Initialize("LinkMenuItemPart_Edit", model => - { - model.Name = part.ContentItem.DisplayText; - model.Url = part.Url; - model.MenuItemPart = part; - }); + return Initialize( + "LinkMenuItemPart_Edit", + model => + { + model.Name = part.ContentItem.DisplayText; + model.Url = part.Url; + model.MenuItemPart = part; + } + ); } public override async Task UpdateAsync(LinkMenuItemPart part, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/MenuPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/MenuPartDisplayDriver.cs index 30b74a72591..e60579951f8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/MenuPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/Drivers/MenuPartDisplayDriver.cs @@ -29,7 +29,7 @@ public MenuPartDisplayDriver( IHtmlLocalizer htmlLocalizer, INotifier notifier, ILogger logger - ) + ) { _contentDefinitionManager = contentDefinitionManager; H = htmlLocalizer; @@ -39,29 +39,42 @@ ILogger logger public override IDisplayResult Edit(MenuPart part) { - return Initialize("MenuPart_Edit", async model => - { - var menuItemContentTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(t => t.StereotypeEquals("MenuItem")); - var notify = false; - - foreach (var menuItem in part.ContentItem.As().MenuItems) + return Initialize( + "MenuPart_Edit", + async model => { - if (!menuItemContentTypes.Any(c => c.Name == menuItem.ContentType)) + var menuItemContentTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(t => t.StereotypeEquals("MenuItem")); + var notify = false; + + foreach (var menuItem in part.ContentItem.As().MenuItems) { - _logger.LogWarning("The menu item content item with id {ContentItemId} has no matching {ContentType} content type definition.", menuItem.ContentItem.ContentItemId, menuItem.ContentItem.ContentType); - await _notifier.WarningAsync(H["The menu item content item with id {0} has no matching {1} content type definition.", menuItem.ContentItem.ContentItemId, menuItem.ContentItem.ContentType]); - notify = true; + if (!menuItemContentTypes.Any(c => c.Name == menuItem.ContentType)) + { + _logger.LogWarning( + "The menu item content item with id {ContentItemId} has no matching {ContentType} content type definition.", + menuItem.ContentItem.ContentItemId, + menuItem.ContentItem.ContentType + ); + await _notifier.WarningAsync( + H[ + "The menu item content item with id {0} has no matching {1} content type definition.", + menuItem.ContentItem.ContentItemId, + menuItem.ContentItem.ContentType + ] + ); + notify = true; + } } - } - if (notify) - { - await _notifier.WarningAsync(H["Publishing this content item may erase created content. Fix any content type issues beforehand."]); - } + if (notify) + { + await _notifier.WarningAsync(H["Publishing this content item may erase created content. Fix any content type issues beforehand."]); + } - model.MenuPart = part; - model.MenuItemContentTypes = menuItemContentTypes; - }); + model.MenuPart = part; + model.MenuItemContentTypes = menuItemContentTypes; + } + ); } public override async Task UpdateAsync(MenuPart part, IUpdateModel updater) @@ -122,7 +135,8 @@ private static JsonObject ProcessItem(MenuItemsListPart originalItems, JsonObjec { menuItems.Add(ProcessItem(originalItems, children[i] as JsonObject)); contentItem["MenuItemsListPart"] = new JsonObject { ["MenuItems"] = menuItems }; - }; + } + ; } return contentItem; diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/GraphQL/MenuItemContentTypeBuilder.cs b/src/OrchardCore.Modules/OrchardCore.Menu/GraphQL/MenuItemContentTypeBuilder.cs index ead2711ce86..dfaded09814 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/GraphQL/MenuItemContentTypeBuilder.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/GraphQL/MenuItemContentTypeBuilder.cs @@ -17,12 +17,14 @@ public void Build(FieldType contentQuery, ContentTypeDefinition contentTypeDefin return; } - contentItemType.AddField(new FieldType - { - Type = typeof(MenuItemsListQueryObjectType), - Name = nameof(MenuItemsListPart).ToFieldName(), - Resolver = new FuncFieldResolver(context => context.Source.As()) - }); + contentItemType.AddField( + new FieldType + { + Type = typeof(MenuItemsListQueryObjectType), + Name = nameof(MenuItemsListPart).ToFieldName(), + Resolver = new FuncFieldResolver(context => context.Source.As()) + } + ); contentItemType.Interface(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/GraphQL/MenuItemsListQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Menu/GraphQL/MenuItemsListQueryObjectType.cs index 19ccba88ccc..d0d35e3cdad 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/GraphQL/MenuItemsListQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/GraphQL/MenuItemsListQueryObjectType.cs @@ -9,10 +9,7 @@ public MenuItemsListQueryObjectType() { Name = "MenuItemsListPart"; - Field>("menuItems") - .Description("The menu items.") - .Resolve(context => context.Source.MenuItems); - + Field>("menuItems").Description("The menu items.").Resolve(context => context.Source.MenuItems); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Menu/Manifest.cs index 1ad38c2680a..9d5b1e93487 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/Manifest.cs @@ -6,12 +6,6 @@ Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion, Description = "The Menu module provides menu management features.", - Dependencies = - [ - "OrchardCore.Contents", - "OrchardCore.Title", - "OrchardCore.Alias", - "OrchardCore.Recipes.Core", - ], + Dependencies = ["OrchardCore.Contents", "OrchardCore.Title", "OrchardCore.Alias", "OrchardCore.Recipes.Core",], Category = "Navigation" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/MenuShapes.cs b/src/OrchardCore.Modules/OrchardCore.Menu/MenuShapes.cs index f957782ed4a..b5bcbd568ad 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/MenuShapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/MenuShapes.cs @@ -15,7 +15,8 @@ public class MenuShapes : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("Menu") + builder + .Describe("Menu") .OnProcessing(async context => { var menu = context.Shape; @@ -28,11 +29,12 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) var contentManager = context.ServiceProvider.GetRequiredService(); var handleManager = context.ServiceProvider.GetRequiredService(); - var contentItemId = menu.TryGetProperty("Alias", out object alias) && alias != null - ? await handleManager.GetContentItemIdAsync(alias.ToString()) - : menu.TryGetProperty("ContentItemId", out object id) - ? id.ToString() - : null; + var contentItemId = + menu.TryGetProperty("Alias", out object alias) && alias != null + ? await handleManager.GetContentItemIdAsync(alias.ToString()) + : menu.TryGetProperty("ContentItemId", out object id) + ? id.ToString() + : null; if (contentItemId == null) { @@ -74,12 +76,17 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) foreach (var contentItem in menuItems) { - var shape = await shapeFactory.CreateAsync("MenuItem", Arguments.From(new - { - ContentItem = contentItem, - Level = 0, - Menu = menu - })); + var shape = await shapeFactory.CreateAsync( + "MenuItem", + Arguments.From( + new + { + ContentItem = contentItem, + Level = 0, + Menu = menu + } + ) + ); shape.Metadata.Differentiator = differentiator; @@ -88,7 +95,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("MenuItem") + builder + .Describe("MenuItem") .OnDisplaying(async context => { var menuItem = context.Shape; @@ -105,12 +113,17 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { foreach (var contentItem in menuItems) { - var shape = await shapeFactory.CreateAsync("MenuItem", Arguments.From(new - { - ContentItem = contentItem, - Level = level + 1, - Menu = menu - })); + var shape = await shapeFactory.CreateAsync( + "MenuItem", + Arguments.From( + new + { + ContentItem = contentItem, + Level = level + 1, + Menu = menu + } + ) + ); shape.Metadata.Differentiator = differentiator; @@ -143,7 +156,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("MenuItemLink") + builder + .Describe("MenuItemLink") .OnDisplaying(displaying => { var menuItem = displaying.Shape; diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/Models/MenuPart.cs b/src/OrchardCore.Modules/OrchardCore.Menu/Models/MenuPart.cs index e728ea35723..3826ca671bb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/Models/MenuPart.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/Models/MenuPart.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Menu.Models { // This part is added automatically to all menus - public class MenuPart : ContentPart - { - } + public class MenuPart : ContentPart { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Menu/Permissions.cs index 3ec0bc2fa3d..95fb4be217a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageMenu = new("ManageMenu", "Manage menus"); - private readonly IEnumerable _allPermissions = - [ - ManageMenu, - ]; + private readonly IEnumerable _allPermissions = [ManageMenu,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/Settings/HtmlMenuItemPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Menu/Settings/HtmlMenuItemPartSettingsDisplayDriver.cs index b452dec1e45..ea634fadd64 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/Settings/HtmlMenuItemPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/Settings/HtmlMenuItemPartSettingsDisplayDriver.cs @@ -12,13 +12,16 @@ public class HtmlMenuItemPartSettingsDisplayDriver : ContentTypePartDefinitionDi { public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("HtmlMenuItemPartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + "HtmlMenuItemPartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); - model.SanitizeHtml = settings.SanitizeHtml; - }) - .Location("Content:20"); + model.SanitizeHtml = settings.SanitizeHtml; + } + ) + .Location("Content:20"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Menu/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Menu/Startup.cs index fe576a8c95e..d73d4797edf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Menu/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Menu/Startup.cs @@ -27,22 +27,18 @@ public override void ConfigureServices(IServiceCollection services) // MenuPart services.AddScoped(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddContentPart(); // LinkMenuItemPart - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); // ContentMenuItemPart - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); // HtmlMenuItemPart - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddScoped(); services.AddTagHelpers(); diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/AdminMenuMicrosoftAccount.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/AdminMenuMicrosoftAccount.cs index 3fcd818deb8..6f9d34f5c44 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/AdminMenuMicrosoftAccount.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/AdminMenuMicrosoftAccount.cs @@ -9,11 +9,8 @@ namespace OrchardCore.Microsoft.Authentication [Feature(MicrosoftAuthenticationConstants.Features.MicrosoftAccount)] public class AdminMenuMicrosoftAccount : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", MicrosoftAuthenticationConstants.Features.MicrosoftAccount }, - }; + private static readonly RouteValueDictionary _routeValues = + new() { { "area", "OrchardCore.Settings" }, { "groupId", MicrosoftAuthenticationConstants.Features.MicrosoftAccount }, }; protected readonly IStringLocalizer S; @@ -29,18 +26,25 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Authentication"], authentication => authentication - .Add(S["Microsoft"], S["Microsoft"].PrefixPosition(), microsoft => microsoft - .AddClass("microsoft") - .Id("microsoft") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageMicrosoftAuthentication) - .LocalNav() - ) + builder.Add( + S["Security"], + security => + security.Add( + S["Authentication"], + authentication => + authentication.Add( + S["Microsoft"], + S["Microsoft"].PrefixPosition(), + microsoft => + microsoft + .AddClass("microsoft") + .Id("microsoft") + .Action("Index", "Admin", _routeValues) + .Permission(Permissions.ManageMicrosoftAuthentication) + .LocalNav() + ) ) - ); + ); return Task.CompletedTask; } @@ -49,11 +53,7 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) [Feature(MicrosoftAuthenticationConstants.Features.AAD)] public class AdminMenuAAD : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", MicrosoftAuthenticationConstants.Features.AAD }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", MicrosoftAuthenticationConstants.Features.AAD }, }; protected readonly IStringLocalizer S; @@ -66,15 +66,25 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Authentication"], authentication => authentication - .Add(S["Microsoft Entra ID"], S["Microsoft Entra ID"].PrefixPosition(), client => client - .AddClass("microsoft-entra-id").Id("microsoft-entra-id") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageMicrosoftAuthentication) - .LocalNav()) - )); + builder.Add( + S["Security"], + security => + security.Add( + S["Authentication"], + authentication => + authentication.Add( + S["Microsoft Entra ID"], + S["Microsoft Entra ID"].PrefixPosition(), + client => + client + .AddClass("microsoft-entra-id") + .Id("microsoft-entra-id") + .Action("Index", "Admin", _routeValues) + .Permission(Permissions.ManageMicrosoftAuthentication) + .LocalNav() + ) + ) + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/AzureADOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/AzureADOptionsConfiguration.cs index 95daa4d3b1b..baf66c9c7f1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/AzureADOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/AzureADOptionsConfiguration.cs @@ -7,13 +7,12 @@ using OrchardCore.Microsoft.Authentication.Settings; using MicrosoftIdentityDefaults = Microsoft.Identity.Web.Constants; - namespace OrchardCore.Microsoft.Authentication.Configuration { - public class AzureADOptionsConfiguration : - IConfigureOptions, - IConfigureNamedOptions, - IConfigureNamedOptions + public class AzureADOptionsConfiguration + : IConfigureOptions, + IConfigureNamedOptions, + IConfigureNamedOptions { public const string AzureAdOpenIdConnectScheme = MicrosoftIdentityDefaults.AzureAd + OpenIdConnectDefaults.AuthenticationScheme; @@ -42,16 +41,22 @@ public void Configure(AuthenticationOptions options) } // Register the OpenID Connect client handler in the authentication handlers collection. - options.AddScheme(Constants.AzureAd, builder => - { - builder.DisplayName = settings.DisplayName; - builder.HandlerType = typeof(PolicySchemeHandler); - }); - - options.AddScheme(AzureAdOpenIdConnectScheme, builder => - { - builder.HandlerType = typeof(OpenIdConnectHandler); - }); + options.AddScheme( + Constants.AzureAd, + builder => + { + builder.DisplayName = settings.DisplayName; + builder.HandlerType = typeof(PolicySchemeHandler); + } + ); + + options.AddScheme( + AzureAdOpenIdConnectScheme, + builder => + { + builder.HandlerType = typeof(OpenIdConnectHandler); + } + ); } public void Configure(string name, MicrosoftIdentityOptions options) @@ -89,6 +94,7 @@ public void Configure(string name, PolicySchemeOptions options) options.ForwardDefault = "Identity.External"; options.ForwardChallenge = AzureAdOpenIdConnectScheme; } + public void Configure(PolicySchemeOptions options) => Debug.Fail("This infrastructure method shouldn't be called."); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/AzureADSettingsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/AzureADSettingsConfiguration.cs index 2606a5e764b..c5d395d587c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/AzureADSettingsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/AzureADSettingsConfiguration.cs @@ -15,10 +15,7 @@ public class AzureADSettingsConfiguration : IConfigureOptions private readonly ShellSettings _shellSettings; private readonly ILogger _logger; - public AzureADSettingsConfiguration( - IAzureADService azureADService, - ShellSettings shellSettings, - ILogger logger) + public AzureADSettingsConfiguration(IAzureADService azureADService, ShellSettings shellSettings, ILogger logger) { _azureADService = azureADService; _shellSettings = shellSettings; @@ -27,9 +24,7 @@ public AzureADSettingsConfiguration( public void Configure(AzureADSettings options) { - var settings = GetAzureADSettingsAsync() - .GetAwaiter() - .GetResult(); + var settings = GetAzureADSettingsAsync().GetAwaiter().GetResult(); if (settings != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/MicrosoftAccountOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/MicrosoftAccountOptionsConfiguration.cs index 4d288619e56..66985bbd5c6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/MicrosoftAccountOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/MicrosoftAccountOptionsConfiguration.cs @@ -8,9 +8,7 @@ namespace OrchardCore.Microsoft.Authentication.Configuration { - public class MicrosoftAccountOptionsConfiguration : - IConfigureOptions, - IConfigureNamedOptions + public class MicrosoftAccountOptionsConfiguration : IConfigureOptions, IConfigureNamedOptions { private readonly MicrosoftAccountSettings _microsoftAccountSettings; private readonly IDataProtectionProvider _dataProtectionProvider; @@ -19,7 +17,8 @@ public class MicrosoftAccountOptionsConfiguration : public MicrosoftAccountOptionsConfiguration( IOptions microsoftAccountSettings, IDataProtectionProvider dataProtectionProvider, - ILogger logger) + ILogger logger + ) { _microsoftAccountSettings = microsoftAccountSettings.Value; _dataProtectionProvider = dataProtectionProvider; @@ -33,8 +32,7 @@ public void Configure(AuthenticationOptions options) return; } - if (string.IsNullOrWhiteSpace(_microsoftAccountSettings.AppId) || - string.IsNullOrWhiteSpace(_microsoftAccountSettings.AppSecret)) + if (string.IsNullOrWhiteSpace(_microsoftAccountSettings.AppId) || string.IsNullOrWhiteSpace(_microsoftAccountSettings.AppSecret)) { _logger.LogWarning("The Microsoft login provider is enabled but not configured."); @@ -42,11 +40,14 @@ public void Configure(AuthenticationOptions options) } // Register the OpenID Connect client handler in the authentication handlers collection. - options.AddScheme(MicrosoftAccountDefaults.AuthenticationScheme, builder => - { - builder.DisplayName = "Microsoft Account"; - builder.HandlerType = typeof(MicrosoftAccountHandler); - }); + options.AddScheme( + MicrosoftAccountDefaults.AuthenticationScheme, + builder => + { + builder.DisplayName = "Microsoft Account"; + builder.HandlerType = typeof(MicrosoftAccountHandler); + } + ); } public void Configure(string name, MicrosoftAccountOptions options) @@ -66,7 +67,9 @@ public void Configure(string name, MicrosoftAccountOptions options) try { - options.ClientSecret = _dataProtectionProvider.CreateProtector(MicrosoftAuthenticationConstants.Features.MicrosoftAccount).Unprotect(_microsoftAccountSettings.AppSecret); + options.ClientSecret = _dataProtectionProvider + .CreateProtector(MicrosoftAuthenticationConstants.Features.MicrosoftAccount) + .Unprotect(_microsoftAccountSettings.AppSecret); } catch { diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/MicrosoftAccountSettingsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/MicrosoftAccountSettingsConfiguration.cs index a92a8ec9b00..e0b531477e7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/MicrosoftAccountSettingsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/MicrosoftAccountSettingsConfiguration.cs @@ -18,7 +18,8 @@ public class MicrosoftAccountSettingsConfiguration : IConfigureOptions logger) + ILogger logger + ) { _microsoftAccountService = microsoftAccountService; _shellSettings = shellSettings; @@ -27,9 +28,7 @@ public MicrosoftAccountSettingsConfiguration( public void Configure(MicrosoftAccountSettings options) { - var settings = GetMicrosoftAccountSettingsAsync() - .GetAwaiter() - .GetResult(); + var settings = GetMicrosoftAccountSettingsAsync().GetAwaiter().GetResult(); if (settings != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/OpenIdConnectOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/OpenIdConnectOptionsConfiguration.cs index 0d523f8fac9..1bf3cdfb692 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/OpenIdConnectOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Configuration/OpenIdConnectOptionsConfiguration.cs @@ -13,9 +13,7 @@ internal class OpenIdConnectOptionsConfiguration : IConfigureNamedOptions _azureADOptions; private readonly AzureADSettings _azureADSettings; - public OpenIdConnectOptionsConfiguration( - IOptionsMonitor azureADOptions, - IOptions azureADSettings) + public OpenIdConnectOptionsConfiguration(IOptionsMonitor azureADOptions, IOptions azureADSettings) { _azureADOptions = azureADOptions; _azureADSettings = azureADSettings.Value; @@ -38,7 +36,6 @@ public void Configure(string name, OpenIdConnectOptions options) options.SignInScheme = "Identity.External"; options.UseTokenLifetime = true; options.SaveTokens = _azureADSettings.SaveTokens; - } public void Configure(OpenIdConnectOptions options) => Debug.Fail("This infrastructure method shouldn't be called."); diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Deployment/AzureADDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Deployment/AzureADDeploymentStepDriver.cs index 0335201e8d3..519086612c0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Deployment/AzureADDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Deployment/AzureADDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class AzureADDeploymentStepDriver : DisplayDriver EditAsync(AzureADSettings settings, B { return null; } - return Initialize("MicrosoftEntraIDSettings_Edit", model => - { - model.DisplayName = settings.DisplayName; - model.AppId = settings.AppId; - model.TenantId = settings.TenantId; - model.SaveTokens = settings.SaveTokens; - if (settings.CallbackPath.HasValue) - { - model.CallbackPath = settings.CallbackPath.Value; - } - }).Location("Content:0").OnGroup(MicrosoftAuthenticationConstants.Features.AAD); + return Initialize( + "MicrosoftEntraIDSettings_Edit", + model => + { + model.DisplayName = settings.DisplayName; + model.AppId = settings.AppId; + model.TenantId = settings.TenantId; + model.SaveTokens = settings.SaveTokens; + if (settings.CallbackPath.HasValue) + { + model.CallbackPath = settings.CallbackPath.Value; + } + } + ) + .Location("Content:0") + .OnGroup(MicrosoftAuthenticationConstants.Features.AAD); } public override async Task UpdateAsync(AzureADSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Drivers/MicrosoftAccountSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Drivers/MicrosoftAccountSettingsDisplayDriver.cs index c66aa8edbca..4afcc4fda18 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Drivers/MicrosoftAccountSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Drivers/MicrosoftAccountSettingsDisplayDriver.cs @@ -29,7 +29,8 @@ public MicrosoftAccountSettingsDisplayDriver( IHttpContextAccessor httpContextAccessor, IShellHost shellHost, ShellSettings shellSettings, - ILogger logger) + ILogger logger + ) { _authorizationService = authorizationService; _dataProtectionProvider = dataProtectionProvider; @@ -47,33 +48,38 @@ public override async Task EditAsync(MicrosoftAccountSettings se return null; } - return Initialize("MicrosoftAccountSettings_Edit", model => - { - model.AppId = settings.AppId; - if (!string.IsNullOrWhiteSpace(settings.AppSecret)) - { - try + return Initialize( + "MicrosoftAccountSettings_Edit", + model => { - var protector = _dataProtectionProvider.CreateProtector(MicrosoftAuthenticationConstants.Features.MicrosoftAccount); - model.AppSecret = protector.Unprotect(settings.AppSecret); + model.AppId = settings.AppId; + if (!string.IsNullOrWhiteSpace(settings.AppSecret)) + { + try + { + var protector = _dataProtectionProvider.CreateProtector(MicrosoftAuthenticationConstants.Features.MicrosoftAccount); + model.AppSecret = protector.Unprotect(settings.AppSecret); + } + catch (CryptographicException) + { + _logger.LogError("The app secret could not be decrypted. It may have been encrypted using a different key."); + model.AppSecret = string.Empty; + model.HasDecryptionError = true; + } + } + else + { + model.AppSecret = string.Empty; + } + if (settings.CallbackPath.HasValue) + { + model.CallbackPath = settings.CallbackPath.Value; + } + model.SaveTokens = settings.SaveTokens; } - catch (CryptographicException) - { - _logger.LogError("The app secret could not be decrypted. It may have been encrypted using a different key."); - model.AppSecret = string.Empty; - model.HasDecryptionError = true; - } - } - else - { - model.AppSecret = string.Empty; - } - if (settings.CallbackPath.HasValue) - { - model.CallbackPath = settings.CallbackPath.Value; - } - model.SaveTokens = settings.SaveTokens; - }).Location("Content:5").OnGroup(MicrosoftAuthenticationConstants.Features.MicrosoftAccount); + ) + .Location("Content:5") + .OnGroup(MicrosoftAuthenticationConstants.Features.MicrosoftAccount); } public override async Task UpdateAsync(MicrosoftAccountSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Extensions/OrchardCoreBuilderExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Extensions/OrchardCoreBuilderExtensions.cs index 83494f8fb05..142b1868d69 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Extensions/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Extensions/OrchardCoreBuilderExtensions.cs @@ -8,24 +8,28 @@ public static class OrchardCoreBuilderExtensions { public static OrchardCoreBuilder ConfigureMicrosoftAccountSettings(this OrchardCoreBuilder builder) { - builder.ConfigureServices((tenantServices, serviceProvider) => - { - var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Microsoft_Authentication_MicrosoftAccount"); + builder.ConfigureServices( + (tenantServices, serviceProvider) => + { + var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Microsoft_Authentication_MicrosoftAccount"); - tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); - }); + tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); + } + ); return builder; } public static OrchardCoreBuilder ConfigureAzureADSettings(this OrchardCoreBuilder builder) { - builder.ConfigureServices((tenantServices, serviceProvider) => - { - var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Microsoft_Authentication_AzureAD"); + builder.ConfigureServices( + (tenantServices, serviceProvider) => + { + var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Microsoft_Authentication_AzureAD"); - tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); - }); + tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); + } + ); return builder; } diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/MicrosoftAccountStartup.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/MicrosoftAccountStartup.cs index 5ea511e78f9..63a281ced9d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/MicrosoftAccountStartup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/MicrosoftAccountStartup.cs @@ -36,14 +36,16 @@ public override void ConfigureServices(IServiceCollection services) services.AddTransient, MicrosoftAccountSettingsConfiguration>(); // Register the options initializers required by the Microsoft Account Handler. - services.TryAddEnumerable(new[] - { - // Orchard-specific initializers: - ServiceDescriptor.Transient, MicrosoftAccountOptionsConfiguration>(), - ServiceDescriptor.Transient, MicrosoftAccountOptionsConfiguration>(), - // Built-in initializers: - ServiceDescriptor.Transient, OAuthPostConfigureOptions>() - }); + services.TryAddEnumerable( + new[] + { + // Orchard-specific initializers: + ServiceDescriptor.Transient, MicrosoftAccountOptionsConfiguration>(), + ServiceDescriptor.Transient, MicrosoftAccountOptionsConfiguration>(), + // Built-in initializers: + ServiceDescriptor.Transient, OAuthPostConfigureOptions>() + } + ); } } @@ -63,17 +65,18 @@ public override void ConfigureServices(IServiceCollection services) services.AddTransient, AzureADSettingsConfiguration>(); // Register the options initializers required by the Policy Scheme, Cookie and OpenId Connect Handler. - services.TryAddEnumerable(new[] - { - // Orchard-specific initializers. - ServiceDescriptor.Transient, AzureADOptionsConfiguration>(), - ServiceDescriptor.Transient, AzureADOptionsConfiguration>(), - ServiceDescriptor.Transient, AzureADOptionsConfiguration>(), - ServiceDescriptor.Transient, OpenIdConnectOptionsConfiguration>(), - - // Built-in initializers: - ServiceDescriptor.Singleton, OpenIdConnectPostConfigureOptions>(), - }); + services.TryAddEnumerable( + new[] + { + // Orchard-specific initializers. + ServiceDescriptor.Transient, AzureADOptionsConfiguration>(), + ServiceDescriptor.Transient, AzureADOptionsConfiguration>(), + ServiceDescriptor.Transient, AzureADOptionsConfiguration>(), + ServiceDescriptor.Transient, OpenIdConnectOptionsConfiguration>(), + // Built-in initializers: + ServiceDescriptor.Singleton, OpenIdConnectPostConfigureOptions>(), + } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Permissions.cs index 8bee6617d03..6cd6a3e92ce 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Permissions.cs @@ -6,23 +6,11 @@ namespace OrchardCore.Microsoft.Authentication; public class Permissions : IPermissionProvider { - public static readonly Permission ManageMicrosoftAuthentication - = new("ManageMicrosoftAuthentication", "Manage Microsoft Authentication settings"); + public static readonly Permission ManageMicrosoftAuthentication = new("ManageMicrosoftAuthentication", "Manage Microsoft Authentication settings"); - private readonly IEnumerable _allPermissions = - [ - ManageMicrosoftAuthentication, - ]; + private readonly IEnumerable _allPermissions = [ManageMicrosoftAuthentication,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Services/AzureADService.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Services/AzureADService.cs index 514cadd4dcc..e9b63577639 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Services/AzureADService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Services/AzureADService.cs @@ -14,9 +14,7 @@ public class AzureADService : IAzureADService private readonly ISiteService _siteService; protected readonly IStringLocalizer S; - public AzureADService( - ISiteService siteService, - IStringLocalizer stringLocalizer) + public AzureADService(ISiteService siteService, IStringLocalizer stringLocalizer) { _siteService = siteService; S = stringLocalizer; @@ -39,13 +37,16 @@ public async Task UpdateSettingsAsync(AzureADSettings settings) ArgumentNullException.ThrowIfNull(settings); var container = await _siteService.LoadSiteSettingsAsync(); - container.Alter(nameof(AzureADSettings), aspect => - { - aspect.AppId = settings.AppId; - aspect.CallbackPath = settings.CallbackPath; - aspect.DisplayName = settings.DisplayName; - aspect.TenantId = settings.TenantId; - }); + container.Alter( + nameof(AzureADSettings), + aspect => + { + aspect.AppId = settings.AppId; + aspect.CallbackPath = settings.CallbackPath; + aspect.DisplayName = settings.DisplayName; + aspect.TenantId = settings.TenantId; + } + ); await _siteService.UpdateSiteSettingsAsync(container); } diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Services/MicrosoftAccountService.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Services/MicrosoftAccountService.cs index 2424d0f4f3e..14ddc2dd63b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Services/MicrosoftAccountService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/Services/MicrosoftAccountService.cs @@ -14,9 +14,7 @@ public class MicrosoftAccountService : IMicrosoftAccountService private readonly ISiteService _siteService; protected readonly IStringLocalizer S; - public MicrosoftAccountService( - ISiteService siteService, - IStringLocalizer stringLocalizer) + public MicrosoftAccountService(ISiteService siteService, IStringLocalizer stringLocalizer) { _siteService = siteService; S = stringLocalizer; @@ -39,12 +37,15 @@ public async Task UpdateSettingsAsync(MicrosoftAccountSettings settings) ArgumentNullException.ThrowIfNull(settings); var container = await _siteService.LoadSiteSettingsAsync(); - container.Alter(nameof(MicrosoftAccountSettings), aspect => - { - aspect.AppId = settings.AppId; - aspect.AppSecret = settings.AppSecret; - aspect.CallbackPath = settings.CallbackPath; - }); + container.Alter( + nameof(MicrosoftAccountSettings), + aspect => + { + aspect.AppId = settings.AppId; + aspect.AppSecret = settings.AppSecret; + aspect.CallbackPath = settings.CallbackPath; + } + ); await _siteService.UpdateSiteSettingsAsync(container); } diff --git a/src/OrchardCore.Modules/OrchardCore.MiniProfiler/CurrentDbProfiler.cs b/src/OrchardCore.Modules/OrchardCore.MiniProfiler/CurrentDbProfiler.cs index 10242b2c8e1..07f45deda0f 100644 --- a/src/OrchardCore.Modules/OrchardCore.MiniProfiler/CurrentDbProfiler.cs +++ b/src/OrchardCore.Modules/OrchardCore.MiniProfiler/CurrentDbProfiler.cs @@ -8,6 +8,7 @@ namespace OrchardCore.MiniProfiler internal class CurrentDbProfiler : IDbProfiler { private Func GetProfiler { get; } + public CurrentDbProfiler(Func getProfiler) => GetProfiler = getProfiler; public bool IsActive => ((IDbProfiler)StackExchange.Profiling.MiniProfiler.Current)?.IsActive ?? false; @@ -15,13 +16,10 @@ internal class CurrentDbProfiler : IDbProfiler public void ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader) => GetProfiler()?.ExecuteFinish(profiledDbCommand, executeType, reader); - public void ExecuteStart(IDbCommand profiledDbCommand, SqlExecuteType executeType) => - GetProfiler()?.ExecuteStart(profiledDbCommand, executeType); + public void ExecuteStart(IDbCommand profiledDbCommand, SqlExecuteType executeType) => GetProfiler()?.ExecuteStart(profiledDbCommand, executeType); - public void OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception exception) => - GetProfiler()?.OnError(profiledDbCommand, executeType, exception); + public void OnError(IDbCommand profiledDbCommand, SqlExecuteType executeType, Exception exception) => GetProfiler()?.OnError(profiledDbCommand, executeType, exception); - public void ReaderFinish(IDataReader reader) => - GetProfiler()?.ReaderFinish(reader); + public void ReaderFinish(IDataReader reader) => GetProfiler()?.ReaderFinish(reader); } } diff --git a/src/OrchardCore.Modules/OrchardCore.MiniProfiler/MiniProfilerFilter.cs b/src/OrchardCore.Modules/OrchardCore.MiniProfiler/MiniProfilerFilter.cs index 0e969bc221b..034ea92de19 100644 --- a/src/OrchardCore.Modules/OrchardCore.MiniProfiler/MiniProfilerFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.MiniProfiler/MiniProfilerFilter.cs @@ -14,10 +14,7 @@ public class MiniProfilerFilter : IAsyncResultFilter private readonly IShapeFactory _shapeFactory; private readonly IAuthorizationService _authorizationService; - public MiniProfilerFilter( - ILayoutAccessor layoutAccessor, - IShapeFactory shapeFactory, - IAuthorizationService authorizationService) + public MiniProfilerFilter(ILayoutAccessor layoutAccessor, IShapeFactory shapeFactory, IAuthorizationService authorizationService) { _layoutAccessor = layoutAccessor; _shapeFactory = shapeFactory; @@ -29,12 +26,9 @@ public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultE var viewMiniProfilerOnFrontEnd = await _authorizationService.AuthorizeAsync(context.HttpContext.User, Permissions.ViewMiniProfilerOnFrontEnd); var viewMiniProfilerOnBackEnd = await _authorizationService.AuthorizeAsync(context.HttpContext.User, Permissions.ViewMiniProfilerOnBackEnd); if ( - context.IsViewOrPageResult() && - ( - (viewMiniProfilerOnFrontEnd && !AdminAttribute.IsApplied(context.HttpContext)) || - (viewMiniProfilerOnBackEnd && AdminAttribute.IsApplied(context.HttpContext)) - ) - ) + context.IsViewOrPageResult() + && ((viewMiniProfilerOnFrontEnd && !AdminAttribute.IsApplied(context.HttpContext)) || (viewMiniProfilerOnBackEnd && AdminAttribute.IsApplied(context.HttpContext))) + ) { var layout = await _layoutAccessor.GetLayoutAsync(); var footerZone = layout.Zones["Footer"]; diff --git a/src/OrchardCore.Modules/OrchardCore.MiniProfiler/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.MiniProfiler/Permissions.cs index 66e56cd09eb..ae1d802f9ea 100644 --- a/src/OrchardCore.Modules/OrchardCore.MiniProfiler/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.MiniProfiler/Permissions.cs @@ -9,21 +9,9 @@ public class Permissions : IPermissionProvider public static readonly Permission ViewMiniProfilerOnFrontEnd = new("ViewMiniProfilerOnFrontEnd", "View Mini Profiler widget on front end pages"); public static readonly Permission ViewMiniProfilerOnBackEnd = new("ViewMiniProfilerOnBackEnd", "View Mini Profiler widget on back end pages"); - private readonly IEnumerable _allPermissions = - [ - ViewMiniProfilerOnFrontEnd, - ViewMiniProfilerOnBackEnd, - ]; + private readonly IEnumerable _allPermissions = [ViewMiniProfilerOnFrontEnd, ViewMiniProfilerOnBackEnd,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.MiniProfiler/Startup.cs b/src/OrchardCore.Modules/OrchardCore.MiniProfiler/Startup.cs index a1b1e935c46..1583c710eea 100644 --- a/src/OrchardCore.Modules/OrchardCore.MiniProfiler/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.MiniProfiler/Startup.cs @@ -17,10 +17,12 @@ public class Startup : StartupBase public override void ConfigureServices(IServiceCollection services) { - services.Configure((options) => - { - options.Filters.Add(typeof(MiniProfilerFilter)); - }); + services.Configure( + (options) => + { + options.Filters.Add(typeof(MiniProfilerFilter)); + } + ); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Mvc.HelloWorld/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Mvc.HelloWorld/Manifest.cs index 6eb1d6f185e..7778982f842 100644 --- a/src/OrchardCore.Modules/OrchardCore.Mvc.HelloWorld/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Mvc.HelloWorld/Manifest.cs @@ -1,5 +1,3 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Mvc HelloWorld" -)] +[assembly: Module(Name = "Mvc HelloWorld")] diff --git a/src/OrchardCore.Modules/OrchardCore.Mvc.HelloWorld/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Mvc.HelloWorld/Startup.cs index 4e5b05db420..f187f8b10f0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Mvc.HelloWorld/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Mvc.HelloWorld/Startup.cs @@ -22,13 +22,7 @@ public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilde throw new Exception(":("); } - routes.MapAreaControllerRoute - ( - name: "Home", - areaName: "OrchardCore.Mvc.HelloWorld", - pattern: "", - defaults: new { controller = "Home", action = "Index" } - ); + routes.MapAreaControllerRoute(name: "Home", areaName: "OrchardCore.Mvc.HelloWorld", pattern: "", defaults: new { controller = "Home", action = "Index" }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Navigation/NavigationShapes.cs b/src/OrchardCore.Modules/OrchardCore.Navigation/NavigationShapes.cs index d984364033c..95299f31a8f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Navigation/NavigationShapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.Navigation/NavigationShapes.cs @@ -14,7 +14,8 @@ public class NavigationShapes : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("Navigation") + builder + .Describe("Navigation") .OnDisplaying(displaying => { var menu = displaying.Shape; @@ -73,7 +74,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("NavigationItem") + builder + .Describe("NavigationItem") .OnDisplaying(displaying => { var menuItem = displaying.Shape; @@ -88,7 +90,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) menuItem.Metadata.Alternates.Add("NavigationItem__" + encodedMenuName + "__level__" + level); }); - builder.Describe("NavigationItemLink") + builder + .Describe("NavigationItemLink") .OnDisplaying(displaying => { var menuItem = displaying.Shape; diff --git a/src/OrchardCore.Modules/OrchardCore.Navigation/PagerShapesTableProvider.cs b/src/OrchardCore.Modules/OrchardCore.Navigation/PagerShapesTableProvider.cs index 53506f88f5b..b9955f2729d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Navigation/PagerShapesTableProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Navigation/PagerShapesTableProvider.cs @@ -21,7 +21,8 @@ public class PagerShapesTableProvider : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("Pager") + builder + .Describe("Pager") .OnCreated(created => { // Initializes the common properties of a Pager shape @@ -34,10 +35,12 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) if (displaying.Shape.TryGetProperty("PagerId", out string pagerId) && !string.IsNullOrEmpty(pagerId)) { displaying.Shape.Metadata.Alternates.Add("Pager__" + pagerId.EncodeAlternateElement()); - }; + } + ; }); - builder.Describe("PagerSlim") + builder + .Describe("PagerSlim") .OnCreated(created => { // Initializes the common properties of a Pager shape @@ -50,10 +53,12 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) if (displaying.Shape.TryGetProperty("PagerId", out string pagerId) && !string.IsNullOrEmpty(pagerId)) { displaying.Shape.Metadata.Alternates.Add("Pager__" + pagerId.EncodeAlternateElement()); - }; + } + ; }); - builder.Describe("Pager_Gap") + builder + .Describe("Pager_Gap") .OnDisplaying(displaying => { var shape = displaying.Shape; @@ -64,7 +69,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("Pager_First") + builder + .Describe("Pager_First") .OnDisplaying(displaying => { var shape = displaying.Shape; @@ -75,7 +81,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("Pager_Previous") + builder + .Describe("Pager_Previous") .OnDisplaying(displaying => { var shape = displaying.Shape; @@ -86,7 +93,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("Pager_Next") + builder + .Describe("Pager_Next") .OnDisplaying(displaying => { var shape = displaying.Shape; @@ -97,7 +105,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("Pager_Last") + builder + .Describe("Pager_Last") .OnDisplaying(displaying => { var shape = displaying.Shape; @@ -108,7 +117,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("Pager_CurrentPage") + builder + .Describe("Pager_CurrentPage") .OnDisplaying(displaying => { var shape = displaying.Shape; @@ -119,7 +129,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("Pager_Links") + builder + .Describe("Pager_Links") .OnDisplaying(displaying => { if (displaying.Shape.TryGetProperty("PagerId", out string pagerId)) @@ -142,7 +153,11 @@ public PagerShapes(IStringLocalizer localizer) } [Shape] - public async Task Pager_Links(Shape shape, DisplayContext displayContext, IShapeFactory shapeFactory, IHtmlHelper Html, + public async Task Pager_Links( + Shape shape, + DisplayContext displayContext, + IShapeFactory shapeFactory, + IHtmlHelper Html, string PagerId, int Page, int PageSize, @@ -154,7 +169,8 @@ public async Task Pager_Links(Shape shape, DisplayContext displayC object LastText, object GapText, bool ShowNext, - Dictionary UrlParams) + Dictionary UrlParams + ) { var noFollow = shape.Attributes.ContainsKey("rel") && shape.Attributes["rel"] == "no-follow"; var currentPage = Page; @@ -202,13 +218,18 @@ public async Task Pager_Links(Shape shape, DisplayContext displayC } // first - var firstItem = await shapeFactory.CreateAsync("Pager_First", Arguments.From(new - { - Value = firstText, - RouteValues = new RouteValueDictionary(routeData), - Pager = shape, - Disabled = Page < 2 - })); + var firstItem = await shapeFactory.CreateAsync( + "Pager_First", + Arguments.From( + new + { + Value = firstText, + RouteValues = new RouteValueDictionary(routeData), + Pager = shape, + Disabled = Page < 2 + } + ) + ); if (noFollow) { @@ -223,13 +244,18 @@ public async Task Pager_Links(Shape shape, DisplayContext displayC routeData[pageKey] = currentPage - 1; } - var previousItem = await shapeFactory.CreateAsync("Pager_Previous", Arguments.From(new - { - Value = previousText, - RouteValues = new RouteValueDictionary(routeData), - Pager = shape, - Disabled = Page < 2 - })); + var previousItem = await shapeFactory.CreateAsync( + "Pager_Previous", + Arguments.From( + new + { + Value = previousText, + RouteValues = new RouteValueDictionary(routeData), + Pager = shape, + Disabled = Page < 2 + } + ) + ); if (noFollow) { @@ -241,11 +267,7 @@ public async Task Pager_Links(Shape shape, DisplayContext displayC // gap at the beginning of the pager if (firstPage > 1 && numberOfPagesToShow > 0) { - await shape.AddAsync(await shapeFactory.CreateAsync("Pager_Gap", Arguments.From(new - { - Value = gapText, - Pager = shape - }))); + await shape.AddAsync(await shapeFactory.CreateAsync("Pager_Gap", Arguments.From(new { Value = gapText, Pager = shape }))); } // page numbers @@ -265,12 +287,17 @@ await shape.AddAsync(await shapeFactory.CreateAsync("Pager_Gap", Arguments.From( if (p == currentPage) { - var currentPageItem = await shapeFactory.CreateAsync("Pager_CurrentPage", Arguments.From(new - { - Value = p, - RouteValues = new RouteValueDictionary(routeData), - Pager = shape - })); + var currentPageItem = await shapeFactory.CreateAsync( + "Pager_CurrentPage", + Arguments.From( + new + { + Value = p, + RouteValues = new RouteValueDictionary(routeData), + Pager = shape + } + ) + ); if (noFollow) { @@ -281,12 +308,17 @@ await shape.AddAsync(await shapeFactory.CreateAsync("Pager_Gap", Arguments.From( } else { - var pagerItem = await shapeFactory.CreateAsync("Pager_Link", Arguments.From(new - { - Value = p, - RouteValues = new RouteValueDictionary(routeData), - Pager = shape - })); + var pagerItem = await shapeFactory.CreateAsync( + "Pager_Link", + Arguments.From( + new + { + Value = p, + RouteValues = new RouteValueDictionary(routeData), + Pager = shape + } + ) + ); if (p > currentPage) { @@ -305,22 +337,23 @@ await shape.AddAsync(await shapeFactory.CreateAsync("Pager_Gap", Arguments.From( // gap at the end of the pager if (lastPage < totalPageCount && numberOfPagesToShow > 0) { - await shape.AddAsync(await shapeFactory.CreateAsync("Pager_Gap", Arguments.From(new - { - Value = gapText, - Pager = shape - }))); + await shape.AddAsync(await shapeFactory.CreateAsync("Pager_Gap", Arguments.From(new { Value = gapText, Pager = shape }))); } // Next routeData[pageKey] = Page + 1; - var pagerNextItem = await shapeFactory.CreateAsync("Pager_Next", Arguments.From(new - { - Value = nextText, - RouteValues = new RouteValueDictionary(routeData), - Pager = shape, - Disabled = Page >= totalPageCount && !ShowNext - })); + var pagerNextItem = await shapeFactory.CreateAsync( + "Pager_Next", + Arguments.From( + new + { + Value = nextText, + RouteValues = new RouteValueDictionary(routeData), + Pager = shape, + Disabled = Page >= totalPageCount && !ShowNext + } + ) + ); if (noFollow) { @@ -331,13 +364,18 @@ await shape.AddAsync(await shapeFactory.CreateAsync("Pager_Gap", Arguments.From( // Last routeData[pageKey] = totalPageCount; - var pagerLastItem = await shapeFactory.CreateAsync("Pager_Last", Arguments.From(new - { - Value = lastText, - RouteValues = new RouteValueDictionary(routeData), - Pager = shape, - Disabled = Page >= totalPageCount - })); + var pagerLastItem = await shapeFactory.CreateAsync( + "Pager_Last", + Arguments.From( + new + { + Value = lastText, + RouteValues = new RouteValueDictionary(routeData), + Pager = shape, + Disabled = Page >= totalPageCount + } + ) + ); if (noFollow) { @@ -359,12 +397,17 @@ public Task Pager(Shape shape, DisplayContext displayContext) } [Shape] - public async Task PagerSlim(Shape shape, DisplayContext displayContext, IShapeFactory shapeFactory, IHtmlHelper Html, + public async Task PagerSlim( + Shape shape, + DisplayContext displayContext, + IShapeFactory shapeFactory, + IHtmlHelper Html, object PreviousText, object NextText, string PreviousClass, string NextClass, - Dictionary UrlParams) + Dictionary UrlParams + ) { var noFollow = shape.Attributes.ContainsKey("rel") && shape.Attributes["rel"] == "no-follow"; var previousText = PreviousText ?? S["<"]; @@ -380,19 +423,21 @@ public async Task PagerSlim(Shape shape, DisplayContext displayCon if (shape.TryGetProperty("Before", out string before)) { - var beforeRouteData = new RouteValueDictionary(routeData) - { - ["before"] = before - }; + var beforeRouteData = new RouteValueDictionary(routeData) { ["before"] = before }; beforeRouteData.Remove("after"); - var previousItem = await shapeFactory.CreateAsync("Pager_Previous", Arguments.From(new - { - Value = previousText, - RouteValues = beforeRouteData, - Pager = shape - })); + var previousItem = await shapeFactory.CreateAsync( + "Pager_Previous", + Arguments.From( + new + { + Value = previousText, + RouteValues = beforeRouteData, + Pager = shape + } + ) + ); if (noFollow) { @@ -409,19 +454,21 @@ public async Task PagerSlim(Shape shape, DisplayContext displayCon if (shape.TryGetProperty("After", out string after)) { - var afterRouteData = new RouteValueDictionary(routeData) - { - ["after"] = after - }; + var afterRouteData = new RouteValueDictionary(routeData) { ["after"] = after }; afterRouteData.Remove("before"); - var nextItem = await shapeFactory.CreateAsync("Pager_Next", Arguments.From(new - { - Value = nextText, - RouteValues = afterRouteData, - Pager = shape - })); + var nextItem = await shapeFactory.CreateAsync( + "Pager_Next", + Arguments.From( + new + { + Value = nextText, + RouteValues = afterRouteData, + Pager = shape + } + ) + ); if (noFollow) { diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyContentOwnerTask.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyContentOwnerTask.cs index e134a2b5ffb..b853c304c4a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyContentOwnerTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyContentOwnerTask.cs @@ -18,17 +18,14 @@ public class NotifyContentOwnerTask : NotifyUserTaskActivity logger, - IStringLocalizer localizer, - ISession session - ) : base(notificationCoordinator, - expressionEvaluator, - htmlEncoder, - logger, - localizer) + INotificationService notificationCoordinator, + IWorkflowExpressionEvaluator expressionEvaluator, + HtmlEncoder htmlEncoder, + ILogger logger, + IStringLocalizer localizer, + ISession session + ) + : base(notificationCoordinator, expressionEvaluator, htmlEncoder, logger, localizer) { _session = session; } @@ -37,9 +34,7 @@ ISession session protected override async Task> GetUsersAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - if (workflowContext.Input.TryGetValue("ContentItem", out var obj) - && obj is ContentItem contentItem - && !string.IsNullOrEmpty(contentItem.Owner)) + if (workflowContext.Input.TryGetValue("ContentItem", out var obj) && obj is ContentItem contentItem && !string.IsNullOrEmpty(contentItem.Owner)) { if (workflowContext.Input.TryGetValue("Owner", out var ownerObject) && ownerObject is User user && user.IsEnabled) { diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyUserTask.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyUserTask.cs index c4a24145aa8..3a08f38b647 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyUserTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyUserTask.cs @@ -14,18 +14,13 @@ namespace OrchardCore.Notifications.Activities; public class NotifyUserTask : NotifyUserTaskActivity { public NotifyUserTask( - INotificationService notificationCoordinator, - IWorkflowExpressionEvaluator expressionEvaluator, - HtmlEncoder htmlEncoder, - ILogger logger, - IStringLocalizer localizer - ) : base(notificationCoordinator, - expressionEvaluator, - htmlEncoder, - logger, - localizer) - { - } + INotificationService notificationCoordinator, + IWorkflowExpressionEvaluator expressionEvaluator, + HtmlEncoder htmlEncoder, + ILogger logger, + IStringLocalizer localizer + ) + : base(notificationCoordinator, expressionEvaluator, htmlEncoder, logger, localizer) { } public override LocalizedString DisplayText => S["Notify User Task"]; diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyUserTaskActivity.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyUserTaskActivity.cs index 3cdc7730e94..924dcd0e656 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyUserTaskActivity.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Activities/NotifyUserTaskActivity.cs @@ -62,8 +62,8 @@ public bool IsHtmlPreferred set => SetProperty(value); } - public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) - => Outcomes(S["Done"], S["Failed"], S["Failed: no user found"]); + public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) => + Outcomes(S["Done"], S["Failed"], S["Failed: no user found"]); public override async Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { @@ -104,24 +104,24 @@ protected virtual async Task GetMessageAsync(WorkflowExecu }; } - abstract public override string Name { get; } + public abstract override string Name { get; } - abstract public override LocalizedString DisplayText { get; } + public abstract override LocalizedString DisplayText { get; } - abstract protected Task> GetUsersAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext); + protected abstract Task> GetUsersAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext); } -public abstract class NotifyUserTaskActivity : NotifyUserTaskActivity where TActivity : ITask +public abstract class NotifyUserTaskActivity : NotifyUserTaskActivity + where TActivity : ITask { protected NotifyUserTaskActivity( INotificationService notificationService, IWorkflowExpressionEvaluator expressionEvaluator, HtmlEncoder htmlEncoder, ILogger logger, - IStringLocalizer localizer) - : base(notificationService, expressionEvaluator, htmlEncoder, logger, localizer) - { - } + IStringLocalizer localizer + ) + : base(notificationService, expressionEvaluator, htmlEncoder, logger, localizer) { } // The technical name of the activity. Within a workflow definition, activities make use of this name. public override string Name => typeof(TActivity).Name; diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Controllers/AdminController.cs index 4f3e00846a2..d1a1a354dc4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Controllers/AdminController.cs @@ -46,7 +46,6 @@ public class AdminController : Controller, IUpdateModel public AdminController( IAuthorizationService authorizationService, ISession session, - IOptions pagerOptions, IDisplayManager notificationDisplayManager, INotificationsAdminListQueryService notificationsAdminListQueryService, @@ -55,7 +54,8 @@ public AdminController( IClock clock, IShapeFactory shapeFactory, IStringLocalizer stringLocalizer, - IHtmlLocalizer htmlLocalizer) + IHtmlLocalizer htmlLocalizer + ) { _authorizationService = authorizationService; _session = session; @@ -75,7 +75,8 @@ public AdminController( public async Task List( [ModelBinder(BinderType = typeof(NotificationFilterEngineModelBinder), Name = "q")] QueryFilterResult queryFilterResult, PagerParameters pagerParameters, - ListNotificationOptions options) + ListNotificationOptions options + ) { if (!await _authorizationService.AuthorizeAsync(HttpContext.User, NotificationPermissions.ManageNotifications)) { @@ -91,16 +92,8 @@ public async Task List( // Populate route values to maintain previous route data when generating page links. options.RouteValues.TryAdd("q", options.FilterResult.ToString()); - options.Statuses = - [ - new(S["Read"], nameof(NotificationStatus.Read)), - new(S["Unread"], nameof(NotificationStatus.Unread)), - ]; - options.Sorts = - [ - new(S["Recently created"], nameof(NotificationOrder.Latest)), - new(S["Previously created"], nameof(NotificationOrder.Oldest)), - ]; + options.Statuses = [new(S["Read"], nameof(NotificationStatus.Read)), new(S["Unread"], nameof(NotificationStatus.Unread)),]; + options.Sorts = [new(S["Recently created"], nameof(NotificationOrder.Latest)), new(S["Previously created"], nameof(NotificationOrder.Oldest)),]; options.BulkActions = [ new(S["Mark as read"], nameof(NotificationBulkAction.Read)), @@ -132,13 +125,16 @@ public async Task List( var header = await _notificationOptionsDisplayManager.BuildEditorAsync(options, this, false, string.Empty, string.Empty); - var shapeViewModel = await _shapeFactory.CreateAsync("NotificationsAdminList", viewModel => - { - viewModel.Options = options; - viewModel.Header = header; - viewModel.Notifications = notificationSummaries; - viewModel.Pager = pagerShape; - }); + var shapeViewModel = await _shapeFactory.CreateAsync( + "NotificationsAdminList", + viewModel => + { + viewModel.Options = options; + viewModel.Header = header; + viewModel.Notifications = notificationSummaries; + viewModel.Pager = pagerShape; + } + ); return View(shapeViewModel); } @@ -173,7 +169,12 @@ public async Task ListPOST(ListNotificationOptions options, IEnume if (itemIds?.Count() > 0) { - var notifications = await _session.Query(x => x.UserId == CurrentUserId() && x.NotificationId.IsIn(itemIds), collection: NotificationConstants.NotificationCollection).ListAsync(); + var notifications = await _session + .Query( + x => x.UserId == CurrentUserId() && x.NotificationId.IsIn(itemIds), + collection: NotificationConstants.NotificationCollection + ) + .ListAsync(); var utcNow = _clock.UtcNow; var counter = 0; @@ -246,7 +247,9 @@ public async Task ReadAll(string returnUrl) return Forbid(); } - var notifications = await _session.Query(x => x.UserId == CurrentUserId() && !x.IsRead, collection: NotificationConstants.NotificationCollection).ListAsync(); + var notifications = await _session + .Query(x => x.UserId == CurrentUserId() && !x.IsRead, collection: NotificationConstants.NotificationCollection) + .ListAsync(); var utcNow = _clock.UtcNow; var counter = 0; @@ -279,7 +282,12 @@ public async Task Toggle(string notificationId, bool markAsRead, if (!string.IsNullOrWhiteSpace(notificationId)) { - var notification = await _session.Query(x => x.UserId == CurrentUserId() && x.NotificationId == notificationId && x.IsRead != markAsRead, collection: NotificationConstants.NotificationCollection).FirstOrDefaultAsync(); + var notification = await _session + .Query( + x => x.UserId == CurrentUserId() && x.NotificationId == notificationId && x.IsRead != markAsRead, + collection: NotificationConstants.NotificationCollection + ) + .FirstOrDefaultAsync(); if (notification != null) { @@ -314,7 +322,12 @@ public async Task Delete(string notificationId, string returnUrl) if (!string.IsNullOrWhiteSpace(notificationId)) { - var notification = await _session.Query(x => x.UserId == CurrentUserId() && x.NotificationId == notificationId, collection: NotificationConstants.NotificationCollection).FirstOrDefaultAsync(); + var notification = await _session + .Query( + x => x.UserId == CurrentUserId() && x.NotificationId == notificationId, + collection: NotificationConstants.NotificationCollection + ) + .FirstOrDefaultAsync(); if (notification != null) { @@ -325,11 +338,8 @@ public async Task Delete(string notificationId, string returnUrl) return RedirectTo(returnUrl); } - private IActionResult RedirectTo(string returnUrl) - => !string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) - ? (IActionResult)this.LocalRedirect(returnUrl, true) - : RedirectToAction(nameof(List)); + private IActionResult RedirectTo(string returnUrl) => + !string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) ? (IActionResult)this.LocalRedirect(returnUrl, true) : RedirectToAction(nameof(List)); - private string CurrentUserId() - => User.FindFirstValue(ClaimTypes.NameIdentifier); + private string CurrentUserId() => User.FindFirstValue(ClaimTypes.NameIdentifier); } diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Controllers/ApiController.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Controllers/ApiController.cs index ff78681c39c..b0ac19f8542 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Controllers/ApiController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Controllers/ApiController.cs @@ -21,10 +21,7 @@ public class ApiController : Controller private readonly YesSql.ISession _session; private readonly IClock _clock; - public ApiController( - IAuthorizationService authorizationService, - YesSql.ISession session, - IClock clock) + public ApiController(IAuthorizationService authorizationService, YesSql.ISession session, IClock clock) { _authorizationService = authorizationService; _session = session; @@ -44,7 +41,12 @@ public async Task Read(ReadNotificationViewModel viewModel) return Forbid(); } - var notification = await _session.Query(x => x.NotificationId == viewModel.MessageId && x.UserId == CurrentUserId(), collection: NotificationConstants.NotificationCollection).FirstOrDefaultAsync(); + var notification = await _session + .Query( + x => x.NotificationId == viewModel.MessageId && x.UserId == CurrentUserId(), + collection: NotificationConstants.NotificationCollection + ) + .FirstOrDefaultAsync(); if (notification == null) { @@ -64,12 +66,8 @@ public async Task Read(ReadNotificationViewModel viewModel) await _session.SaveAsync(notification, collection: NotificationConstants.NotificationCollection); } - return Ok(new - { - messageId = viewModel.MessageId, - updated, - }); + return Ok(new { messageId = viewModel.MessageId, updated, }); } - private string CurrentUserId() - => User.FindFirstValue(ClaimTypes.NameIdentifier); + + private string CurrentUserId() => User.FindFirstValue(ClaimTypes.NameIdentifier); } diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/ListNotificationOptionsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/ListNotificationOptionsDisplayDriver.cs index 0f9a8c60bc8..d4007a991f9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/ListNotificationOptionsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/ListNotificationOptionsDisplayDriver.cs @@ -17,12 +17,9 @@ protected override void BuildPrefix(ListNotificationOptions model, string htmlFi public override IDisplayResult Display(ListNotificationOptions model) { return Combine( - Initialize("NotificationsAdminListBulkActions", m => BuildOptionsViewModel(m, model)) - .Location("BulkActions", "Content:10"), - View("NotificationsAdminFilters_Thumbnail__Status", model) - .Location("Thumbnail", "Content:30"), - View("NotificationsAdminFilters_Thumbnail__Sort", model) - .Location("Thumbnail", "Content:40") + Initialize("NotificationsAdminListBulkActions", m => BuildOptionsViewModel(m, model)).Location("BulkActions", "Content:10"), + View("NotificationsAdminFilters_Thumbnail__Status", model).Location("Thumbnail", "Content:30"), + View("NotificationsAdminFilters_Thumbnail__Sort", model).Location("Thumbnail", "Content:40") ); } @@ -31,18 +28,12 @@ public override IDisplayResult Edit(ListNotificationOptions model) model.FilterResult.MapTo(model); return Combine( - Initialize("NotificationsAdminListBulkActions", m => BuildOptionsViewModel(m, model)) - .Location("BulkActions", "Content:10"), - Initialize("NotificationsAdminListSearch", m => BuildOptionsViewModel(m, model)) - .Location("Search:10"), - Initialize("NotificationsAdminListActionBarButtons", m => BuildOptionsViewModel(m, model)) - .Location("ActionBarButtons:10"), - Initialize("NotificationsAdminListSummary", m => BuildOptionsViewModel(m, model)) - .Location("Summary:10"), - Initialize("NotificationsAdminListFilters", m => BuildOptionsViewModel(m, model)) - .Location("Actions:10.1"), - Initialize("NotificationsAdminList_Fields_BulkActions", m => BuildOptionsViewModel(m, model)) - .Location("Actions:10.1") + Initialize("NotificationsAdminListBulkActions", m => BuildOptionsViewModel(m, model)).Location("BulkActions", "Content:10"), + Initialize("NotificationsAdminListSearch", m => BuildOptionsViewModel(m, model)).Location("Search:10"), + Initialize("NotificationsAdminListActionBarButtons", m => BuildOptionsViewModel(m, model)).Location("ActionBarButtons:10"), + Initialize("NotificationsAdminListSummary", m => BuildOptionsViewModel(m, model)).Location("Summary:10"), + Initialize("NotificationsAdminListFilters", m => BuildOptionsViewModel(m, model)).Location("Actions:10.1"), + Initialize("NotificationsAdminList_Fields_BulkActions", m => BuildOptionsViewModel(m, model)).Location("Actions:10.1") ); } diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotificationDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotificationDisplayDriver.cs index d2ff2897a82..1ebc3156a2c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotificationDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotificationDisplayDriver.cs @@ -11,12 +11,9 @@ public override IDisplayResult Display(Notification notification) { var results = new List() { - Shape("NotificationsMeta_SummaryAdmin", new NotificationViewModel(notification)) - .Location("SummaryAdmin", "Meta:20"), - Shape("NotificationsActions_SummaryAdmin", new NotificationViewModel(notification)) - .Location("SummaryAdmin", "Actions:5"), - Shape("NotificationsButtonActions_SummaryAdmin", new NotificationViewModel(notification)) - .Location("SummaryAdmin", "ActionsMenu:10"), + Shape("NotificationsMeta_SummaryAdmin", new NotificationViewModel(notification)).Location("SummaryAdmin", "Meta:20"), + Shape("NotificationsActions_SummaryAdmin", new NotificationViewModel(notification)).Location("SummaryAdmin", "Actions:5"), + Shape("NotificationsButtonActions_SummaryAdmin", new NotificationViewModel(notification)).Location("SummaryAdmin", "ActionsMenu:10"), }; return Combine(results); diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotificationNavbarDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotificationNavbarDisplayDriver.cs index ef1b8fd1b85..3ffe87edd84 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotificationNavbarDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotificationNavbarDisplayDriver.cs @@ -20,10 +20,7 @@ public class NotificationNavbarDisplayDriver : DisplayDriver private readonly IHttpContextAccessor _httpContextAccessor; private readonly YesSql.ISession _session; - public NotificationNavbarDisplayDriver( - IAuthorizationService authorizationService, - IHttpContextAccessor httpContextAccessor, - YesSql.ISession session) + public NotificationNavbarDisplayDriver(IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor, YesSql.ISession session) { _authorizationService = authorizationService; _httpContextAccessor = httpContextAccessor; @@ -32,20 +29,26 @@ public NotificationNavbarDisplayDriver( public override IDisplayResult Display(Navbar model) { - return Initialize("UserNotificationNavbar", async model => - { - var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); - var notifications = (await _session.Query(x => x.UserId == userId && !x.IsRead, collection: NotificationConstants.NotificationCollection) - .OrderByDescending(x => x.CreatedAtUtc) - .Take(MaxVisibleNotifications + 1) - .ListAsync()).ToList(); + return Initialize( + "UserNotificationNavbar", + async model => + { + var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); + var notifications = ( + await _session + .Query(x => x.UserId == userId && !x.IsRead, collection: NotificationConstants.NotificationCollection) + .OrderByDescending(x => x.CreatedAtUtc) + .Take(MaxVisibleNotifications + 1) + .ListAsync() + ).ToList(); - model.Notifications = notifications; - model.MaxVisibleNotifications = MaxVisibleNotifications; - model.TotalUnread = notifications.Count; - - }).Location("Detail", "Content:9") - .Location("DetailAdmin", "Content:9") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, NotificationPermissions.ManageNotifications)); + model.Notifications = notifications; + model.MaxVisibleNotifications = MaxVisibleNotifications; + model.TotalUnread = notifications.Count; + } + ) + .Location("Detail", "Content:9") + .Location("DetailAdmin", "Content:9") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, NotificationPermissions.ManageNotifications)); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyContentOwnerTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyContentOwnerTaskDisplayDriver.cs index e0803912ae4..a15df66bd79 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyContentOwnerTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyContentOwnerTaskDisplayDriver.cs @@ -2,7 +2,4 @@ namespace OrchardCore.Notifications.Drivers; -public class NotifyContentOwnerTaskDisplayDriver : NotifyUserTaskActivityDisplayDriver -{ - -} +public class NotifyContentOwnerTaskDisplayDriver : NotifyUserTaskActivityDisplayDriver { } diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyUserTaskActivityDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyUserTaskActivityDisplayDriver.cs index 9dcd4a24af4..887e67ede56 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyUserTaskActivityDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyUserTaskActivityDisplayDriver.cs @@ -18,13 +18,19 @@ public class NotifyUserTaskActivityDisplayDriver : Ac public override IDisplayResult Edit(TActivity model) { - return Initialize(EditShapeType, (Func)(viewModel => - { - return EditActivityAsync(model, viewModel); - })).Location("Content"); + return Initialize( + EditShapeType, + (Func)( + viewModel => + { + return EditActivityAsync(model, viewModel); + } + ) + ) + .Location("Content"); } - public async override Task UpdateAsync(TActivity model, IUpdateModel updater) + public override async Task UpdateAsync(TActivity model, IUpdateModel updater) { var viewModel = new TEditViewModel(); if (await updater.TryUpdateModelAsync(viewModel, Prefix)) @@ -80,15 +86,11 @@ protected override void UpdateActivity(TEditViewModel model, TActivity activity) public override IDisplayResult Display(TActivity activity) { return Combine( - Shape($"{typeof(TActivity).Name}_Fields_Thumbnail", new ActivityViewModel(activity)) - .Location("Thumbnail", "Content"), - Shape($"{typeof(TActivity).Name}_Fields_Design", new ActivityViewModel(activity)) - .Location("Design", "Content") + Shape($"{typeof(TActivity).Name}_Fields_Thumbnail", new ActivityViewModel(activity)).Location("Thumbnail", "Content"), + Shape($"{typeof(TActivity).Name}_Fields_Design", new ActivityViewModel(activity)).Location("Design", "Content") ); } } public class NotifyUserTaskActivityDisplayDriver : NotifyUserTaskActivityDisplayDriver - where TActivity : NotifyUserTaskActivity -{ -} + where TActivity : NotifyUserTaskActivity { } diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyUserTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyUserTaskDisplayDriver.cs index 0a48ac77866..5e3c88febe5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyUserTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/NotifyUserTaskDisplayDriver.cs @@ -2,6 +2,4 @@ namespace OrchardCore.Notifications.Drivers; -public class NotifyUserTaskDisplayDriver : NotifyUserTaskActivityDisplayDriver -{ -} +public class NotifyUserTaskDisplayDriver : NotifyUserTaskActivityDisplayDriver { } diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/UserNotificationPreferencesPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/UserNotificationPreferencesPartDisplayDriver.cs index de90879412c..fbff1d33559 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/UserNotificationPreferencesPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Drivers/UserNotificationPreferencesPartDisplayDriver.cs @@ -23,33 +23,35 @@ public UserNotificationPreferencesPartDisplayDriver(IEnumerable EditAsync(User user, UserNotificationPreferencesPart part, BuildEditorContext context) { - var result = Initialize("UserNotificationPreferencesPart_Edit", model => - { - var sortedMethods = new List(part.Methods ?? []); - var optout = part.Optout ?? []; - - // By default the use is opted into all available methods until explicitly optout. - model.Methods = _notificationMethodProviders.Select(x => x.Method).Except(optout).ToArray(); - - model.Optout = optout; - - var availableItems = _notificationMethodProviders - .Select(provider => new SelectListItem(provider.Name, provider.Method)); - - if (sortedMethods.Count > 0) - { - model.AvailableMethods = availableItems - // Sort the methods in the same order they are saved to honor the priority order (i.e., user preferences.) - .OrderBy(x => sortedMethods.IndexOf(x.Value)) - .ThenBy(x => x.Text); - } - else - { - model.AvailableMethods = availableItems.OrderBy(x => x.Text); - } - - }).Location("Content:11") - .RenderWhen(() => Task.FromResult(_notificationMethodProviders.Any())); + var result = Initialize( + "UserNotificationPreferencesPart_Edit", + model => + { + var sortedMethods = new List(part.Methods ?? []); + var optout = part.Optout ?? []; + + // By default the use is opted into all available methods until explicitly optout. + model.Methods = _notificationMethodProviders.Select(x => x.Method).Except(optout).ToArray(); + + model.Optout = optout; + + var availableItems = _notificationMethodProviders.Select(provider => new SelectListItem(provider.Name, provider.Method)); + + if (sortedMethods.Count > 0) + { + model.AvailableMethods = availableItems + // Sort the methods in the same order they are saved to honor the priority order (i.e., user preferences.) + .OrderBy(x => sortedMethods.IndexOf(x.Value)) + .ThenBy(x => x.Text); + } + else + { + model.AvailableMethods = availableItems.OrderBy(x => x.Text); + } + } + ) + .Location("Content:11") + .RenderWhen(() => Task.FromResult(_notificationMethodProviders.Any())); return Task.FromResult(result); } @@ -74,17 +76,13 @@ public override async Task UpdateAsync(User user, UserNotificati } else { - part.Methods = _notificationMethodProviders.OrderBy(provider => provider.Name.ToString()) - .Select(x => x.Method) - .ToArray(); + part.Methods = _notificationMethodProviders.OrderBy(provider => provider.Name.ToString()).Select(x => x.Method).ToArray(); } var selectedMethods = new List(model.Methods ?? []); // Store any method that is not selected as an optout. - part.Optout = _notificationMethodProviders.Where(provider => !selectedMethods.Contains(provider.Method)) - .Select(provider => provider.Method) - .ToArray(); + part.Optout = _notificationMethodProviders.Where(provider => !selectedMethods.Contains(provider.Method)).Select(provider => provider.Method).ToArray(); } return await EditAsync(user, part, context); diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Manifest.cs index b1f8cc1d53d..fa32bf0a435 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Manifest.cs @@ -1,26 +1,13 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] -[assembly: Feature( - Id = "OrchardCore.Notifications", - Name = "Notifications", - Description = "Provides a way to notify users.", - Category = "Notifications" -)] +[assembly: Feature(Id = "OrchardCore.Notifications", Name = "Notifications", Description = "Provides a way to notify users.", Category = "Notifications")] [assembly: Feature( Id = "OrchardCore.Notifications.Email", Name = "Email Notifications", Description = "Provides a way to send email notifications to users.", Category = "Notifications", - Dependencies = - [ - "OrchardCore.Notifications", - "OrchardCore.Email", - ] + Dependencies = ["OrchardCore.Notifications", "OrchardCore.Email",] )] diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/Migrations/NotificationMigrations.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/Migrations/NotificationMigrations.cs index f8015b28709..e57421310ff 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/Migrations/NotificationMigrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/Migrations/NotificationMigrations.cs @@ -10,24 +10,20 @@ public class NotificationMigrations : DataMigration { public async Task CreateAsync() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("NotificationId", column => column.WithLength(26)) - .Column("UserId", column => column.WithLength(26)) - .Column("IsRead") - .Column("ReadAtUtc") - .Column("CreatedAtUtc") - .Column("Content", column => column.WithLength(NotificationConstants.NotificationIndexContentLength)), + await SchemaBuilder.CreateMapIndexTableAsync( + table => + table + .Column("NotificationId", column => column.WithLength(26)) + .Column("UserId", column => column.WithLength(26)) + .Column("IsRead") + .Column("ReadAtUtc") + .Column("CreatedAtUtc") + .Column("Content", column => column.WithLength(NotificationConstants.NotificationIndexContentLength)), collection: NotificationConstants.NotificationCollection ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_NotificationIndex_DocumentId", - "DocumentId", - "NotificationId", - "UserId", - "IsRead", - "CreatedAtUtc", - "Content"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_NotificationIndex_DocumentId", "DocumentId", "NotificationId", "UserId", "IsRead", "CreatedAtUtc", "Content"), collection: NotificationConstants.NotificationCollection ); diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/NotificationPermissionsProvider.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/NotificationPermissionsProvider.cs index 484b84dbc91..4b1d8004641 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/NotificationPermissionsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/NotificationPermissionsProvider.cs @@ -8,45 +8,17 @@ public class NotificationPermissionsProvider : IPermissionProvider { public static readonly Permission ManageNotifications = NotificationPermissions.ManageNotifications; - private readonly IEnumerable _allPermissions = - [ - ManageNotifications, - ]; + private readonly IEnumerable _allPermissions = [ManageNotifications,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Moderator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Author", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Contributor", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Authenticated", - Permissions = _allPermissions, - }, - ]; + [ + new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Editor", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Moderator", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Author", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Contributor", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Authenticated", Permissions = _allPermissions, }, + ]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/ViewModels/NotificationViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/ViewModels/NotificationViewModel.cs index 95a06a3eadd..84915097bac 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/ViewModels/NotificationViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/ViewModels/NotificationViewModel.cs @@ -6,9 +6,7 @@ public class NotificationViewModel : ShapeViewModel { public Notification Notification { get; set; } - public NotificationViewModel() - { - } + public NotificationViewModel() { } public NotificationViewModel(Notification notification) { diff --git a/src/OrchardCore.Modules/OrchardCore.Notifications/ViewModels/UserNotificationMessageViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Notifications/ViewModels/UserNotificationMessageViewModel.cs index 6f2a91ed11b..02cab24f96a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Notifications/ViewModels/UserNotificationMessageViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Notifications/ViewModels/UserNotificationMessageViewModel.cs @@ -18,6 +18,5 @@ public class UserNotificationMessageViewModel public string Url { get; set; } - public bool HasBody() - => !string.IsNullOrWhiteSpace(Body); + public bool HasBody() => !string.IsNullOrWhiteSpace(Body); } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/AdminMenu.cs index 05fa6b6972c..3236b3e5743 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/AdminMenu.cs @@ -10,18 +10,12 @@ namespace OrchardCore.OpenId { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _clientRouteValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", "OrchardCore.OpenId.Client" }, - }; + private static readonly RouteValueDictionary _clientRouteValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", "OrchardCore.OpenId.Client" }, }; private readonly ShellDescriptor _shellDescriptor; protected readonly IStringLocalizer S; - public AdminMenu( - IStringLocalizer localizer, - ShellDescriptor shellDescriptor) + public AdminMenu(IStringLocalizer localizer, ShellDescriptor shellDescriptor) { S = localizer; _shellDescriptor = shellDescriptor; @@ -34,60 +28,87 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder.Add(S["Security"], security => security - .Add(S["OpenID Connect"], S["OpenID Connect"].PrefixPosition(), category => - { - category.AddClass("openid").Id("openid"); - - var features = _shellDescriptor.Features.Select(feature => feature.Id).ToImmutableArray(); - if (features.Contains(OpenIdConstants.Features.Client) || - features.Contains(OpenIdConstants.Features.Server) || - features.Contains(OpenIdConstants.Features.Validation)) - { - category.Add(S["Settings"], "1", settings => - { - if (features.Contains(OpenIdConstants.Features.Client)) + builder.Add( + S["Security"], + security => + security.Add( + S["OpenID Connect"], + S["OpenID Connect"].PrefixPosition(), + category => { - settings.Add(S["Authentication client"], "1", client => client - .Action("Index", "Admin", _clientRouteValues) - .Permission(Permissions.ManageClientSettings) - .LocalNav()); - } + category.AddClass("openid").Id("openid"); - if (features.Contains(OpenIdConstants.Features.Server)) - { - settings.Add(S["Authorization server"], "2", server => server - .Action("Index", "ServerConfiguration", "OrchardCore.OpenId") - .Permission(Permissions.ManageServerSettings) - .LocalNav()); - } + var features = _shellDescriptor.Features.Select(feature => feature.Id).ToImmutableArray(); + if ( + features.Contains(OpenIdConstants.Features.Client) + || features.Contains(OpenIdConstants.Features.Server) + || features.Contains(OpenIdConstants.Features.Validation) + ) + { + category.Add( + S["Settings"], + "1", + settings => + { + if (features.Contains(OpenIdConstants.Features.Client)) + { + settings.Add( + S["Authentication client"], + "1", + client => client.Action("Index", "Admin", _clientRouteValues).Permission(Permissions.ManageClientSettings).LocalNav() + ); + } - if (features.Contains(OpenIdConstants.Features.Validation)) - { - settings.Add(S["Token validation"], "3", validation => validation - .Action("Index", "ValidationConfiguration", "OrchardCore.OpenId") - .Permission(Permissions.ManageValidationSettings) - .LocalNav()); - } - }); - } + if (features.Contains(OpenIdConstants.Features.Server)) + { + settings.Add( + S["Authorization server"], + "2", + server => + server.Action("Index", "ServerConfiguration", "OrchardCore.OpenId").Permission(Permissions.ManageServerSettings).LocalNav() + ); + } - if (features.Contains(OpenIdConstants.Features.Management)) - { - category.Add(S["Management"], "2", management => - { - management.Add(S["Applications"], "1", applications => applications - .Action("Index", "Application", "OrchardCore.OpenId") - .Permission(Permissions.ManageApplications) - .LocalNav()); + if (features.Contains(OpenIdConstants.Features.Validation)) + { + settings.Add( + S["Token validation"], + "3", + validation => + validation + .Action("Index", "ValidationConfiguration", "OrchardCore.OpenId") + .Permission(Permissions.ManageValidationSettings) + .LocalNav() + ); + } + } + ); + } - management.Add(S["Scopes"], "2", applications => applications - .Action("Index", "Scope", "OrchardCore.OpenId") - .Permission(Permissions.ManageScopes) - .LocalNav()); - }); - } - })); + if (features.Contains(OpenIdConstants.Features.Management)) + { + category.Add( + S["Management"], + "2", + management => + { + management.Add( + S["Applications"], + "1", + applications => applications.Action("Index", "Application", "OrchardCore.OpenId").Permission(Permissions.ManageApplications).LocalNav() + ); + + management.Add( + S["Scopes"], + "2", + applications => applications.Action("Index", "Scope", "OrchardCore.OpenId").Permission(Permissions.ManageScopes).LocalNav() + ); + } + ); + } + } + ) + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdClientConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdClientConfiguration.cs index 2184f190d08..53cc8ce4042 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdClientConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdClientConfiguration.cs @@ -16,9 +16,7 @@ namespace OrchardCore.OpenId.Configuration { [Feature(OpenIdConstants.Features.Client)] - public class OpenIdClientConfiguration : - IConfigureOptions, - IConfigureNamedOptions + public class OpenIdClientConfiguration : IConfigureOptions, IConfigureNamedOptions { private readonly IOpenIdClientService _clientService; private readonly IDataProtectionProvider _dataProtectionProvider; @@ -29,7 +27,8 @@ public OpenIdClientConfiguration( IOpenIdClientService clientService, IDataProtectionProvider dataProtectionProvider, ShellSettings shellSettings, - ILogger logger) + ILogger logger + ) { _clientService = clientService; _dataProtectionProvider = dataProtectionProvider; diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdServerConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdServerConfiguration.cs index aad287183dc..8f95ca1ce41 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdServerConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdServerConfiguration.cs @@ -19,19 +19,17 @@ namespace OrchardCore.OpenId.Configuration { [Feature(OpenIdConstants.Features.Server)] - public class OpenIdServerConfiguration : IConfigureOptions, - IConfigureOptions, - IConfigureOptions, - IConfigureNamedOptions + public class OpenIdServerConfiguration + : IConfigureOptions, + IConfigureOptions, + IConfigureOptions, + IConfigureNamedOptions { private readonly IOpenIdServerService _serverService; private readonly ShellSettings _shellSettings; private readonly ILogger _logger; - public OpenIdServerConfiguration( - IOpenIdServerService serverService, - ShellSettings shellSettings, - ILogger logger) + public OpenIdServerConfiguration(IOpenIdServerService serverService, ShellSettings shellSettings, ILogger logger) { _serverService = serverService; _shellSettings = shellSettings; @@ -46,8 +44,7 @@ public void Configure(AuthenticationOptions options) return; } - options.AddScheme( - OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, displayName: null); + options.AddScheme(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, displayName: null); } public void Configure(OpenIddictServerOptions options) @@ -65,8 +62,7 @@ public void Configure(OpenIddictServerOptions options) foreach (var key in _serverService.GetEncryptionKeysAsync().GetAwaiter().GetResult()) { - options.EncryptionCredentials.Add(new EncryptingCredentials(key, - SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512)); + options.EncryptionCredentials.Add(new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512)); } foreach (var key in _serverService.GetSigningKeysAsync().GetAwaiter().GetResult()) @@ -82,38 +78,32 @@ public void Configure(OpenIddictServerOptions options) if (settings.AuthorizationEndpointPath.HasValue) { - options.AuthorizationEndpointUris.Add(new Uri( - settings.AuthorizationEndpointPath.ToUriComponent()[1..], UriKind.Relative)); + options.AuthorizationEndpointUris.Add(new Uri(settings.AuthorizationEndpointPath.ToUriComponent()[1..], UriKind.Relative)); } if (settings.LogoutEndpointPath.HasValue) { - options.LogoutEndpointUris.Add(new Uri( - settings.LogoutEndpointPath.ToUriComponent()[1..], UriKind.Relative)); + options.LogoutEndpointUris.Add(new Uri(settings.LogoutEndpointPath.ToUriComponent()[1..], UriKind.Relative)); } if (settings.TokenEndpointPath.HasValue) { - options.TokenEndpointUris.Add(new Uri( - settings.TokenEndpointPath.ToUriComponent()[1..], UriKind.Relative)); + options.TokenEndpointUris.Add(new Uri(settings.TokenEndpointPath.ToUriComponent()[1..], UriKind.Relative)); } if (settings.UserinfoEndpointPath.HasValue) { - options.UserinfoEndpointUris.Add(new Uri( - settings.UserinfoEndpointPath.ToUriComponent()[1..], UriKind.Relative)); + options.UserinfoEndpointUris.Add(new Uri(settings.UserinfoEndpointPath.ToUriComponent()[1..], UriKind.Relative)); } if (settings.IntrospectionEndpointPath.HasValue) { - options.IntrospectionEndpointUris.Add(new Uri( - settings.IntrospectionEndpointPath.ToUriComponent()[1..], UriKind.Relative)); + options.IntrospectionEndpointUris.Add(new Uri(settings.IntrospectionEndpointPath.ToUriComponent()[1..], UriKind.Relative)); } if (settings.RevocationEndpointPath.HasValue) { - options.RevocationEndpointUris.Add(new Uri( - settings.RevocationEndpointPath.ToUriComponent()[1..], UriKind.Relative)); + options.RevocationEndpointUris.Add(new Uri(settings.RevocationEndpointPath.ToUriComponent()[1..], UriKind.Relative)); } // For now, response types and response modes are not directly @@ -224,8 +214,7 @@ public void Configure(string name, OpenIddictServerAspNetCoreOptions options) options.DisableTransportSecurityRequirement = true; } - public void Configure(OpenIddictServerAspNetCoreOptions options) - => Debug.Fail("This infrastructure method shouldn't be called."); + public void Configure(OpenIddictServerAspNetCoreOptions options) => Debug.Fail("This infrastructure method shouldn't be called."); private async Task GetServerSettingsAsync() { diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdValidationConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdValidationConfiguration.cs index efa76e848a0..dcf972213c1 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdValidationConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Configuration/OpenIdValidationConfiguration.cs @@ -25,10 +25,11 @@ namespace OrchardCore.OpenId.Configuration { [Feature(OpenIdConstants.Features.Validation)] - public class OpenIdValidationConfiguration : IConfigureOptions, - IConfigureOptions, - IConfigureOptions, - IConfigureNamedOptions + public class OpenIdValidationConfiguration + : IConfigureOptions, + IConfigureOptions, + IConfigureOptions, + IConfigureNamedOptions { private readonly ILogger _logger; private readonly IOpenIdValidationService _validationService; @@ -41,7 +42,8 @@ public OpenIdValidationConfiguration( IOpenIdValidationService validationService, IRunningShellTable runningShellTable, IShellHost shellHost, - ShellSettings shellSettings) + ShellSettings shellSettings + ) { _logger = logger; _validationService = validationService; @@ -60,31 +62,32 @@ public void Configure(AuthenticationOptions options) if (settings.Authority != null) { - options.AddScheme( - OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme, displayName: null); + options.AddScheme(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme, displayName: null); return; } // Note: the shell host guarantees that the OpenID server service resolved inside // this using block won't be disposed until the service scope itself is released. - CreateTenantScope(settings.Tenant).UsingAsync(async scope => - { - var service = scope.ServiceProvider.GetService(); - if (service == null) + CreateTenantScope(settings.Tenant) + .UsingAsync(async scope => { - return; - } + var service = scope.ServiceProvider.GetService(); + if (service == null) + { + return; + } - var configuration = await GetServerSettingsAsync(service); - if (configuration == null) - { - return; - } + var configuration = await GetServerSettingsAsync(service); + if (configuration == null) + { + return; + } - options.AddScheme( - OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme, displayName: null); - }).GetAwaiter().GetResult(); + options.AddScheme(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme, displayName: null); + }) + .GetAwaiter() + .GetResult(); } public void Configure(OpenIddictValidationOptions options) @@ -118,77 +121,78 @@ public void Configure(OpenIddictValidationOptions options) // currently used in the API validation feature), no matter what their actual "typ" header is. if (settings.DisableTokenTypeValidation) { - options.TokenValidationParameters.TypeValidator = (type, token, parameters) - => JsonWebTokenTypes.AccessToken; + options.TokenValidationParameters.TypeValidator = (type, token, parameters) => JsonWebTokenTypes.AccessToken; } } // Note: the shell host guarantees that the OpenID server service resolved inside // this using block won't be disposed until the service scope itself is released. - CreateTenantScope(settings.Tenant).UsingAsync(async scope => - { - var service = scope.ServiceProvider.GetService(); - if (service == null) + CreateTenantScope(settings.Tenant) + .UsingAsync(async scope => { - return; - } + var service = scope.ServiceProvider.GetService(); + if (service == null) + { + return; + } - var configuration = await GetServerSettingsAsync(service); - if (configuration == null) - { - return; - } + var configuration = await GetServerSettingsAsync(service); + if (configuration == null) + { + return; + } - options.Configuration = new OpenIddictConfiguration(); + options.Configuration = new OpenIddictConfiguration(); - options.Issuer = configuration.Authority; + options.Issuer = configuration.Authority; - // Import the signing keys from the OpenID server configuration. - foreach (var key in await service.GetSigningKeysAsync()) - { - options.Configuration.SigningKeys.Add(key); - } + // Import the signing keys from the OpenID server configuration. + foreach (var key in await service.GetSigningKeysAsync()) + { + options.Configuration.SigningKeys.Add(key); + } - // Register the encryption keys used by the OpenID Connect server. - foreach (var key in await service.GetEncryptionKeysAsync()) - { - options.EncryptionCredentials.Add(new EncryptingCredentials(key, - SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512)); - } + // Register the encryption keys used by the OpenID Connect server. + foreach (var key in await service.GetEncryptionKeysAsync()) + { + options.EncryptionCredentials.Add(new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512)); + } - // When the server is another tenant, don't allow the current tenant - // to choose the valid audiences, as this would otherwise allow it - // to validate/introspect tokens meant to be used with another tenant. - options.Audiences.Add(OpenIdConstants.Prefixes.Tenant + _shellSettings.Name); + // When the server is another tenant, don't allow the current tenant + // to choose the valid audiences, as this would otherwise allow it + // to validate/introspect tokens meant to be used with another tenant. + options.Audiences.Add(OpenIdConstants.Prefixes.Tenant + _shellSettings.Name); - // Note: token entry validation must be enabled to be able to validate reference tokens. - options.EnableTokenEntryValidation = configuration.UseReferenceAccessTokens; + // Note: token entry validation must be enabled to be able to validate reference tokens. + options.EnableTokenEntryValidation = configuration.UseReferenceAccessTokens; - // If an authority was explicitly set in the OpenID server options, - // prefer it to the dynamic tenant comparison as it's more efficient. - if (configuration.Authority != null) - { - options.TokenValidationParameters.ValidIssuer = configuration.Authority.AbsoluteUri; - } - else - { - options.TokenValidationParameters.IssuerValidator = (issuer, token, parameters) => + // If an authority was explicitly set in the OpenID server options, + // prefer it to the dynamic tenant comparison as it's more efficient. + if (configuration.Authority != null) { - if (!Uri.TryCreate(issuer, UriKind.Absolute, out var uri)) - { - throw new SecurityTokenInvalidIssuerException("The token issuer is not valid."); - } - - var tenant = _runningShellTable.Match(HostString.FromUriComponent(uri), uri.AbsolutePath); - if (tenant == null || !string.Equals(tenant.Name, settings.Tenant)) + options.TokenValidationParameters.ValidIssuer = configuration.Authority.AbsoluteUri; + } + else + { + options.TokenValidationParameters.IssuerValidator = (issuer, token, parameters) => { - throw new SecurityTokenInvalidIssuerException("The token issuer is not valid."); - } - - return issuer; - }; - } - }).GetAwaiter().GetResult(); + if (!Uri.TryCreate(issuer, UriKind.Absolute, out var uri)) + { + throw new SecurityTokenInvalidIssuerException("The token issuer is not valid."); + } + + var tenant = _runningShellTable.Match(HostString.FromUriComponent(uri), uri.AbsolutePath); + if (tenant == null || !string.Equals(tenant.Name, settings.Tenant)) + { + throw new SecurityTokenInvalidIssuerException("The token issuer is not valid."); + } + + return issuer; + }; + } + }) + .GetAwaiter() + .GetResult(); } public void Configure(OpenIddictValidationDataProtectionOptions options) @@ -201,22 +205,24 @@ public void Configure(OpenIddictValidationDataProtectionOptions options) // If the tokens are issued by an authorization server located in a separate tenant, // resolve the isolated data protection provider associated with the specified tenant. - if (!string.IsNullOrEmpty(settings.Tenant) && - !string.Equals(settings.Tenant, _shellSettings.Name)) + if (!string.IsNullOrEmpty(settings.Tenant) && !string.Equals(settings.Tenant, _shellSettings.Name)) { - CreateTenantScope(settings.Tenant).UsingAsync(async scope => - { - // If the other tenant is released, ensure the current tenant is also restarted as it - // relies on a data protection provider whose lifetime is managed by the other tenant. - // To make sure the other tenant is not disposed before all the pending requests are - // processed by the current tenant, a tenant dependency is manually added. - await scope.ShellContext.AddDependentShellAsync(await _shellHost.GetOrCreateShellContextAsync(_shellSettings)); - - // Note: the data protection provider is always registered as a singleton and thus will - // survive the current scope, which is mainly used to prevent the other tenant from being - // released before we have a chance to declare the current tenant as a dependent tenant. - options.DataProtectionProvider = scope.ServiceProvider.GetDataProtectionProvider(); - }).GetAwaiter().GetResult(); + CreateTenantScope(settings.Tenant) + .UsingAsync(async scope => + { + // If the other tenant is released, ensure the current tenant is also restarted as it + // relies on a data protection provider whose lifetime is managed by the other tenant. + // To make sure the other tenant is not disposed before all the pending requests are + // processed by the current tenant, a tenant dependency is manually added. + await scope.ShellContext.AddDependentShellAsync(await _shellHost.GetOrCreateShellContextAsync(_shellSettings)); + + // Note: the data protection provider is always registered as a singleton and thus will + // survive the current scope, which is mainly used to prevent the other tenant from being + // released before we have a chance to declare the current tenant as a dependent tenant. + options.DataProtectionProvider = scope.ServiceProvider.GetDataProtectionProvider(); + }) + .GetAwaiter() + .GetResult(); } } @@ -229,8 +235,7 @@ public void Configure(string name, ApiAuthorizationOptions options) options.ApiAuthenticationScheme = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme; } - public void Configure(ApiAuthorizationOptions options) - => Debug.Fail("This infrastructure method shouldn't be called."); + public void Configure(ApiAuthorizationOptions options) => Debug.Fail("This infrastructure method shouldn't be called."); private ShellScope CreateTenantScope(string tenant) { diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/AccessController.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/AccessController.cs index 6e3cc60446d..fb9922629ed 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/AccessController.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/AccessController.cs @@ -38,7 +38,8 @@ public AccessController( IOpenIdApplicationManager applicationManager, IOpenIdAuthorizationManager authorizationManager, IOpenIdScopeManager scopeManager, - ShellSettings shellSettings) + ShellSettings shellSettings + ) { _applicationManager = applicationManager; _authorizationManager = authorizationManager; @@ -52,11 +53,7 @@ public async Task Authorize() var response = HttpContext.GetOpenIddictServerResponse(); if (response != null) { - return View("Error", new ErrorViewModel - { - Error = response.Error, - ErrorDescription = response.ErrorDescription - }); + return View("Error", new ErrorViewModel { Error = response.Error, ErrorDescription = response.ErrorDescription }); } var request = HttpContext.GetOpenIddictServerRequest(); @@ -75,31 +72,36 @@ public async Task Authorize() // If a max_age parameter was provided, ensure that the cookie is not too old. // If it's too old, automatically redirect the user agent to the login page. - if (request.MaxAge != null && result.Properties.IssuedUtc != null && - DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value)) + if (request.MaxAge != null && result.Properties.IssuedUtc != null && DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value)) { return RedirectToLoginPage(request); } - var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ?? - throw new InvalidOperationException("The application details cannot be found."); + var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ?? throw new InvalidOperationException("The application details cannot be found."); - var authorizations = await _authorizationManager.FindAsync( - subject: result.Principal.GetUserIdentifier(), - client: await _applicationManager.GetIdAsync(application), - status: Statuses.Valid, - type: AuthorizationTypes.Permanent, - scopes: request.GetScopes()).ToListAsync(); + var authorizations = await _authorizationManager + .FindAsync( + subject: result.Principal.GetUserIdentifier(), + client: await _applicationManager.GetIdAsync(application), + status: Statuses.Valid, + type: AuthorizationTypes.Permanent, + scopes: request.GetScopes() + ) + .ToListAsync(); switch (await _applicationManager.GetConsentTypeAsync(application)) { case ConsentTypes.External when authorizations.Count == 0: - return Forbid(new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "The logged in user is not allowed to access this client application." - }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + return Forbid( + new AuthenticationProperties( + new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The logged in user is not allowed to access this client application." + } + ), + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme + ); case ConsentTypes.Implicit: case ConsentTypes.External when authorizations.Count > 0: @@ -130,7 +132,8 @@ public async Task Authorize() subject: identity.GetUserIdentifier(), client: await _applicationManager.GetIdAsync(application), type: AuthorizationTypes.Permanent, - scopes: identity.GetScopes()); + scopes: identity.GetScopes() + ); identity.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization)); identity.SetDestinations(GetDestinations); @@ -138,20 +141,26 @@ public async Task Authorize() return SignIn(new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); case ConsentTypes.Explicit when request.HasPrompt(Prompts.None): - return Forbid(new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "Interactive user consent is required." - }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + return Forbid( + new AuthenticationProperties( + new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "Interactive user consent is required." + } + ), + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme + ); default: - return View(new AuthorizeViewModel - { - ApplicationName = await _applicationManager.GetLocalizedDisplayNameAsync(application), - RequestId = request.RequestId, - Scope = request.Scope - }); + return View( + new AuthorizeViewModel + { + ApplicationName = await _applicationManager.GetLocalizedDisplayNameAsync(application), + RequestId = request.RequestId, + Scope = request.Scope + } + ); } IActionResult RedirectToLoginPage(OpenIddictRequest request) @@ -160,11 +169,16 @@ IActionResult RedirectToLoginPage(OpenIddictRequest request) // return an error indicating that the user is not logged in. if (request.HasPrompt(Prompts.None)) { - return Forbid(new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in." - }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + return Forbid( + new AuthenticationProperties( + new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in." + } + ), + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme + ); } string GetRedirectUrl() @@ -176,10 +190,7 @@ string GetRedirectUrl() return Request.PathBase + Request.Path + QueryString.Create(parameters); } - return Challenge(new AuthenticationProperties - { - RedirectUri = GetRedirectUrl() - }); + return Challenge(new AuthenticationProperties { RedirectUri = GetRedirectUrl() }); } } @@ -195,11 +206,7 @@ public async Task AuthorizeAccept() var response = HttpContext.GetOpenIddictServerResponse(); if (response != null) { - return View("Error", new ErrorViewModel - { - Error = response.Error, - ErrorDescription = response.ErrorDescription - }); + return View("Error", new ErrorViewModel { Error = response.Error, ErrorDescription = response.ErrorDescription }); } var request = HttpContext.GetOpenIddictServerRequest(); @@ -208,15 +215,17 @@ public async Task AuthorizeAccept() return NotFound(); } - var application = await _applicationManager.FindByClientIdAsync(request.ClientId) - ?? throw new InvalidOperationException("The application details cannot be found."); + var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ?? throw new InvalidOperationException("The application details cannot be found."); - var authorizations = await _authorizationManager.FindAsync( - subject: User.GetUserIdentifier(), - client: await _applicationManager.GetIdAsync(application), - status: Statuses.Valid, - type: AuthorizationTypes.Permanent, - scopes: request.GetScopes()).ToListAsync(); + var authorizations = await _authorizationManager + .FindAsync( + subject: User.GetUserIdentifier(), + client: await _applicationManager.GetIdAsync(application), + status: Statuses.Valid, + type: AuthorizationTypes.Permanent, + scopes: request.GetScopes() + ) + .ToListAsync(); // Note: the same check is already made in the GET action but is repeated // here to ensure a malicious user can't abuse this POST endpoint and @@ -224,12 +233,16 @@ public async Task AuthorizeAccept() switch (await _applicationManager.GetConsentTypeAsync(application)) { case ConsentTypes.External when authorizations.Count == 0: - return Forbid(new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "The logged in user is not allowed to access this client application." - }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + return Forbid( + new AuthenticationProperties( + new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The logged in user is not allowed to access this client application." + } + ), + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme + ); default: var identity = new ClaimsIdentity(User.Claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); @@ -258,7 +271,8 @@ public async Task AuthorizeAccept() subject: identity.GetUserIdentifier(), client: await _applicationManager.GetIdAsync(application), type: AuthorizationTypes.Permanent, - scopes: identity.GetScopes()); + scopes: identity.GetScopes() + ); identity.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization)); identity.SetDestinations(GetDestinations); @@ -274,11 +288,7 @@ public IActionResult AuthorizeDeny() var response = HttpContext.GetOpenIddictServerResponse(); if (response != null) { - return View("Error", new ErrorViewModel - { - Error = response.Error, - ErrorDescription = response.ErrorDescription - }); + return View("Error", new ErrorViewModel { Error = response.Error, ErrorDescription = response.ErrorDescription }); } var request = HttpContext.GetOpenIddictServerRequest(); @@ -296,11 +306,7 @@ public async Task Logout() var response = HttpContext.GetOpenIddictServerResponse(); if (response != null) { - return View("Error", new ErrorViewModel - { - Error = response.Error, - ErrorDescription = response.ErrorDescription - }); + return View("Error", new ErrorViewModel { Error = response.Error, ErrorDescription = response.ErrorDescription }); } var request = HttpContext.GetOpenIddictServerRequest(); @@ -320,10 +326,7 @@ public async Task Logout() } } - return View(new LogoutViewModel - { - RequestId = request.RequestId - }); + return View(new LogoutViewModel { RequestId = request.RequestId }); } [ActionName(nameof(Logout)), AllowAnonymous, DisableCors] @@ -333,11 +336,7 @@ public async Task LogoutAccept() var response = HttpContext.GetOpenIddictServerResponse(); if (response != null) { - return View("Error", new ErrorViewModel - { - Error = response.Error, - ErrorDescription = response.ErrorDescription - }); + return View("Error", new ErrorViewModel { Error = response.Error, ErrorDescription = response.ErrorDescription }); } var request = HttpContext.GetOpenIddictServerRequest(); @@ -370,11 +369,7 @@ public IActionResult LogoutDeny() var response = HttpContext.GetOpenIddictServerResponse(); if (response != null) { - return View("Error", new ErrorViewModel - { - Error = response.Error, - ErrorDescription = response.ErrorDescription - }); + return View("Error", new ErrorViewModel { Error = response.Error, ErrorDescription = response.ErrorDescription }); } var request = HttpContext.GetOpenIddictServerRequest(); @@ -425,29 +420,31 @@ private async Task ExchangeClientCredentialsGrantType(OpenIddictR { if (request.HasScope(Scopes.OfflineAccess)) { - return Forbid(new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidScope, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "The 'offline_access' scope is not allowed when using the client credentials grant." - }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + return Forbid( + new AuthenticationProperties( + new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidScope, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The 'offline_access' scope is not allowed when using the client credentials grant." + } + ), + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme + ); } // Note: client authentication is always enforced by OpenIddict before this action is invoked. - var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ?? - throw new InvalidOperationException("The application details cannot be found."); + var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ?? throw new InvalidOperationException("The application details cannot be found."); - var identity = new ClaimsIdentity( - OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, - Claims.Name, Claims.Role); + var identity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, Claims.Name, Claims.Role); identity.AddClaim(new Claim(OpenIdConstants.Claims.EntityType, OpenIdConstants.EntityTypes.Application)); identity.AddClaim(new Claim(Claims.Subject, request.ClientId)); // Always add a "name" claim for grant_type=client_credentials in both // access and identity tokens even if the "name" scope wasn't requested. - identity.AddClaim(new Claim(Claims.Name, await _applicationManager.GetDisplayNameAsync(application)) - .SetDestinations(Destinations.AccessToken, Destinations.IdentityToken)); + identity.AddClaim( + new Claim(Claims.Name, await _applicationManager.GetDisplayNameAsync(application)).SetDestinations(Destinations.AccessToken, Destinations.IdentityToken) + ); // If the role service is available, add all the role claims // associated with the application roles in the database. @@ -458,8 +455,7 @@ private async Task ExchangeClientCredentialsGrantType(OpenIddictR // Since the claims added in this block have a dynamic name, directly set the destinations // here instead of relying on the GetDestination() helper that only works with static claims. - identity.AddClaim(new Claim(identity.RoleClaimType, role) - .SetDestinations(Destinations.AccessToken, Destinations.IdentityToken)); + identity.AddClaim(new Claim(identity.RoleClaimType, role).SetDestinations(Destinations.AccessToken, Destinations.IdentityToken)); if (roleService != null) { @@ -479,53 +475,68 @@ private async Task ExchangeClientCredentialsGrantType(OpenIddictR private async Task ExchangePasswordGrantType(OpenIddictRequest request) { - var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ?? - throw new InvalidOperationException("The application details cannot be found."); + var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ?? throw new InvalidOperationException("The application details cannot be found."); // By design, the password flow requires direct username/password validation, which is performed by // the user service. If this service is not registered, prevent the password flow from being used. var service = HttpContext.RequestServices.GetService(); if (service == null) { - return Forbid(new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.UnsupportedGrantType, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "The resource owner password credentials grant is not supported." - }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + return Forbid( + new AuthenticationProperties( + new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.UnsupportedGrantType, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The resource owner password credentials grant is not supported." + } + ), + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme + ); } string error = null; var user = await service.AuthenticateAsync(request.Username, request.Password, (key, message) => error = message); if (user == null) { - return Forbid(new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidGrant, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = error - }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + return Forbid( + new AuthenticationProperties( + new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidGrant, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = error + } + ), + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme + ); } var principal = await service.CreatePrincipalAsync(user); - var authorizations = await _authorizationManager.FindAsync( - subject: principal.GetUserIdentifier(), - client: await _applicationManager.GetIdAsync(application), - status: Statuses.Valid, - type: AuthorizationTypes.Permanent, - scopes: request.GetScopes()).ToListAsync(); + var authorizations = await _authorizationManager + .FindAsync( + subject: principal.GetUserIdentifier(), + client: await _applicationManager.GetIdAsync(application), + status: Statuses.Valid, + type: AuthorizationTypes.Permanent, + scopes: request.GetScopes() + ) + .ToListAsync(); // If the application is configured to use external consent, // reject the request if no existing authorization can be found. switch (await _applicationManager.GetConsentTypeAsync(application)) { case ConsentTypes.External when authorizations.Count == 0: - return Forbid(new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "The logged in user is not allowed to access this client application." - }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + return Forbid( + new AuthenticationProperties( + new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The logged in user is not allowed to access this client application." + } + ), + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme + ); } var identity = (ClaimsIdentity)principal.Identity; @@ -554,7 +565,8 @@ private async Task ExchangePasswordGrantType(OpenIddictRequest re subject: identity.GetUserIdentifier(), client: await _applicationManager.GetIdAsync(application), type: AuthorizationTypes.Permanent, - scopes: identity.GetScopes()); + scopes: identity.GetScopes() + ); identity.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization)); identity.SetDestinations(GetDestinations); @@ -565,20 +577,26 @@ private async Task ExchangePasswordGrantType(OpenIddictRequest re private async Task ExchangeAuthorizationCodeOrRefreshTokenGrantType(OpenIddictRequest request) { // Retrieve the claims principal stored in the authorization code/refresh token. - var info = await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme) ?? - throw new InvalidOperationException("The user principal cannot be resolved."); + var info = + await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme) + ?? throw new InvalidOperationException("The user principal cannot be resolved."); if (request.IsRefreshTokenGrantType()) { var type = info.Principal.FindFirst(OpenIdConstants.Claims.EntityType)?.Value; if (!string.Equals(type, OpenIdConstants.EntityTypes.User)) { - return Forbid(new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.UnauthorizedClient, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "The refresh token grant type is not allowed for refresh tokens retrieved using the client credentials flow." - }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + return Forbid( + new AuthenticationProperties( + new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.UnauthorizedClient, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = + "The refresh token grant type is not allowed for refresh tokens retrieved using the client credentials flow." + } + ), + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme + ); } } @@ -642,13 +660,10 @@ private static IEnumerable GetDestinations(Claim claim) case Claims.Name when claim.Subject.HasScope(Scopes.Profile): case Claims.Email when claim.Subject.HasScope(Scopes.Email): case Claims.Role when claim.Subject.HasScope(Scopes.Roles): - return new[] - { - Destinations.AccessToken, - Destinations.IdentityToken - }; + return new[] { Destinations.AccessToken, Destinations.IdentityToken }; - default: return new[] { Destinations.AccessToken }; + default: + return new[] { Destinations.AccessToken }; } } @@ -657,10 +672,7 @@ private async Task> GetResourcesAsync(ImmutableArray // Note: the current tenant name is always added as a valid resource/audience, // which allows the end user to use the corresponding tokens with the APIs // located in the current tenant without having to explicitly register a scope. - var resources = new List() - { - OpenIdConstants.Prefixes.Tenant + _shellSettings.Name - }; + var resources = new List() { OpenIdConstants.Prefixes.Tenant + _shellSettings.Name }; await foreach (var resource in _scopeManager.ListResourcesAsync(scopes)) { diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ApplicationController.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ApplicationController.cs index cc977896dcc..3ef925b00a3 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ApplicationController.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ApplicationController.cs @@ -47,7 +47,8 @@ public ApplicationController( IOpenIdScopeManager scopeManager, IHtmlLocalizer htmlLocalizer, INotifier notifier, - ShellDescriptor shellDescriptor) + ShellDescriptor shellDescriptor + ) { _shapeFactory = shapeFactory; _pagerOptions = pagerOptions.Value; @@ -71,18 +72,17 @@ public async Task Index(PagerParameters pagerParameters) var pager = new Pager(pagerParameters, _pagerOptions.GetPageSize()); var count = await _applicationManager.CountAsync(); - var model = new OpenIdApplicationsIndexViewModel - { - Pager = await _shapeFactory.PagerAsync(pager, (int)count), - }; + var model = new OpenIdApplicationsIndexViewModel { Pager = await _shapeFactory.PagerAsync(pager, (int)count), }; await foreach (var application in _applicationManager.ListAsync(pager.PageSize, pager.GetStartIndex())) { - model.Applications.Add(new OpenIdApplicationEntry - { - DisplayName = await _applicationManager.GetDisplayNameAsync(application), - Id = await _applicationManager.GetPhysicalIdAsync(application) - }); + model.Applications.Add( + new OpenIdApplicationEntry + { + DisplayName = await _applicationManager.GetDisplayNameAsync(application), + Id = await _applicationManager.GetPhysicalIdAsync(application) + } + ); } return View(model); @@ -103,10 +103,7 @@ public async Task Create(string returnUrl = null) { foreach (var role in await roleService.GetRoleNamesAsync()) { - model.RoleEntries.Add(new CreateOpenIdApplicationViewModel.RoleEntry - { - Name = role - }); + model.RoleEntries.Add(new CreateOpenIdApplicationViewModel.RoleEntry { Name = role }); } } else @@ -116,10 +113,7 @@ public async Task Create(string returnUrl = null) await foreach (var scope in _scopeManager.ListAsync(null, null, default)) { - model.ScopeEntries.Add(new CreateOpenIdApplicationViewModel.ScopeEntry - { - Name = await _scopeManager.GetNameAsync(scope) - }); + model.ScopeEntries.Add(new CreateOpenIdApplicationViewModel.ScopeEntry { Name = await _scopeManager.GetNameAsync(scope) }); } ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync(); @@ -135,13 +129,11 @@ public async Task Create(CreateOpenIdApplicationViewModel model, return Forbid(); } - if (!string.IsNullOrEmpty(model.ClientSecret) && - string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase)) + if (!string.IsNullOrEmpty(model.ClientSecret) && string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase)) { ModelState.AddModelError(nameof(model.ClientSecret), S["No client secret can be set for public applications."]); } - else if (string.IsNullOrEmpty(model.ClientSecret) && - string.Equals(model.Type, OpenIddictConstants.ClientTypes.Confidential, StringComparison.OrdinalIgnoreCase)) + else if (string.IsNullOrEmpty(model.ClientSecret) && string.Equals(model.Type, OpenIddictConstants.ClientTypes.Confidential, StringComparison.OrdinalIgnoreCase)) { ModelState.AddModelError(nameof(model.ClientSecret), S["The client secret is required for confidential applications."]); } @@ -209,24 +201,31 @@ public async Task Edit(string id, string returnUrl = null) var model = new EditOpenIdApplicationViewModel { - AllowAuthorizationCodeFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode) && - await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.Code), + AllowAuthorizationCodeFlow = + await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode) + && await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.Code), AllowClientCredentialsFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials), // Note: the hybrid flow doesn't have a dedicated grant_type but is treated as a combination // of both the authorization code and implicit grants. As such, to determine whether the hybrid // flow is enabled, both the authorization code grant and the implicit grant MUST be enabled. - AllowHybridFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode) && - await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Implicit) && - (await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.CodeIdToken) || - await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.CodeIdTokenToken) || - await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.CodeToken)), - - AllowImplicitFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Implicit) && - (await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.IdToken) || - await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.IdTokenToken) || - await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.Token)), + AllowHybridFlow = + await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode) + && await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Implicit) + && ( + await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.CodeIdToken) + || await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.CodeIdTokenToken) + || await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.CodeToken) + ), + + AllowImplicitFlow = + await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Implicit) + && ( + await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.IdToken) + || await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.IdTokenToken) + || await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.Token) + ), AllowPasswordFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Password), AllowRefreshTokenFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.RefreshToken), @@ -250,11 +249,7 @@ await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.Token)), foreach (var role in await roleService.GetRoleNamesAsync()) { - model.RoleEntries.Add(new EditOpenIdApplicationViewModel.RoleEntry - { - Name = role, - Selected = roles.Contains(role, StringComparer.OrdinalIgnoreCase) - }); + model.RoleEntries.Add(new EditOpenIdApplicationViewModel.RoleEntry { Name = role, Selected = roles.Contains(role, StringComparer.OrdinalIgnoreCase) }); } } else @@ -266,11 +261,13 @@ await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.Token)), await foreach (var scope in _scopeManager.ListAsync()) { var scopeName = await _scopeManager.GetNameAsync(scope); - model.ScopeEntries.Add(new EditOpenIdApplicationViewModel.ScopeEntry - { - Name = scopeName, - Selected = await _applicationManager.HasPermissionAsync(application, OpenIddictConstants.Permissions.Prefixes.Scope + scopeName) - }); + model.ScopeEntries.Add( + new EditOpenIdApplicationViewModel.ScopeEntry + { + Name = scopeName, + Selected = await _applicationManager.HasPermissionAsync(application, OpenIddictConstants.Permissions.Prefixes.Scope + scopeName) + } + ); } ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync(); @@ -293,15 +290,16 @@ public async Task Edit(EditOpenIdApplicationViewModel model, stri } // If the application was a public client and is now a confidential client, ensure a client secret was provided. - if (string.IsNullOrEmpty(model.ClientSecret) && - !string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase) && - await _applicationManager.HasClientTypeAsync(application, OpenIddictConstants.ClientTypes.Public)) + if ( + string.IsNullOrEmpty(model.ClientSecret) + && !string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase) + && await _applicationManager.HasClientTypeAsync(application, OpenIddictConstants.ClientTypes.Public) + ) { ModelState.AddModelError(nameof(model.ClientSecret), S["Setting a new client secret is required."]); } - if (!string.IsNullOrEmpty(model.ClientSecret) && - string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase)) + if (!string.IsNullOrEmpty(model.ClientSecret) && string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase)) { ModelState.AddModelError(nameof(model.ClientSecret), S["No client secret can be set for public applications."]); } @@ -309,9 +307,7 @@ await _applicationManager.HasClientTypeAsync(application, OpenIddictConstants.Cl if (ModelState.IsValid) { var other = await _applicationManager.FindByClientIdAsync(model.ClientId); - if (other != null && !string.Equals( - await _applicationManager.GetIdAsync(other), - await _applicationManager.GetIdAsync(application), StringComparison.Ordinal)) + if (other != null && !string.Equals(await _applicationManager.GetIdAsync(other), await _applicationManager.GetIdAsync(application), StringComparison.Ordinal)) { ModelState.AddModelError(nameof(model.ClientId), S["The client identifier is already taken by another application."]); } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ScopeController.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ScopeController.cs index 7b5461825c3..a1121d121b2 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ScopeController.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ScopeController.cs @@ -42,7 +42,8 @@ public ScopeController( INotifier notifier, ShellDescriptor shellDescriptor, ShellSettings shellSettings, - IShellHost shellHost) + IShellHost shellHost + ) { _scopeManager = scopeManager; _shapeFactory = shapeFactory; @@ -66,20 +67,19 @@ public async Task Index(PagerParameters pagerParameters) var pager = new Pager(pagerParameters, _pagerOptions.GetPageSize()); var count = await _scopeManager.CountAsync(); - var model = new OpenIdScopeIndexViewModel - { - Pager = await _shapeFactory.PagerAsync(pager, (int)count), - }; + var model = new OpenIdScopeIndexViewModel { Pager = await _shapeFactory.PagerAsync(pager, (int)count), }; await foreach (var scope in _scopeManager.ListAsync(pager.PageSize, pager.GetStartIndex())) { - model.Scopes.Add(new OpenIdScopeEntry - { - Description = await _scopeManager.GetDescriptionAsync(scope), - DisplayName = await _scopeManager.GetDisplayNameAsync(scope), - Id = await _scopeManager.GetPhysicalIdAsync(scope), - Name = await _scopeManager.GetNameAsync(scope) - }); + model.Scopes.Add( + new OpenIdScopeEntry + { + Description = await _scopeManager.GetDescriptionAsync(scope), + DisplayName = await _scopeManager.GetDisplayNameAsync(scope), + Id = await _scopeManager.GetPhysicalIdAsync(scope), + Name = await _scopeManager.GetNameAsync(scope) + } + ); } return View(model); @@ -97,11 +97,7 @@ public async Task Create(string returnUrl = null) foreach (var tenant in _shellHost.GetAllSettings().Where(s => s.IsRunning())) { - model.Tenants.Add(new CreateOpenIdScopeViewModel.TenantEntry - { - Current = string.Equals(tenant.Name, _shellSettings.Name), - Name = tenant.Name - }); + model.Tenants.Add(new CreateOpenIdScopeViewModel.TenantEntry { Current = string.Equals(tenant.Name, _shellSettings.Name), Name = tenant.Name }); } ViewData["ReturnUrl"] = returnUrl; @@ -139,10 +135,12 @@ public async Task Create(CreateOpenIdScopeViewModel model, string descriptor.Resources.UnionWith(model.Resources.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } - descriptor.Resources.UnionWith(model.Tenants - .Where(tenant => tenant.Selected) - .Where(tenant => !string.Equals(tenant.Name, _shellSettings.Name)) - .Select(tenant => OpenIdConstants.Prefixes.Tenant + tenant.Name)); + descriptor.Resources.UnionWith( + model + .Tenants.Where(tenant => tenant.Selected) + .Where(tenant => !string.Equals(tenant.Name, _shellSettings.Name)) + .Select(tenant => OpenIdConstants.Prefixes.Tenant + tenant.Name) + ); await _scopeManager.CreateAsync(descriptor); @@ -177,19 +175,23 @@ public async Task Edit(string id, string returnUrl = null) var resources = await _scopeManager.GetResourcesAsync(scope); - model.Resources = string.Join(" ", + model.Resources = string.Join( + " ", from resource in resources where !string.IsNullOrEmpty(resource) && !resource.StartsWith(OpenIdConstants.Prefixes.Tenant, StringComparison.Ordinal) - select resource); + select resource + ); foreach (var tenant in _shellHost.GetAllSettings().Where(s => s.IsRunning())) { - model.Tenants.Add(new EditOpenIdScopeViewModel.TenantEntry - { - Current = string.Equals(tenant.Name, _shellSettings.Name), - Name = tenant.Name, - Selected = resources.Contains(OpenIdConstants.Prefixes.Tenant + tenant.Name) - }); + model.Tenants.Add( + new EditOpenIdScopeViewModel.TenantEntry + { + Current = string.Equals(tenant.Name, _shellSettings.Name), + Name = tenant.Name, + Selected = resources.Contains(OpenIdConstants.Prefixes.Tenant + tenant.Name) + } + ); } ViewData["ReturnUrl"] = returnUrl; @@ -213,9 +215,7 @@ public async Task Edit(EditOpenIdScopeViewModel model, string ret if (ModelState.IsValid) { var other = await _scopeManager.FindByNameAsync(model.Name); - if (other != null && !string.Equals( - await _scopeManager.GetIdAsync(other), - await _scopeManager.GetIdAsync(scope))) + if (other != null && !string.Equals(await _scopeManager.GetIdAsync(other), await _scopeManager.GetIdAsync(scope))) { ModelState.AddModelError(nameof(model.Name), S["The name is already taken by another scope."]); } @@ -241,10 +241,12 @@ await _scopeManager.GetIdAsync(scope))) descriptor.Resources.UnionWith(model.Resources.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } - descriptor.Resources.UnionWith(model.Tenants - .Where(tenant => tenant.Selected) - .Where(tenant => !string.Equals(tenant.Name, _shellSettings.Name)) - .Select(tenant => OpenIdConstants.Prefixes.Tenant + tenant.Name)); + descriptor.Resources.UnionWith( + model + .Tenants.Where(tenant => tenant.Selected) + .Where(tenant => !string.Equals(tenant.Name, _shellSettings.Name)) + .Select(tenant => OpenIdConstants.Prefixes.Tenant + tenant.Name) + ); await _scopeManager.UpdateAsync(scope, descriptor); diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ServerConfigurationController.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ServerConfigurationController.cs index f6c408a2b51..71ad5b7d505 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ServerConfigurationController.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ServerConfigurationController.cs @@ -35,7 +35,8 @@ public ServerConfigurationController( IDisplayManager serverSettingsDisplayManager, IShellHost shellHost, ShellSettings shellSettings, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _authorizationService = authorizationService; H = htmlLocalizer; diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/UserInfoController.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/UserInfoController.cs index 7def02963b3..59809d81338 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/UserInfoController.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/UserInfoController.cs @@ -49,12 +49,16 @@ public async Task Me() var type = principal.FindFirst(OpenIdConstants.Claims.EntityType)?.Value; if (!string.Equals(type, OpenIdConstants.EntityTypes.User)) { - return Forbid(new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidRequest, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "The userinfo endpoint can only be used with access tokens representing users." - }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + return Forbid( + new AuthenticationProperties( + new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidRequest, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The userinfo endpoint can only be used with access tokens representing users." + } + ), + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme + ); } var claims = new Dictionary(); @@ -125,10 +129,11 @@ public async Task Me() if (principal.HasScope(Scopes.Phone)) { - var phone = principal.FindFirst(Claims.PhoneNumber)?.Value ?? - principal.FindFirst(ClaimTypes.MobilePhone)?.Value ?? - principal.FindFirst(ClaimTypes.HomePhone)?.Value ?? - principal.FindFirst(ClaimTypes.OtherPhone)?.Value; + var phone = + principal.FindFirst(Claims.PhoneNumber)?.Value + ?? principal.FindFirst(ClaimTypes.MobilePhone)?.Value + ?? principal.FindFirst(ClaimTypes.HomePhone)?.Value + ?? principal.FindFirst(ClaimTypes.OtherPhone)?.Value; if (!string.IsNullOrEmpty(phone)) { @@ -144,10 +149,7 @@ public async Task Me() if (principal.HasScope(Scopes.Roles)) { - var roles = principal.FindAll(Claims.Role) - .Concat(principal.FindAll(ClaimTypes.Role)) - .Select(claim => claim.Value) - .ToArray(); + var roles = principal.FindAll(Claims.Role).Concat(principal.FindAll(ClaimTypes.Role)).Select(claim => claim.Value).ToArray(); if (roles.Length != 0) { diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ValidationConfigurationController.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ValidationConfigurationController.cs index 7935372dea5..6dc27a12a05 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ValidationConfigurationController.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/ValidationConfigurationController.cs @@ -35,7 +35,8 @@ public ValidationConfigurationController( IDisplayManager validationSettingsDisplayManager, IShellHost shellHost, ShellSettings shellSettings, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _authorizationService = authorizationService; H = htmlLocalizer; diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Deployment/OpenIdServerDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Deployment/OpenIdServerDeploymentSource.cs index a3474788075..4f6431710bf 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Deployment/OpenIdServerDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Deployment/OpenIdServerDeploymentSource.cs @@ -25,8 +25,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan return; } - var settings = await _openIdServerService - .GetSettingsAsync(); + var settings = await _openIdServerService.GetSettingsAsync(); var settingsModel = new OpenIdServerSettingsStepModel { @@ -65,10 +64,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan // Use nameof(OpenIdServerSettings) as name, // to match the recipe step. - var obj = new JsonObject - { - ["name"] = nameof(OpenIdServerSettings), - }; + var obj = new JsonObject { ["name"] = nameof(OpenIdServerSettings), }; obj.Merge(JObject.FromObject(settingsModel)); diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Deployment/OpenIdServerDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Deployment/OpenIdServerDeploymentStepDriver.cs index 0a714ed94ee..71badfcba4b 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Deployment/OpenIdServerDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Deployment/OpenIdServerDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class OpenIdServerDeploymentStepDriver : DisplayDriver stringLocalizer) + IStringLocalizer stringLocalizer + ) { _authorizationService = authorizationService; _dataProtectionProvider = dataProtectionProvider; @@ -59,46 +60,51 @@ public override async Task EditAsync(OpenIdClientSettings settin return null; } - return Initialize("OpenIdClientSettings_Edit", model => - { - model.DisplayName = settings.DisplayName; - model.Scopes = settings.Scopes != null ? string.Join(" ", settings.Scopes) : null; - model.Authority = settings.Authority?.AbsoluteUri; - model.CallbackPath = settings.CallbackPath; - model.ClientId = settings.ClientId; - model.ClientSecret = settings.ClientSecret; - model.SignedOutCallbackPath = settings.SignedOutCallbackPath; - model.SignedOutRedirectUri = settings.SignedOutRedirectUri; - model.ResponseMode = settings.ResponseMode; - model.StoreExternalTokens = settings.StoreExternalTokens; - - if (settings.ResponseType == OpenIdConnectResponseType.Code) - { - model.UseCodeFlow = true; - } - else if (settings.ResponseType == OpenIdConnectResponseType.CodeIdToken) - { - model.UseCodeIdTokenFlow = true; - } - else if (settings.ResponseType == OpenIdConnectResponseType.CodeIdTokenToken) - { - model.UseCodeIdTokenTokenFlow = true; - } - else if (settings.ResponseType == OpenIdConnectResponseType.CodeToken) - { - model.UseCodeTokenFlow = true; - } - else if (settings.ResponseType == OpenIdConnectResponseType.IdToken) - { - model.UseIdTokenFlow = true; - } - else if (settings.ResponseType == OpenIdConnectResponseType.IdTokenToken) - { - model.UseIdTokenTokenFlow = true; - } - - model.Parameters = JConvert.SerializeObject(settings.Parameters, JOptions.CamelCase); - }).Location("Content:2").OnGroup(SettingsGroupId); + return Initialize( + "OpenIdClientSettings_Edit", + model => + { + model.DisplayName = settings.DisplayName; + model.Scopes = settings.Scopes != null ? string.Join(" ", settings.Scopes) : null; + model.Authority = settings.Authority?.AbsoluteUri; + model.CallbackPath = settings.CallbackPath; + model.ClientId = settings.ClientId; + model.ClientSecret = settings.ClientSecret; + model.SignedOutCallbackPath = settings.SignedOutCallbackPath; + model.SignedOutRedirectUri = settings.SignedOutRedirectUri; + model.ResponseMode = settings.ResponseMode; + model.StoreExternalTokens = settings.StoreExternalTokens; + + if (settings.ResponseType == OpenIdConnectResponseType.Code) + { + model.UseCodeFlow = true; + } + else if (settings.ResponseType == OpenIdConnectResponseType.CodeIdToken) + { + model.UseCodeIdTokenFlow = true; + } + else if (settings.ResponseType == OpenIdConnectResponseType.CodeIdTokenToken) + { + model.UseCodeIdTokenTokenFlow = true; + } + else if (settings.ResponseType == OpenIdConnectResponseType.CodeToken) + { + model.UseCodeTokenFlow = true; + } + else if (settings.ResponseType == OpenIdConnectResponseType.IdToken) + { + model.UseIdTokenFlow = true; + } + else if (settings.ResponseType == OpenIdConnectResponseType.IdTokenToken) + { + model.UseIdTokenTokenFlow = true; + } + + model.Parameters = JConvert.SerializeObject(settings.Parameters, JOptions.CamelCase); + } + ) + .Location("Content:2") + .OnGroup(SettingsGroupId); } public override async Task UpdateAsync(OpenIdClientSettings settings, BuildEditorContext context) @@ -163,9 +169,7 @@ public override async Task UpdateAsync(OpenIdClientSettings sett try { - settings.Parameters = string.IsNullOrWhiteSpace(model.Parameters) - ? [] - : JConvert.DeserializeObject(model.Parameters); + settings.Parameters = string.IsNullOrWhiteSpace(model.Parameters) ? [] : JConvert.DeserializeObject(model.Parameters); } catch { diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Drivers/OpenIdServerSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Drivers/OpenIdServerSettingsDisplayDriver.cs index 1d58af902c8..c71e7f678d8 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Drivers/OpenIdServerSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Drivers/OpenIdServerSettingsDisplayDriver.cs @@ -14,59 +14,66 @@ public class OpenIdServerSettingsDisplayDriver : DisplayDriver _serverService = serverService; - - public override Task EditAsync(OpenIdServerSettings settings, BuildEditorContext context) - => Task.FromResult(Initialize("OpenIdServerSettings_Edit", async model => - { - model.AccessTokenFormat = settings.AccessTokenFormat; - model.Authority = settings.Authority?.AbsoluteUri; - - model.EncryptionCertificateStoreLocation = settings.EncryptionCertificateStoreLocation; - model.EncryptionCertificateStoreName = settings.EncryptionCertificateStoreName; - model.EncryptionCertificateThumbprint = settings.EncryptionCertificateThumbprint; - - model.SigningCertificateStoreLocation = settings.SigningCertificateStoreLocation; - model.SigningCertificateStoreName = settings.SigningCertificateStoreName; - model.SigningCertificateThumbprint = settings.SigningCertificateThumbprint; - - model.EnableAuthorizationEndpoint = settings.AuthorizationEndpointPath.HasValue; - model.EnableLogoutEndpoint = settings.LogoutEndpointPath.HasValue; - model.EnableTokenEndpoint = settings.TokenEndpointPath.HasValue; - model.EnableUserInfoEndpoint = settings.UserinfoEndpointPath.HasValue; - model.EnableIntrospectionEndpoint = settings.IntrospectionEndpointPath.HasValue; - model.EnableRevocationEndpoint = settings.RevocationEndpointPath.HasValue; - - model.AllowAuthorizationCodeFlow = settings.AllowAuthorizationCodeFlow; - model.AllowClientCredentialsFlow = settings.AllowClientCredentialsFlow; - model.AllowHybridFlow = settings.AllowHybridFlow; - model.AllowImplicitFlow = settings.AllowImplicitFlow; - model.AllowPasswordFlow = settings.AllowPasswordFlow; - model.AllowRefreshTokenFlow = settings.AllowRefreshTokenFlow; - - model.DisableAccessTokenEncryption = settings.DisableAccessTokenEncryption; - model.DisableRollingRefreshTokens = settings.DisableRollingRefreshTokens; - model.UseReferenceAccessTokens = settings.UseReferenceAccessTokens; - model.RequireProofKeyForCodeExchange = settings.RequireProofKeyForCodeExchange; - - foreach (var (certificate, location, name) in await _serverService.GetAvailableCertificatesAsync()) - { - model.AvailableCertificates.Add(new CertificateInfo - { - StoreLocation = location, - StoreName = name, - FriendlyName = certificate.FriendlyName, - Issuer = certificate.Issuer, - Subject = certificate.Subject, - NotBefore = certificate.NotBefore, - NotAfter = certificate.NotAfter, - ThumbPrint = certificate.Thumbprint, - HasPrivateKey = certificate.HasPrivateKey, - Archived = certificate.Archived - }); - } - }).Location("Content:2")); + public OpenIdServerSettingsDisplayDriver(IOpenIdServerService serverService) => _serverService = serverService; + + public override Task EditAsync(OpenIdServerSettings settings, BuildEditorContext context) => + Task.FromResult( + Initialize( + "OpenIdServerSettings_Edit", + async model => + { + model.AccessTokenFormat = settings.AccessTokenFormat; + model.Authority = settings.Authority?.AbsoluteUri; + + model.EncryptionCertificateStoreLocation = settings.EncryptionCertificateStoreLocation; + model.EncryptionCertificateStoreName = settings.EncryptionCertificateStoreName; + model.EncryptionCertificateThumbprint = settings.EncryptionCertificateThumbprint; + + model.SigningCertificateStoreLocation = settings.SigningCertificateStoreLocation; + model.SigningCertificateStoreName = settings.SigningCertificateStoreName; + model.SigningCertificateThumbprint = settings.SigningCertificateThumbprint; + + model.EnableAuthorizationEndpoint = settings.AuthorizationEndpointPath.HasValue; + model.EnableLogoutEndpoint = settings.LogoutEndpointPath.HasValue; + model.EnableTokenEndpoint = settings.TokenEndpointPath.HasValue; + model.EnableUserInfoEndpoint = settings.UserinfoEndpointPath.HasValue; + model.EnableIntrospectionEndpoint = settings.IntrospectionEndpointPath.HasValue; + model.EnableRevocationEndpoint = settings.RevocationEndpointPath.HasValue; + + model.AllowAuthorizationCodeFlow = settings.AllowAuthorizationCodeFlow; + model.AllowClientCredentialsFlow = settings.AllowClientCredentialsFlow; + model.AllowHybridFlow = settings.AllowHybridFlow; + model.AllowImplicitFlow = settings.AllowImplicitFlow; + model.AllowPasswordFlow = settings.AllowPasswordFlow; + model.AllowRefreshTokenFlow = settings.AllowRefreshTokenFlow; + + model.DisableAccessTokenEncryption = settings.DisableAccessTokenEncryption; + model.DisableRollingRefreshTokens = settings.DisableRollingRefreshTokens; + model.UseReferenceAccessTokens = settings.UseReferenceAccessTokens; + model.RequireProofKeyForCodeExchange = settings.RequireProofKeyForCodeExchange; + + foreach (var (certificate, location, name) in await _serverService.GetAvailableCertificatesAsync()) + { + model.AvailableCertificates.Add( + new CertificateInfo + { + StoreLocation = location, + StoreName = name, + FriendlyName = certificate.FriendlyName, + Issuer = certificate.Issuer, + Subject = certificate.Subject, + NotBefore = certificate.NotBefore, + NotAfter = certificate.NotAfter, + ThumbPrint = certificate.Thumbprint, + HasPrivateKey = certificate.HasPrivateKey, + Archived = certificate.Archived + } + ); + } + } + ) + .Location("Content:2") + ); public override async Task UpdateAsync(OpenIdServerSettings settings, UpdateEditorContext context) { @@ -84,18 +91,12 @@ public override async Task UpdateAsync(OpenIdServerSettings sett settings.SigningCertificateStoreName = model.SigningCertificateStoreName; settings.SigningCertificateThumbprint = model.SigningCertificateThumbprint; - settings.AuthorizationEndpointPath = model.EnableAuthorizationEndpoint ? - new PathString("/connect/authorize") : PathString.Empty; - settings.LogoutEndpointPath = model.EnableLogoutEndpoint ? - new PathString("/connect/logout") : PathString.Empty; - settings.TokenEndpointPath = model.EnableTokenEndpoint ? - new PathString("/connect/token") : PathString.Empty; - settings.UserinfoEndpointPath = model.EnableUserInfoEndpoint ? - new PathString("/connect/userinfo") : PathString.Empty; - settings.IntrospectionEndpointPath = model.EnableIntrospectionEndpoint ? - new PathString("/connect/introspect") : PathString.Empty; - settings.RevocationEndpointPath = model.EnableRevocationEndpoint ? - new PathString("/connect/revoke") : PathString.Empty; + settings.AuthorizationEndpointPath = model.EnableAuthorizationEndpoint ? new PathString("/connect/authorize") : PathString.Empty; + settings.LogoutEndpointPath = model.EnableLogoutEndpoint ? new PathString("/connect/logout") : PathString.Empty; + settings.TokenEndpointPath = model.EnableTokenEndpoint ? new PathString("/connect/token") : PathString.Empty; + settings.UserinfoEndpointPath = model.EnableUserInfoEndpoint ? new PathString("/connect/userinfo") : PathString.Empty; + settings.IntrospectionEndpointPath = model.EnableIntrospectionEndpoint ? new PathString("/connect/introspect") : PathString.Empty; + settings.RevocationEndpointPath = model.EnableRevocationEndpoint ? new PathString("/connect/revoke") : PathString.Empty; settings.AllowAuthorizationCodeFlow = model.AllowAuthorizationCodeFlow; settings.AllowClientCredentialsFlow = model.AllowClientCredentialsFlow; diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Drivers/OpenIdValidationSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Drivers/OpenIdValidationSettingsDisplayDriver.cs index 1843a661ebb..205c041513f 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Drivers/OpenIdValidationSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Drivers/OpenIdValidationSettingsDisplayDriver.cs @@ -16,37 +16,42 @@ public class OpenIdValidationSettingsDisplayDriver : DisplayDriver _shellHost = shellHost; + public OpenIdValidationSettingsDisplayDriver(IShellHost shellHost) => _shellHost = shellHost; - public override Task EditAsync(OpenIdValidationSettings settings, BuildEditorContext context) - => Task.FromResult(Initialize("OpenIdValidationSettings_Edit", async model => - { - model.Authority = settings.Authority?.AbsoluteUri; - model.MetadataAddress = settings.MetadataAddress?.AbsoluteUri; - model.Audience = settings.Audience; - model.DisableTokenTypeValidation = settings.DisableTokenTypeValidation; - model.Tenant = settings.Tenant; + public override Task EditAsync(OpenIdValidationSettings settings, BuildEditorContext context) => + Task.FromResult( + Initialize( + "OpenIdValidationSettings_Edit", + async model => + { + model.Authority = settings.Authority?.AbsoluteUri; + model.MetadataAddress = settings.MetadataAddress?.AbsoluteUri; + model.Audience = settings.Audience; + model.DisableTokenTypeValidation = settings.DisableTokenTypeValidation; + model.Tenant = settings.Tenant; - var availableTenants = new List(); + var availableTenants = new List(); - foreach (var shellSettings in _shellHost.GetAllSettings().Where(s => s.IsRunning())) - { - var shellScope = await _shellHost.GetScopeAsync(shellSettings); + foreach (var shellSettings in _shellHost.GetAllSettings().Where(s => s.IsRunning())) + { + var shellScope = await _shellHost.GetScopeAsync(shellSettings); - await shellScope.UsingAsync(scope => - { - var descriptor = scope.ServiceProvider.GetRequiredService(); - if (descriptor.Features.Any(feature => feature.Id == OpenIdConstants.Features.Server)) - { - availableTenants.Add(shellSettings.Name); - } - return Task.CompletedTask; - }); - } + await shellScope.UsingAsync(scope => + { + var descriptor = scope.ServiceProvider.GetRequiredService(); + if (descriptor.Features.Any(feature => feature.Id == OpenIdConstants.Features.Server)) + { + availableTenants.Add(shellSettings.Name); + } + return Task.CompletedTask; + }); + } - model.AvailableTenants = availableTenants; - }).Location("Content:2")); + model.AvailableTenants = availableTenants; + } + ) + .Location("Content:2") + ); public override async Task UpdateAsync(OpenIdValidationSettings settings, UpdateEditorContext context) { diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Handlers/OpenIdApplicationRoleRemovedEventHandler.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Handlers/OpenIdApplicationRoleRemovedEventHandler.cs index cbfbca53565..3943ff3e241 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Handlers/OpenIdApplicationRoleRemovedEventHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Handlers/OpenIdApplicationRoleRemovedEventHandler.cs @@ -9,8 +9,7 @@ public class OpenIdApplicationRoleRemovedEventHandler : IRoleRemovedEventHandler { private readonly IOpenIdApplicationManager _manager; - public OpenIdApplicationRoleRemovedEventHandler(IOpenIdApplicationManager manager) - => _manager = manager; + public OpenIdApplicationRoleRemovedEventHandler(IOpenIdApplicationManager manager) => _manager = manager; public async Task RoleRemovedAsync(string roleName) { diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Manifest.cs index 8a014aedf44..29c69cf3e1e 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Manifest.cs @@ -1,12 +1,7 @@ using OrchardCore.Modules.Manifest; using OrchardCore.OpenId; -[assembly: Module( - Name = "OpenID", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "OpenID", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = OpenIdConstants.Features.Core, @@ -21,10 +16,7 @@ Name = "OpenID Client", Category = "OpenID Connect", Description = "Authenticates users from an external OpenID Connect identity provider.", - Dependencies = - [ - OpenIdConstants.Features.Core, - ] + Dependencies = [OpenIdConstants.Features.Core,] )] [assembly: Feature( @@ -32,10 +24,7 @@ Name = "OpenID Management Interface", Category = "OpenID Connect", Description = "Allows adding, editing and removing the registered applications.", - Dependencies = - [ - OpenIdConstants.Features.Core, - ] + Dependencies = [OpenIdConstants.Features.Core,] )] [assembly: Feature( @@ -43,11 +32,7 @@ Name = "OpenID Authorization Server", Category = "OpenID Connect", Description = "Enables authentication of external applications using the OpenID Connect/OAuth 2.0 standards.", - Dependencies = - [ - OpenIdConstants.Features.Core, - OpenIdConstants.Features.Management, - ] + Dependencies = [OpenIdConstants.Features.Core, OpenIdConstants.Features.Management,] )] [assembly: Feature( @@ -55,8 +40,5 @@ Name = "OpenID Token Validation", Category = "OpenID Connect", Description = "Validates tokens issued by the Orchard OpenID server or by a remote server supporting JWT and OpenID Connect discovery.", - Dependencies = - [ - OpenIdConstants.Features.Core, - ] + Dependencies = [OpenIdConstants.Features.Core,] )] diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdApplicationSettings.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdApplicationSettings.cs index 7c634610ada..2eec297ed43 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdApplicationSettings.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdApplicationSettings.cs @@ -121,8 +121,7 @@ public static async Task UpdateDescriptorFromSettings(this IOpenIdApplicationMan descriptor.Permissions.Remove(OpenIddictConstants.Permissions.Endpoints.Authorization); } - if (model.AllowAuthorizationCodeFlow || model.AllowHybridFlow || - model.AllowClientCredentialsFlow || model.AllowPasswordFlow || model.AllowRefreshTokenFlow) + if (model.AllowAuthorizationCodeFlow || model.AllowHybridFlow || model.AllowClientCredentialsFlow || model.AllowPasswordFlow || model.AllowRefreshTokenFlow) { descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Token); } @@ -225,17 +224,13 @@ public static async Task UpdateDescriptorFromSettings(this IOpenIdApplicationMan } descriptor.PostLogoutRedirectUris.Clear(); - foreach (var uri in - (from uri in model.PostLogoutRedirectUris?.Split(_separator, StringSplitOptions.RemoveEmptyEntries) ?? [] - select new Uri(uri, UriKind.Absolute))) + foreach (var uri in (from uri in model.PostLogoutRedirectUris?.Split(_separator, StringSplitOptions.RemoveEmptyEntries) ?? [] select new Uri(uri, UriKind.Absolute))) { descriptor.PostLogoutRedirectUris.Add(uri); } descriptor.RedirectUris.Clear(); - foreach (var uri in - (from uri in model.RedirectUris?.Split(_separator, StringSplitOptions.RemoveEmptyEntries) ?? [] - select new Uri(uri, UriKind.Absolute))) + foreach (var uri in (from uri in model.RedirectUris?.Split(_separator, StringSplitOptions.RemoveEmptyEntries) ?? [] select new Uri(uri, UriKind.Absolute))) { descriptor.RedirectUris.Add(uri); } @@ -248,7 +243,6 @@ public static async Task UpdateDescriptorFromSettings(this IOpenIdApplicationMan { await _applicationManager.UpdateAsync(application, descriptor); } - } } } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdExtensions.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdExtensions.cs index c5b808e913f..aa8a3bda498 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdExtensions.cs @@ -8,22 +8,22 @@ namespace OrchardCore.OpenId { internal static class OpenIdExtensions { - internal static string GetUserIdentifier(this ClaimsIdentity identity) - => identity.FindFirst(Claims.Subject)?.Value ?? - identity.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? - identity.FindFirst(ClaimTypes.Upn)?.Value ?? - throw new InvalidOperationException("No suitable user identifier can be found in the identity."); - - internal static string GetUserIdentifier(this ClaimsPrincipal principal) - => principal.FindFirst(Claims.Subject)?.Value ?? - principal.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? - principal.FindFirst(ClaimTypes.Upn)?.Value ?? - throw new InvalidOperationException("No suitable user identifier can be found in the principal."); - - internal static string GetUserName(this ClaimsPrincipal principal) - => principal.FindFirst(Claims.Name)?.Value ?? - principal.FindFirst(ClaimTypes.Name)?.Value ?? - throw new InvalidOperationException("No suitable user name can be found in the principal."); + internal static string GetUserIdentifier(this ClaimsIdentity identity) => + identity.FindFirst(Claims.Subject)?.Value + ?? identity.FindFirst(ClaimTypes.NameIdentifier)?.Value + ?? identity.FindFirst(ClaimTypes.Upn)?.Value + ?? throw new InvalidOperationException("No suitable user identifier can be found in the identity."); + + internal static string GetUserIdentifier(this ClaimsPrincipal principal) => + principal.FindFirst(Claims.Subject)?.Value + ?? principal.FindFirst(ClaimTypes.NameIdentifier)?.Value + ?? principal.FindFirst(ClaimTypes.Upn)?.Value + ?? throw new InvalidOperationException("No suitable user identifier can be found in the principal."); + + internal static string GetUserName(this ClaimsPrincipal principal) => + principal.FindFirst(Claims.Name)?.Value + ?? principal.FindFirst(ClaimTypes.Name)?.Value + ?? throw new InvalidOperationException("No suitable user name can be found in the principal."); internal static async Task AnyAsync(this IAsyncEnumerable source) { diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Permissions.cs index 3ed8b1c9686..87253042bce 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Permissions.cs @@ -6,39 +6,19 @@ namespace OrchardCore.OpenId; public class Permissions : IPermissionProvider { - public static readonly Permission ManageApplications - = new("ManageApplications", "View, add, edit and remove the OpenID Connect applications."); - - public static readonly Permission ManageScopes - = new("ManageScopes", "View, add, edit and remove the OpenID Connect scopes."); - - public static readonly Permission ManageClientSettings - = new("ManageClientSettings", "View and edit the OpenID Connect client settings."); - - public static readonly Permission ManageServerSettings - = new("ManageServerSettings", "View and edit the OpenID Connect server settings."); - - public static readonly Permission ManageValidationSettings - = new("ManageValidationSettings", "View and edit the OpenID Connect validation settings."); - - private readonly IEnumerable _allPermissions = - [ - ManageApplications, - ManageScopes, - ManageClientSettings, - ManageServerSettings, - ManageValidationSettings, - ]; - - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); - - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public static readonly Permission ManageApplications = new("ManageApplications", "View, add, edit and remove the OpenID Connect applications."); + + public static readonly Permission ManageScopes = new("ManageScopes", "View, add, edit and remove the OpenID Connect scopes."); + + public static readonly Permission ManageClientSettings = new("ManageClientSettings", "View and edit the OpenID Connect client settings."); + + public static readonly Permission ManageServerSettings = new("ManageServerSettings", "View and edit the OpenID Connect server settings."); + + public static readonly Permission ManageValidationSettings = new("ManageValidationSettings", "View and edit the OpenID Connect validation settings."); + + private readonly IEnumerable _allPermissions = [ManageApplications, ManageScopes, ManageClientSettings, ManageServerSettings, ManageValidationSettings,]; + + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); + + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdScopeStep.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdScopeStep.cs index 7974664825c..68493e6df9a 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdScopeStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdScopeStep.cs @@ -45,9 +45,7 @@ public async Task ExecuteAsync(RecipeExecutionContext context) if (!string.IsNullOrEmpty(model.Resources)) { descriptor.Resources.Clear(); - descriptor.Resources.UnionWith( - model.Resources - .Split(' ', StringSplitOptions.RemoveEmptyEntries)); + descriptor.Resources.UnionWith(model.Resources.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } if (isNew) diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdServerSettingsStep.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdServerSettingsStep.cs index fc40623cb37..89c8e06817b 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdServerSettingsStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdServerSettingsStep.cs @@ -16,8 +16,7 @@ public class OpenIdServerSettingsStep : IRecipeStepHandler { private readonly IOpenIdServerService _serverService; - public OpenIdServerSettingsStep(IOpenIdServerService serverService) - => _serverService = serverService; + public OpenIdServerSettingsStep(IOpenIdServerService serverService) => _serverService = serverService; public async Task ExecuteAsync(RecipeExecutionContext context) { @@ -40,18 +39,12 @@ public async Task ExecuteAsync(RecipeExecutionContext context) settings.SigningCertificateStoreName = model.SigningCertificateStoreName; settings.SigningCertificateThumbprint = model.SigningCertificateThumbprint; - settings.AuthorizationEndpointPath = model.EnableAuthorizationEndpoint ? - new PathString("/connect/authorize") : PathString.Empty; - settings.LogoutEndpointPath = model.EnableLogoutEndpoint ? - new PathString("/connect/logout") : PathString.Empty; - settings.TokenEndpointPath = model.EnableTokenEndpoint ? - new PathString("/connect/token") : PathString.Empty; - settings.UserinfoEndpointPath = model.EnableUserInfoEndpoint ? - new PathString("/connect/userinfo") : PathString.Empty; - settings.IntrospectionEndpointPath = model.EnableIntrospectionEndpoint ? - new PathString("/connect/introspect") : PathString.Empty; - settings.RevocationEndpointPath = model.EnableRevocationEndpoint ? - new PathString("/connect/revoke") : PathString.Empty; + settings.AuthorizationEndpointPath = model.EnableAuthorizationEndpoint ? new PathString("/connect/authorize") : PathString.Empty; + settings.LogoutEndpointPath = model.EnableLogoutEndpoint ? new PathString("/connect/logout") : PathString.Empty; + settings.TokenEndpointPath = model.EnableTokenEndpoint ? new PathString("/connect/token") : PathString.Empty; + settings.UserinfoEndpointPath = model.EnableUserInfoEndpoint ? new PathString("/connect/userinfo") : PathString.Empty; + settings.IntrospectionEndpointPath = model.EnableIntrospectionEndpoint ? new PathString("/connect/introspect") : PathString.Empty; + settings.RevocationEndpointPath = model.EnableRevocationEndpoint ? new PathString("/connect/revoke") : PathString.Empty; settings.AllowAuthorizationCodeFlow = model.AllowAuthorizationCodeFlow; settings.AllowClientCredentialsFlow = model.AllowClientCredentialsFlow; diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdServerSettingsStepModel.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdServerSettingsStepModel.cs index 5693b4b040e..577dfa4e188 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdServerSettingsStepModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdServerSettingsStepModel.cs @@ -6,6 +6,7 @@ namespace OrchardCore.OpenId.Recipes public class OpenIdServerSettingsStepModel { public TokenFormat AccessTokenFormat { get; set; } = TokenFormat.DataProtection; + [Url] public string Authority { get; set; } public bool DisableAccessTokenEncryption { get; set; } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdValidationSettingsStep.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdValidationSettingsStep.cs index e305181a7ca..cf274a425f2 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdValidationSettingsStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdValidationSettingsStep.cs @@ -15,8 +15,7 @@ public class OpenIdValidationSettingsStep : IRecipeStepHandler { private readonly IOpenIdValidationService _validationService; - public OpenIdValidationSettingsStep(IOpenIdValidationService validationService) - => _validationService = validationService; + public OpenIdValidationSettingsStep(IOpenIdValidationService validationService) => _validationService = validationService; public async Task ExecuteAsync(RecipeExecutionContext context) { diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdValidationSettingsStepModel.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdValidationSettingsStepModel.cs index 729fdfef66f..8925c8584e2 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdValidationSettingsStepModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdValidationSettingsStepModel.cs @@ -2,7 +2,6 @@ namespace OrchardCore.OpenId.Recipes { public class OpenIdValidationSettingsStepModel { - public string MetadataAddress { get; set; } public string Audience { get; set; } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdClientService.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdClientService.cs index 6fad5099a0b..e95815f347b 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdClientService.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdClientService.cs @@ -15,9 +15,7 @@ public class OpenIdClientService : IOpenIdClientService private readonly ISiteService _siteService; protected readonly IStringLocalizer S; - public OpenIdClientService( - ISiteService siteService, - IStringLocalizer stringLocalizer) + public OpenIdClientService(ISiteService siteService, IStringLocalizer stringLocalizer) { _siteService = siteService; S = stringLocalizer; @@ -52,57 +50,44 @@ public Task> ValidateSettingsAsync(OpenIdClient if (settings.Authority == null) { - results.Add(new ValidationResult(S["The authority cannot be null or empty."], new[] - { - nameof(settings.Authority) - })); + results.Add(new ValidationResult(S["The authority cannot be null or empty."], new[] { nameof(settings.Authority) })); } else if (!settings.Authority.IsAbsoluteUri || !settings.Authority.IsWellFormedOriginalString()) { - results.Add(new ValidationResult(S["The authority must be a valid absolute URL."], new[] - { - nameof(settings.Authority) - })); + results.Add(new ValidationResult(S["The authority must be a valid absolute URL."], new[] { nameof(settings.Authority) })); } else if (!string.IsNullOrEmpty(settings.Authority.Query) || !string.IsNullOrEmpty(settings.Authority.Fragment)) { - results.Add(new ValidationResult(S["The authority cannot contain a query string or a fragment."], new[] - { - nameof(settings.Authority) - })); + results.Add(new ValidationResult(S["The authority cannot contain a query string or a fragment."], new[] { nameof(settings.Authority) })); } if (string.IsNullOrEmpty(settings.ResponseType)) { - results.Add(new ValidationResult(S["The response type cannot be null or empty."], new[] - { - nameof(settings.ResponseType) - })); + results.Add(new ValidationResult(S["The response type cannot be null or empty."], new[] { nameof(settings.ResponseType) })); } - else if (settings.ResponseType != OpenIdConnectResponseType.Code && settings.ResponseType != OpenIdConnectResponseType.CodeIdToken && - settings.ResponseType != OpenIdConnectResponseType.CodeIdTokenToken && settings.ResponseType != OpenIdConnectResponseType.CodeToken && - settings.ResponseType != OpenIdConnectResponseType.IdToken && settings.ResponseType != OpenIdConnectResponseType.IdTokenToken) + else if ( + settings.ResponseType != OpenIdConnectResponseType.Code + && settings.ResponseType != OpenIdConnectResponseType.CodeIdToken + && settings.ResponseType != OpenIdConnectResponseType.CodeIdTokenToken + && settings.ResponseType != OpenIdConnectResponseType.CodeToken + && settings.ResponseType != OpenIdConnectResponseType.IdToken + && settings.ResponseType != OpenIdConnectResponseType.IdTokenToken + ) { - results.Add(new ValidationResult(S["Unknown response type ."], new[] - { - nameof(settings.ResponseType) - })); + results.Add(new ValidationResult(S["Unknown response type ."], new[] { nameof(settings.ResponseType) })); } if (string.IsNullOrEmpty(settings.ResponseMode)) { - results.Add(new ValidationResult(S["The response mode cannot be null or empty."], new[] - { - nameof(settings.ResponseMode) - })); + results.Add(new ValidationResult(S["The response mode cannot be null or empty."], new[] { nameof(settings.ResponseMode) })); } - else if (settings.ResponseMode != OpenIdConnectResponseMode.FormPost && settings.ResponseMode != OpenIdConnectResponseMode.Fragment && - settings.ResponseMode != OpenIdConnectResponseMode.Query) + else if ( + settings.ResponseMode != OpenIdConnectResponseMode.FormPost + && settings.ResponseMode != OpenIdConnectResponseMode.Fragment + && settings.ResponseMode != OpenIdConnectResponseMode.Query + ) { - results.Add(new ValidationResult(S["Unknown response mode."], new[] - { - nameof(settings.ResponseMode) - })); + results.Add(new ValidationResult(S["Unknown response mode."], new[] { nameof(settings.ResponseMode) })); } return Task.FromResult(results.ToImmutable()); diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdServerService.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdServerService.cs index 81b6f398c94..fefa6e09bb3 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdServerService.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdServerService.cs @@ -38,7 +38,8 @@ public OpenIdServerService( IOptionsMonitor shellOptions, ShellSettings shellSettings, ISiteService siteService, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _dataProtector = dataProtectionProvider.CreateProtector(nameof(OpenIdServerService)); _logger = logger; @@ -99,9 +100,14 @@ public Task> ValidateSettingsAsync(OpenIdServer var results = ImmutableArray.CreateBuilder(); - if (!settings.AllowAuthorizationCodeFlow && !settings.AllowClientCredentialsFlow && - !settings.AllowHybridFlow && !settings.AllowImplicitFlow && - !settings.AllowPasswordFlow && !settings.AllowRefreshTokenFlow) + if ( + !settings.AllowAuthorizationCodeFlow + && !settings.AllowClientCredentialsFlow + && !settings.AllowHybridFlow + && !settings.AllowImplicitFlow + && !settings.AllowPasswordFlow + && !settings.AllowRefreshTokenFlow + ) { results.Add(new ValidationResult(S["At least one OpenID Connect flow must be enabled."])); } @@ -110,124 +116,104 @@ public Task> ValidateSettingsAsync(OpenIdServer { if (!settings.Authority.IsAbsoluteUri || !settings.Authority.IsWellFormedOriginalString()) { - results.Add(new ValidationResult(S["The authority must be a valid absolute URL."], new[] - { - nameof(settings.Authority) - })); + results.Add(new ValidationResult(S["The authority must be a valid absolute URL."], new[] { nameof(settings.Authority) })); } if (!string.IsNullOrEmpty(settings.Authority.Query) || !string.IsNullOrEmpty(settings.Authority.Fragment)) { - results.Add(new ValidationResult(S["The authority cannot contain a query string or a fragment."], new[] - { - nameof(settings.Authority) - })); + results.Add(new ValidationResult(S["The authority cannot contain a query string or a fragment."], new[] { nameof(settings.Authority) })); } } - if (settings.SigningCertificateStoreLocation != null && - settings.SigningCertificateStoreName != null && - !string.IsNullOrEmpty(settings.SigningCertificateThumbprint)) + if (settings.SigningCertificateStoreLocation != null && settings.SigningCertificateStoreName != null && !string.IsNullOrEmpty(settings.SigningCertificateThumbprint)) { - var certificate = GetCertificate( - settings.SigningCertificateStoreLocation.Value, - settings.SigningCertificateStoreName.Value, settings.SigningCertificateThumbprint); + var certificate = GetCertificate(settings.SigningCertificateStoreLocation.Value, settings.SigningCertificateStoreName.Value, settings.SigningCertificateThumbprint); if (certificate == null) { - results.Add(new ValidationResult(S["The certificate cannot be found."], new[] - { - nameof(settings.SigningCertificateThumbprint) - })); + results.Add(new ValidationResult(S["The certificate cannot be found."], new[] { nameof(settings.SigningCertificateThumbprint) })); } else if (!certificate.HasPrivateKey) { - results.Add(new ValidationResult(S["The certificate doesn't contain the required private key."], new[] - { - nameof(settings.SigningCertificateThumbprint) - })); + results.Add(new ValidationResult(S["The certificate doesn't contain the required private key."], new[] { nameof(settings.SigningCertificateThumbprint) })); } else if (certificate.Archived) { - results.Add(new ValidationResult(S["The certificate is not valid because it is marked as archived."], new[] - { - nameof(settings.SigningCertificateThumbprint) - })); + results.Add(new ValidationResult(S["The certificate is not valid because it is marked as archived."], new[] { nameof(settings.SigningCertificateThumbprint) })); } else if (certificate.NotBefore > DateTime.Now || certificate.NotAfter < DateTime.Now) { - results.Add(new ValidationResult(S["The certificate is not valid for current date."], new[] - { - nameof(settings.SigningCertificateThumbprint) - })); + results.Add(new ValidationResult(S["The certificate is not valid for current date."], new[] { nameof(settings.SigningCertificateThumbprint) })); } } if (settings.AllowPasswordFlow && !settings.TokenEndpointPath.HasValue) { - results.Add(new ValidationResult(S["The password flow cannot be enabled when the token endpoint is disabled."], new[] - { - nameof(settings.AllowPasswordFlow) - })); + results.Add(new ValidationResult(S["The password flow cannot be enabled when the token endpoint is disabled."], new[] { nameof(settings.AllowPasswordFlow) })); } if (settings.AllowClientCredentialsFlow && !settings.TokenEndpointPath.HasValue) { - results.Add(new ValidationResult(S["The client credentials flow cannot be enabled when the token endpoint is disabled."], new[] - { - nameof(settings.AllowClientCredentialsFlow) - })); + results.Add( + new ValidationResult( + S["The client credentials flow cannot be enabled when the token endpoint is disabled."], + new[] { nameof(settings.AllowClientCredentialsFlow) } + ) + ); } if (settings.AllowAuthorizationCodeFlow && (!settings.AuthorizationEndpointPath.HasValue || !settings.TokenEndpointPath.HasValue)) { - results.Add(new ValidationResult(S["The authorization code flow cannot be enabled when the authorization and token endpoints are disabled."], new[] - { - nameof(settings.AllowAuthorizationCodeFlow) - })); + results.Add( + new ValidationResult( + S["The authorization code flow cannot be enabled when the authorization and token endpoints are disabled."], + new[] { nameof(settings.AllowAuthorizationCodeFlow) } + ) + ); } if (settings.AllowRefreshTokenFlow) { if (!settings.TokenEndpointPath.HasValue) { - results.Add(new ValidationResult(S["The refresh token flow cannot be enabled when the token endpoint is disabled."], new[] - { - nameof(settings.AllowRefreshTokenFlow) - })); + results.Add( + new ValidationResult(S["The refresh token flow cannot be enabled when the token endpoint is disabled."], new[] { nameof(settings.AllowRefreshTokenFlow) }) + ); } if (!settings.AllowPasswordFlow && !settings.AllowAuthorizationCodeFlow && !settings.AllowHybridFlow) { - results.Add(new ValidationResult(S["The refresh token flow can only be enabled if the password, authorization code or hybrid flows are enabled."], new[] - { - nameof(settings.AllowRefreshTokenFlow) - })); + results.Add( + new ValidationResult( + S["The refresh token flow can only be enabled if the password, authorization code or hybrid flows are enabled."], + new[] { nameof(settings.AllowRefreshTokenFlow) } + ) + ); } } if (settings.AllowImplicitFlow && !settings.AuthorizationEndpointPath.HasValue) { - results.Add(new ValidationResult(S["The implicit flow cannot be enabled when the authorization endpoint is disabled."], new[] - { - nameof(settings.AllowImplicitFlow) - })); + results.Add( + new ValidationResult(S["The implicit flow cannot be enabled when the authorization endpoint is disabled."], new[] { nameof(settings.AllowImplicitFlow) }) + ); } if (settings.AllowHybridFlow && (!settings.AuthorizationEndpointPath.HasValue || !settings.TokenEndpointPath.HasValue)) { - results.Add(new ValidationResult(S["The hybrid flow cannot be enabled when the authorization and token endpoints are disabled."], new[] - { - nameof(settings.AllowHybridFlow) - })); + results.Add( + new ValidationResult( + S["The hybrid flow cannot be enabled when the authorization and token endpoints are disabled."], + new[] { nameof(settings.AllowHybridFlow) } + ) + ); } if (settings.DisableAccessTokenEncryption && settings.AccessTokenFormat != OpenIdServerSettings.TokenFormat.JsonWebToken) { - results.Add(new ValidationResult(S["Access token encryption can only be disabled when using JWT tokens."], new[] - { - nameof(settings.DisableAccessTokenEncryption) - })); + results.Add( + new ValidationResult(S["Access token encryption can only be disabled when using JWT tokens."], new[] { nameof(settings.DisableAccessTokenEncryption) }) + ); } return Task.FromResult(results.ToImmutable()); @@ -272,23 +258,29 @@ public async Task> GetEncryptionKeysAsync() // If a certificate was explicitly provided, return it immediately // instead of using the fallback managed certificates logic. - if (settings.EncryptionCertificateStoreLocation != null && - settings.EncryptionCertificateStoreName != null && - !string.IsNullOrEmpty(settings.EncryptionCertificateThumbprint)) + if ( + settings.EncryptionCertificateStoreLocation != null + && settings.EncryptionCertificateStoreName != null + && !string.IsNullOrEmpty(settings.EncryptionCertificateThumbprint) + ) { var certificate = GetCertificate( settings.EncryptionCertificateStoreLocation.Value, - settings.EncryptionCertificateStoreName.Value, settings.EncryptionCertificateThumbprint); + settings.EncryptionCertificateStoreName.Value, + settings.EncryptionCertificateThumbprint + ); if (certificate != null) { return [new X509SecurityKey(certificate)]; } - _logger.LogWarning("The encryption certificate '{Thumbprint}' could not be found in the " + - "{StoreLocation}/{StoreName} store.", settings.EncryptionCertificateThumbprint, - settings.EncryptionCertificateStoreLocation.Value.ToString(), - settings.EncryptionCertificateStoreName.Value.ToString()); + _logger.LogWarning( + "The encryption certificate '{Thumbprint}' could not be found in the " + "{StoreLocation}/{StoreName} store.", + settings.EncryptionCertificateThumbprint, + settings.EncryptionCertificateStoreLocation.Value.ToString(), + settings.EncryptionCertificateStoreName.Value.ToString() + ); } try @@ -298,9 +290,7 @@ public async Task> GetEncryptionKeysAsync() var certificates = (await GetCertificatesAsync(directory)).Select(tuple => tuple.certificate).ToList(); if (certificates.Any(certificate => certificate.NotAfter.AddDays(-7) > DateTime.Now)) { - return ImmutableArray.CreateRange( - from certificate in certificates - select new X509SecurityKey(certificate)); + return ImmutableArray.CreateRange(from certificate in certificates select new X509SecurityKey(certificate)); } try @@ -329,12 +319,15 @@ from certificate in certificates // and add it in the tenant memory cache so that future calls to this method return it. return [ - _memoryCache.GetOrCreate("05A24221-8C15-4E58-A0A7-56EC3E42E783", entry => - { - entry.SetPriority(CacheItemPriority.NeverRemove); + _memoryCache.GetOrCreate( + "05A24221-8C15-4E58-A0A7-56EC3E42E783", + entry => + { + entry.SetPriority(CacheItemPriority.NeverRemove); - return new RsaSecurityKey(GenerateRsaSecurityKey(size: 2048)); - }), + return new RsaSecurityKey(GenerateRsaSecurityKey(size: 2048)); + } + ), ]; } @@ -344,23 +337,21 @@ public async Task> GetSigningKeysAsync() // If a certificate was explicitly provided, return it immediately // instead of using the fallback managed certificates logic. - if (settings.SigningCertificateStoreLocation != null && - settings.SigningCertificateStoreName != null && - !string.IsNullOrEmpty(settings.SigningCertificateThumbprint)) + if (settings.SigningCertificateStoreLocation != null && settings.SigningCertificateStoreName != null && !string.IsNullOrEmpty(settings.SigningCertificateThumbprint)) { - var certificate = GetCertificate( - settings.SigningCertificateStoreLocation.Value, - settings.SigningCertificateStoreName.Value, settings.SigningCertificateThumbprint); + var certificate = GetCertificate(settings.SigningCertificateStoreLocation.Value, settings.SigningCertificateStoreName.Value, settings.SigningCertificateThumbprint); if (certificate != null) { return [new X509SecurityKey(certificate)]; } - _logger.LogWarning("The signing certificate '{Thumbprint}' could not be found in the " + - "{StoreLocation}/{StoreName} store.", settings.SigningCertificateThumbprint, - settings.SigningCertificateStoreLocation.Value.ToString(), - settings.SigningCertificateStoreName.Value.ToString()); + _logger.LogWarning( + "The signing certificate '{Thumbprint}' could not be found in the " + "{StoreLocation}/{StoreName} store.", + settings.SigningCertificateThumbprint, + settings.SigningCertificateStoreLocation.Value.ToString(), + settings.SigningCertificateStoreName.Value.ToString() + ); } try @@ -370,9 +361,7 @@ public async Task> GetSigningKeysAsync() var certificates = (await GetCertificatesAsync(directory)).Select(tuple => tuple.certificate).ToList(); if (certificates.Any(certificate => certificate.NotAfter.AddDays(-7) > DateTime.Now)) { - return ImmutableArray.CreateRange( - from certificate in certificates - select new X509SecurityKey(certificate)); + return ImmutableArray.CreateRange(from certificate in certificates select new X509SecurityKey(certificate)); } try @@ -401,12 +390,15 @@ from certificate in certificates // and add it in the tenant memory cache so that future calls to this method return it. return [ - _memoryCache.GetOrCreate("44788774-20E3-4499-86F0-AB7CE2DF97F6", entry => - { - entry.SetPriority(CacheItemPriority.NeverRemove); + _memoryCache.GetOrCreate( + "44788774-20E3-4499-86F0-AB7CE2DF97F6", + entry => + { + entry.SetPriority(CacheItemPriority.NeverRemove); - return new RsaSecurityKey(GenerateRsaSecurityKey(size: 2048)); - }), + return new RsaSecurityKey(GenerateRsaSecurityKey(size: 2048)); + } + ), ]; } @@ -459,17 +451,11 @@ private static X509Certificate2 GetCertificate(StoreLocation location, StoreName }; } - private static DirectoryInfo GetEncryptionCertificateDirectory(ShellOptions options, ShellSettings settings) - => Directory.CreateDirectory(Path.Combine( - options.ShellsApplicationDataPath, - options.ShellsContainerName, - settings.Name, "IdentityModel-Encryption-Certificates")); + private static DirectoryInfo GetEncryptionCertificateDirectory(ShellOptions options, ShellSettings settings) => + Directory.CreateDirectory(Path.Combine(options.ShellsApplicationDataPath, options.ShellsContainerName, settings.Name, "IdentityModel-Encryption-Certificates")); - private static DirectoryInfo GetSigningCertificateDirectory(ShellOptions options, ShellSettings settings) - => Directory.CreateDirectory(Path.Combine( - options.ShellsApplicationDataPath, - options.ShellsContainerName, - settings.Name, "IdentityModel-Signing-Certificates")); + private static DirectoryInfo GetSigningCertificateDirectory(ShellOptions options, ShellSettings settings) => + Directory.CreateDirectory(Path.Combine(options.ShellsApplicationDataPath, options.ShellsContainerName, settings.Name, "IdentityModel-Signing-Certificates")); private async Task> GetCertificatesAsync(DirectoryInfo directory) { @@ -517,9 +503,7 @@ async Task GetCertificateAsync(string path) try { // Note: ephemeral key sets are not supported on non-Windows platforms. - var flags = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? - X509KeyStorageFlags.EphemeralKeySet : - X509KeyStorageFlags.MachineKeySet; + var flags = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? X509KeyStorageFlags.EphemeralKeySet : X509KeyStorageFlags.MachineKeySet; return new X509Certificate2(path, password, flags); } @@ -529,13 +513,9 @@ async Task GetCertificateAsync(string path) // For more information, visit https://github.com/OrchardCMS/OrchardCore/issues/3222. catch (CryptographicException exception) { - _logger.LogDebug(exception, "A first-chance exception occurred while trying to extract " + - "a X.509 certificate with the default key storage options."); + _logger.LogDebug(exception, "A first-chance exception occurred while trying to extract " + "a X.509 certificate with the default key storage options."); - return new X509Certificate2(path, password, - X509KeyStorageFlags.MachineKeySet | - X509KeyStorageFlags.PersistKeySet | - X509KeyStorageFlags.Exportable); + return new X509Certificate2(path, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); } // Don't swallow exceptions thrown from the catch handler to ensure unrecoverable exceptions // (e.g caused by malformed X.509 certificates or invalid password) are correctly logged. @@ -608,12 +588,16 @@ private static RSA GenerateRsaSecurityKey(int size) if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Warning: ensure a null key name is specified to ensure the RSA key is not persisted by CNG. - var key = CngKey.Create(CngAlgorithm.Rsa, keyName: null, new CngKeyCreationParameters - { - ExportPolicy = CngExportPolicies.AllowPlaintextExport, - KeyCreationOptions = CngKeyCreationOptions.MachineKey, - Parameters = { new CngProperty("Length", BitConverter.GetBytes(size), CngPropertyOptions.None) } - }); + var key = CngKey.Create( + CngAlgorithm.Rsa, + keyName: null, + new CngKeyCreationParameters + { + ExportPolicy = CngExportPolicies.AllowPlaintextExport, + KeyCreationOptions = CngKeyCreationOptions.MachineKey, + Parameters = { new CngProperty("Length", BitConverter.GetBytes(size), CngPropertyOptions.None) } + } + ); return new RSACng(key); } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdValidationService.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdValidationService.cs index 4b17a6d5887..ec7aafbe4e2 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdValidationService.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Services/OpenIdValidationService.cs @@ -29,7 +29,8 @@ public OpenIdValidationService( ShellSettings shellSettings, IShellHost shellHost, ISiteService siteService, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _shellDescriptor = shellDescriptor; _shellSettings = shellSettings; @@ -61,10 +62,7 @@ private OpenIdValidationSettings GetSettingsFromContainer(ISite container) // feature will use the OpenID server registered in this tenant if it's been enabled. if (_shellDescriptor.Features.Any(feature => feature.Id == OpenIdConstants.Features.Server)) { - return new OpenIdValidationSettings - { - Tenant = _shellSettings.Name, - }; + return new OpenIdValidationSettings { Tenant = _shellSettings.Name, }; } return new OpenIdValidationSettings(); @@ -87,97 +85,63 @@ public async Task> ValidateSettingsAsync(OpenId if (!(settings.Authority == null ^ string.IsNullOrEmpty(settings.Tenant))) { - results.Add(new ValidationResult(S["Either a tenant or an authority must be registered."], new[] - { - nameof(settings.Authority), - nameof(settings.Tenant), - })); + results.Add(new ValidationResult(S["Either a tenant or an authority must be registered."], new[] { nameof(settings.Authority), nameof(settings.Tenant), })); } if (settings.Authority != null) { if (!settings.Authority.IsAbsoluteUri || !settings.Authority.IsWellFormedOriginalString()) { - results.Add(new ValidationResult(S["The specified authority is not valid."], new[] - { - nameof(settings.Authority) - })); + results.Add(new ValidationResult(S["The specified authority is not valid."], new[] { nameof(settings.Authority) })); } if (!string.IsNullOrEmpty(settings.Authority.Query) || !string.IsNullOrEmpty(settings.Authority.Fragment)) { - results.Add(new ValidationResult(S["The authority cannot contain a query string or a fragment."], new[] - { - nameof(settings.Authority), - })); + results.Add(new ValidationResult(S["The authority cannot contain a query string or a fragment."], new[] { nameof(settings.Authority), })); } - } if (settings.MetadataAddress != null) { if (!settings.MetadataAddress.IsAbsoluteUri || !settings.MetadataAddress.IsWellFormedOriginalString()) { - results.Add(new ValidationResult(S["The specified metadata address is not valid."], new[] - { - nameof(settings.MetadataAddress), - })); + results.Add(new ValidationResult(S["The specified metadata address is not valid."], new[] { nameof(settings.MetadataAddress), })); } if (!string.IsNullOrEmpty(settings.MetadataAddress.Query) || !string.IsNullOrEmpty(settings.MetadataAddress.Fragment)) { - results.Add(new ValidationResult(S["The metadata address cannot contain a query string or a fragment."], new[] - { - nameof(settings.MetadataAddress), - })); + results.Add(new ValidationResult(S["The metadata address cannot contain a query string or a fragment."], new[] { nameof(settings.MetadataAddress), })); } if (!string.IsNullOrEmpty(settings.Tenant)) { - results.Add(new ValidationResult(S["No metatada address can be set when using another tenant."], new[] - { - nameof(settings.MetadataAddress), - })); + results.Add(new ValidationResult(S["No metatada address can be set when using another tenant."], new[] { nameof(settings.MetadataAddress), })); } } if (!string.IsNullOrEmpty(settings.Tenant) && !string.IsNullOrEmpty(settings.Audience)) { - results.Add(new ValidationResult(S["No audience can be set when using another tenant."], new[] - { - nameof(settings.Audience), - })); + results.Add(new ValidationResult(S["No audience can be set when using another tenant."], new[] { nameof(settings.Audience), })); } if (settings.Authority != null && string.IsNullOrEmpty(settings.Audience)) { - results.Add(new ValidationResult(S["An audience must be set when configuring the authority."], new[] - { - nameof(settings.Audience), - })); + results.Add(new ValidationResult(S["An audience must be set when configuring the authority."], new[] { nameof(settings.Audience), })); } if (settings.Authority == null && settings.DisableTokenTypeValidation) { - results.Add(new ValidationResult(S["Token type validation can only be disabled for remote servers."], new[] - { - nameof(settings.DisableTokenTypeValidation), - })); + results.Add(new ValidationResult(S["Token type validation can only be disabled for remote servers."], new[] { nameof(settings.DisableTokenTypeValidation), })); } - if (!string.IsNullOrEmpty(settings.Audience) && - settings.Audience.StartsWith(OpenIdConstants.Prefixes.Tenant, StringComparison.OrdinalIgnoreCase)) + if (!string.IsNullOrEmpty(settings.Audience) && settings.Audience.StartsWith(OpenIdConstants.Prefixes.Tenant, StringComparison.OrdinalIgnoreCase)) { - results.Add(new ValidationResult(S["The audience cannot start with the special 'oct:' prefix."], new[] - { - nameof(settings.Audience), - })); + results.Add(new ValidationResult(S["The audience cannot start with the special 'oct:' prefix."], new[] { nameof(settings.Audience), })); } // If a tenant was specified, ensure it is valid, that the OpenID server feature // was enabled and that at least a scope linked with the current tenant exists. - if (!string.IsNullOrEmpty(settings.Tenant) && - !string.Equals(settings.Tenant, _shellSettings.Name)) + if (!string.IsNullOrEmpty(settings.Tenant) && !string.Equals(settings.Tenant, _shellSettings.Name)) { if (!_shellHost.TryGetSettings(settings.Tenant, out var shellSettings)) { @@ -192,29 +156,25 @@ await shellScope.UsingAsync(async scope => var options = scope.ServiceProvider.GetRequiredService>().CurrentValue; if (options.UseReferenceAccessTokens) { - results.Add(new ValidationResult(S["Selecting a server tenant for which reference access tokens are enabled is currently not supported."], new[] - { - nameof(settings.Tenant), - })); + results.Add( + new ValidationResult( + S["Selecting a server tenant for which reference access tokens are enabled is currently not supported."], + new[] { nameof(settings.Tenant), } + ) + ); } var manager = scope.ServiceProvider.GetService(); if (manager == null) { - results.Add(new ValidationResult(S["The specified tenant is not valid."], new[] - { - nameof(settings.Tenant), - })); + results.Add(new ValidationResult(S["The specified tenant is not valid."], new[] { nameof(settings.Tenant), })); } else { var resource = OpenIdConstants.Prefixes.Tenant + _shellSettings.Name; if (!await manager.FindByResourceAsync(resource).AnyAsync()) { - results.Add(new ValidationResult(S["No appropriate scope was found."], new[] - { - nameof(settings.Tenant), - })); + results.Add(new ValidationResult(S["No appropriate scope was found."], new[] { nameof(settings.Tenant), })); } } }); diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Settings/OpenIdValidationSettings.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Settings/OpenIdValidationSettings.cs index 3aacb8406de..873bd399c00 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Settings/OpenIdValidationSettings.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Settings/OpenIdValidationSettings.cs @@ -9,6 +9,5 @@ public class OpenIdValidationSettings public bool DisableTokenTypeValidation { get; set; } public string Tenant { get; set; } public Uri MetadataAddress { get; set; } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Startup.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Startup.cs index 4b011821039..df83cd0c1b6 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Startup.cs @@ -1,3 +1,8 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Builder; @@ -29,11 +34,6 @@ using OrchardCore.Security; using OrchardCore.Security.Permissions; using OrchardCore.Settings; -using System; -using System.ComponentModel.DataAnnotations; -using System.Diagnostics; -using System.Linq; -using System.Threading.Tasks; namespace OrchardCore.OpenId { @@ -44,20 +44,15 @@ public override void ConfigureServices(IServiceCollection services) // Register the OpenIddict core services and the Orchard migrations, managers and default YesSql stores. // The default YesSql stores can be replaced by another database by referencing the corresponding // OpenIddict package (e.g OpenIddict.EntityFrameworkCore) and registering it in the options. - services.AddOpenIddict() + services + .AddOpenIddict() .AddCore(options => { - options.AddOrchardMigrations() - .UseOrchardManagers() - .UseYesSql(); + options.AddOrchardMigrations().UseOrchardManagers().UseYesSql(); }); // Note: the following services are registered using TryAddEnumerable to prevent duplicate registrations. - services.TryAddEnumerable(new[] - { - ServiceDescriptor.Scoped(), - ServiceDescriptor.Scoped(), - }); + services.TryAddEnumerable(new[] { ServiceDescriptor.Scoped(), ServiceDescriptor.Scoped(), }); } } @@ -69,22 +64,25 @@ public override void ConfigureServices(IServiceCollection services) services.TryAddSingleton(); // Note: the following services are registered using TryAddEnumerable to prevent duplicate registrations. - services.TryAddEnumerable(new[] - { - ServiceDescriptor.Scoped, OpenIdClientSettingsDisplayDriver>(), - ServiceDescriptor.Scoped() - }); + services.TryAddEnumerable( + new[] + { + ServiceDescriptor.Scoped, OpenIdClientSettingsDisplayDriver>(), + ServiceDescriptor.Scoped() + } + ); // Register the options initializers required by the OpenID Connect client handler. - services.TryAddEnumerable(new[] - { - // Orchard-specific initializers: - ServiceDescriptor.Singleton, OpenIdClientConfiguration>(), - ServiceDescriptor.Singleton, OpenIdClientConfiguration>(), - - // Built-in initializers: - ServiceDescriptor.Singleton, OpenIdConnectPostConfigureOptions>() - }); + services.TryAddEnumerable( + new[] + { + // Orchard-specific initializers: + ServiceDescriptor.Singleton, OpenIdClientConfiguration>(), + ServiceDescriptor.Singleton, OpenIdClientConfiguration>(), + // Built-in initializers: + ServiceDescriptor.Singleton, OpenIdConnectPostConfigureOptions>() + } + ); } } @@ -93,7 +91,8 @@ public class ServerStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddOpenIddict() + services + .AddOpenIddict() .AddServer(options => { options.UseAspNetCore(); @@ -103,16 +102,17 @@ public override void ConfigureServices(IServiceCollection services) services.TryAddSingleton(); // Note: the following services are registered using TryAddEnumerable to prevent duplicate registrations. - services.TryAddEnumerable(new[] - { - ServiceDescriptor.Scoped(), - ServiceDescriptor.Scoped, OpenIdServerSettingsDisplayDriver>(), - ServiceDescriptor.Scoped(), - ServiceDescriptor.Scoped(), - ServiceDescriptor.Scoped(), - - ServiceDescriptor.Singleton() - }); + services.TryAddEnumerable( + new[] + { + ServiceDescriptor.Scoped(), + ServiceDescriptor.Scoped, OpenIdServerSettingsDisplayDriver>(), + ServiceDescriptor.Scoped(), + ServiceDescriptor.Scoped(), + ServiceDescriptor.Scoped(), + ServiceDescriptor.Singleton() + } + ); // Note: the OpenIddict ASP.NET host adds an authentication options initializer that takes care of // registering the server ASP.NET Core handler. Yet, it MUST NOT be registered at this stage @@ -121,13 +121,15 @@ public override void ConfigureServices(IServiceCollection services) // To prevent that, the initializer is manually removed from the services collection of the tenant. services.RemoveAll, OpenIddictServerAspNetCoreConfiguration>(); - services.TryAddEnumerable(new[] - { - ServiceDescriptor.Singleton, OpenIdServerConfiguration>(), - ServiceDescriptor.Singleton, OpenIdServerConfiguration>(), - ServiceDescriptor.Singleton, OpenIdServerConfiguration>(), - ServiceDescriptor.Singleton, OpenIdServerConfiguration>() - }); + services.TryAddEnumerable( + new[] + { + ServiceDescriptor.Singleton, OpenIdServerConfiguration>(), + ServiceDescriptor.Singleton, OpenIdServerConfiguration>(), + ServiceDescriptor.Singleton, OpenIdServerConfiguration>(), + ServiceDescriptor.Singleton, OpenIdServerConfiguration>() + } + ); } public override async ValueTask ConfigureAsync(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) @@ -209,7 +211,8 @@ public class ValidationStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddOpenIddict() + services + .AddOpenIddict() .AddValidation(options => { options.UseAspNetCore(); @@ -220,11 +223,13 @@ public override void ConfigureServices(IServiceCollection services) services.TryAddSingleton(); // Note: the following services are registered using TryAddEnumerable to prevent duplicate registrations. - services.TryAddEnumerable(new[] - { - ServiceDescriptor.Scoped, OpenIdValidationSettingsDisplayDriver>(), - ServiceDescriptor.Scoped() - }); + services.TryAddEnumerable( + new[] + { + ServiceDescriptor.Scoped, OpenIdValidationSettingsDisplayDriver>(), + ServiceDescriptor.Scoped() + } + ); // Note: the OpenIddict ASP.NET host adds an authentication options initializer that takes care of // registering the validation handler. Yet, it MUST NOT be registered at this stage as it is @@ -233,13 +238,15 @@ public override void ConfigureServices(IServiceCollection services) // To prevent that, the initializer is manually removed from the services collection of the tenant. services.RemoveAll, OpenIddictValidationAspNetCoreConfiguration>(); - services.TryAddEnumerable(new[] - { - ServiceDescriptor.Singleton, OpenIdValidationConfiguration>(), - ServiceDescriptor.Singleton, OpenIdValidationConfiguration>(), - ServiceDescriptor.Singleton, OpenIdValidationConfiguration>(), - ServiceDescriptor.Singleton, OpenIdValidationConfiguration>() - }); + services.TryAddEnumerable( + new[] + { + ServiceDescriptor.Singleton, OpenIdValidationConfiguration>(), + ServiceDescriptor.Singleton, OpenIdValidationConfiguration>(), + ServiceDescriptor.Singleton, OpenIdValidationConfiguration>(), + ServiceDescriptor.Singleton, OpenIdValidationConfiguration>() + } + ); } } @@ -273,7 +280,6 @@ public static IServiceCollection RemoveAll(this IServiceCollection services, Typ } public static IServiceCollection RemoveAll(this IServiceCollection services) - where TImplementation : TService - => services.RemoveAll(typeof(TService), typeof(TImplementation)); + where TImplementation : TService => services.RemoveAll(typeof(TService), typeof(TImplementation)); } } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/Tasks/OpenIdBackgroundTask.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/Tasks/OpenIdBackgroundTask.cs index 1d6ac0b848f..e9e648447e0 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/Tasks/OpenIdBackgroundTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/Tasks/OpenIdBackgroundTask.cs @@ -10,18 +10,13 @@ namespace OrchardCore.OpenId.Tasks { - [BackgroundTask( - Title = "OpenID Cleaner", - Schedule = "*/30 * * * *", - Description = "Performs various cleanup operations for OpenID features.")] + [BackgroundTask(Title = "OpenID Cleaner", Schedule = "*/30 * * * *", Description = "Performs various cleanup operations for OpenID features.")] public class OpenIdBackgroundTask : IBackgroundTask { private readonly ILogger _logger; private readonly IOpenIdServerService _serverService; - public OpenIdBackgroundTask( - ILogger logger, - IOpenIdServerService serverService) + public OpenIdBackgroundTask(ILogger logger, IOpenIdServerService serverService) { _logger = logger; _serverService = serverService; diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/ViewModels/CreateOpenIdApplicationViewModel.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/ViewModels/CreateOpenIdApplicationViewModel.cs index c8b9d6218eb..66271e8ef37 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/ViewModels/CreateOpenIdApplicationViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/ViewModels/CreateOpenIdApplicationViewModel.cs @@ -52,6 +52,7 @@ public class RoleEntry public string Name { get; set; } public bool Selected { get; set; } } + public class ScopeEntry { public string Name { get; set; } diff --git a/src/OrchardCore.Modules/OrchardCore.Placements/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Placements/AdminMenu.cs index 09f8f615551..72e23c1ea73 100644 --- a/src/OrchardCore.Modules/OrchardCore.Placements/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Placements/AdminMenu.cs @@ -20,14 +20,15 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Design"], design => design - .Add(S["Placements"], S["Placements"].PrefixPosition(), import => import - .Action("Index", "Admin", "OrchardCore.Placements") - .Permission(Permissions.ManagePlacements) - .LocalNav() + builder.Add( + S["Design"], + design => + design.Add( + S["Placements"], + S["Placements"].PrefixPosition(), + import => import.Action("Index", "Admin", "OrchardCore.Placements").Permission(Permissions.ManagePlacements).LocalNav() ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Placements/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Placements/Controllers/AdminController.cs index 674c73ec045..1689ab7e6a8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Placements/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Placements/Controllers/AdminController.cs @@ -46,7 +46,8 @@ public AdminController( IStringLocalizer stringLocalizer, INotifier notifier, IOptions pagerOptions, - IShapeFactory shapeFactory) + IShapeFactory shapeFactory + ) { _logger = logger; _authorizationService = authorizationService; @@ -71,10 +72,7 @@ public async Task Index(ContentOptions options, PagerParameters p var shapeTypes = await _placementsManager.ListShapePlacementsAsync(); - var shapeList = shapeTypes.Select(entry => new ShapePlacementViewModel - { - ShapeType = entry.Key - }).ToList(); + var shapeList = shapeTypes.Select(entry => new ShapePlacementViewModel { ShapeType = entry.Key }).ToList(); if (!string.IsNullOrWhiteSpace(options.Search)) { @@ -83,9 +81,7 @@ public async Task Index(ContentOptions options, PagerParameters p var count = shapeList.Count; - shapeList = shapeList.OrderBy(x => x.ShapeType) - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize).ToList(); + shapeList = shapeList.OrderBy(x => x.ShapeType).Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -104,21 +100,15 @@ public async Task Index(ContentOptions options, PagerParameters p Options = options, }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(ListShapePlacementsViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(ListShapePlacementsViewModel model) => + RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Create(string suggestion, string returnUrl = null) { @@ -140,7 +130,14 @@ public async Task Create(string suggestion, string returnUrl = nu return View(nameof(Edit), viewModel); } - public async Task Edit(string shapeType, string displayType = null, string contentType = null, string contentPart = null, string differentiator = null, string returnUrl = null) + public async Task Edit( + string shapeType, + string displayType = null, + string contentType = null, + string contentPart = null, + string differentiator = null, + string returnUrl = null + ) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements)) { @@ -151,11 +148,7 @@ public async Task Edit(string shapeType, string displayType = nul if (placementNodes.Count == 0 || ShouldCreateNode(placementNodes, displayType, contentType, contentPart, differentiator)) { - var generatedNode = new PlacementNode - { - DisplayType = displayType, - Differentiator = differentiator - }; + var generatedNode = new PlacementNode { DisplayType = displayType, Differentiator = differentiator }; if (!string.IsNullOrEmpty(contentType)) { @@ -170,11 +163,7 @@ public async Task Edit(string shapeType, string displayType = nul placementNodes.Add(generatedNode); } - var viewModel = new EditShapePlacementViewModel - { - ShapeType = shapeType, - Nodes = JConvert.SerializeObject(placementNodes, JOptions.Indented) - }; + var viewModel = new EditShapePlacementViewModel { ShapeType = shapeType, Nodes = JConvert.SerializeObject(placementNodes, JOptions.Indented) }; ViewData["ReturnUrl"] = returnUrl; return View(viewModel); @@ -199,8 +188,7 @@ public async Task Edit(EditShapePlacementViewModel viewModel, str try { - var placementNodes = JConvert.DeserializeObject(viewModel.Nodes) - ?? Enumerable.Empty(); + var placementNodes = JConvert.DeserializeObject(viewModel.Nodes) ?? Enumerable.Empty(); // Remove empty nodes. placementNodes = placementNodes.Where(node => !IsEmpty(node)); @@ -310,10 +298,11 @@ private static bool ShouldCreateNode(IEnumerable nodes, string di else { return !nodes.Any(node => - (string.IsNullOrEmpty(displayType) || node.DisplayType == displayType) && - (string.IsNullOrEmpty(contentType) || (node.Filters.ContainsKey("contentType") && FilterEquals(node.Filters["contentType"], contentType))) && - (string.IsNullOrEmpty(contentPart) || (node.Filters.ContainsKey("contentPart") && FilterEquals(node.Filters["contentPart"], contentPart))) && - (string.IsNullOrEmpty(differentiator) || node.Differentiator == differentiator)); + (string.IsNullOrEmpty(displayType) || node.DisplayType == displayType) + && (string.IsNullOrEmpty(contentType) || (node.Filters.ContainsKey("contentType") && FilterEquals(node.Filters["contentType"], contentType))) + && (string.IsNullOrEmpty(contentPart) || (node.Filters.ContainsKey("contentPart") && FilterEquals(node.Filters["contentPart"], contentPart))) + && (string.IsNullOrEmpty(differentiator) || node.Differentiator == differentiator) + ); } } @@ -325,7 +314,6 @@ private static bool IsEmpty(PlacementNode node) && (node.Wrappers == null || node.Wrappers.Length == 0); } - private static bool FilterEquals(object node, string value) { var jsonNode = JNode.FromObject(node); diff --git a/src/OrchardCore.Modules/OrchardCore.Placements/Deployment/PlacementsDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Placements/Deployment/PlacementsDeploymentSource.cs index f2c92873ab3..f82518dbf35 100644 --- a/src/OrchardCore.Modules/OrchardCore.Placements/Deployment/PlacementsDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Placements/Deployment/PlacementsDeploymentSource.cs @@ -31,11 +31,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan placementObjects[placement.Key] = JArray.FromObject(placement.Value); } - result.Steps.Add(new JsonObject - { - ["name"] = "Placements", - ["Placements"] = placementObjects, - }); + result.Steps.Add(new JsonObject { ["name"] = "Placements", ["Placements"] = placementObjects, }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Placements/Deployment/PlacementsDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Placements/Deployment/PlacementsDeploymentStepDriver.cs index f36d13850b4..8388fa4012b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Placements/Deployment/PlacementsDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Placements/Deployment/PlacementsDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class PlacementsDeploymentStepDriver : DisplayDriver _allPermissions = - [ - ManagePlacements, - ]; + private readonly IEnumerable _allPermissions = [ManagePlacements,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _allPermissions, - }, - ]; + [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, }, new PermissionStereotype { Name = "Editor", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Placements/Services/PlacementProvider.cs b/src/OrchardCore.Modules/OrchardCore.Placements/Services/PlacementProvider.cs index 524aa5b121b..77cfc036411 100644 --- a/src/OrchardCore.Modules/OrchardCore.Placements/Services/PlacementProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Placements/Services/PlacementProvider.cs @@ -14,9 +14,7 @@ public class PlacementProvider : IShapePlacementProvider private readonly PlacementsManager _placementsManager; private readonly IEnumerable _placementNodeFilterProviders; - public PlacementProvider( - PlacementsManager placementsManager, - IEnumerable placementNodeFilterProviders) + public PlacementProvider(PlacementsManager placementsManager, IEnumerable placementNodeFilterProviders) { _placementsManager = placementsManager; _placementNodeFilterProviders = placementNodeFilterProviders; @@ -33,9 +31,7 @@ public class PlacementInfoResolver : IPlacementInfoResolver private readonly IReadOnlyDictionary> _placements; private readonly IEnumerable _placementNodeFilterProviders; - public PlacementInfoResolver( - IReadOnlyDictionary> placements, - IEnumerable placementNodeFilterProviders) + public PlacementInfoResolver(IReadOnlyDictionary> placements, IEnumerable placementNodeFilterProviders) { _placements = placements; _placementNodeFilterProviders = placementNodeFilterProviders; @@ -66,10 +62,7 @@ public PlacementInfo ResolvePlacement(ShapePlacementContext placementContext) continue; } - placement ??= new PlacementInfo - { - Source = "OrchardCore.Placements", - }; + placement ??= new PlacementInfo { Source = "OrchardCore.Placements", }; if (!string.IsNullOrEmpty(placementRule.Location)) { @@ -98,8 +91,7 @@ public PlacementInfo ResolvePlacement(ShapePlacementContext placementContext) private static bool CheckFilter(ShapePlacementContext ctx, PlacementNode filter) => ShapePlacementParsingStrategy.CheckFilter(ctx, filter); - private Func BuildPredicate(Func predicate, - KeyValuePair term) + private Func BuildPredicate(Func predicate, KeyValuePair term) { return ShapePlacementParsingStrategy.BuildPredicate(predicate, term, _placementNodeFilterProviders); } diff --git a/src/OrchardCore.Modules/OrchardCore.Placements/Services/PlacementsManager.cs b/src/OrchardCore.Modules/OrchardCore.Placements/Services/PlacementsManager.cs index e9b1295e62d..bc03752cc79 100644 --- a/src/OrchardCore.Modules/OrchardCore.Placements/Services/PlacementsManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.Placements/Services/PlacementsManager.cs @@ -10,8 +10,7 @@ public class PlacementsManager { private readonly IPlacementStore _placementStore; - public PlacementsManager(IPlacementStore placementStore) - => _placementStore = placementStore; + public PlacementsManager(IPlacementStore placementStore) => _placementStore = placementStore; public async Task>> ListShapePlacementsAsync() { diff --git a/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentPartDefinitionDriver.cs b/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentPartDefinitionDriver.cs index 49d5bb6018a..9ade82641b0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentPartDefinitionDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentPartDefinitionDriver.cs @@ -20,39 +20,38 @@ public override IDisplayResult Edit(ContentPartDefinition contentPartDefinition) { var displayName = contentPartDefinition.DisplayName(); - return Initialize("PlacementSettings", model => - { - model.ContentSettingsEntries.Add( - new ContentSettingsEntry + return Initialize( + "PlacementSettings", + model => { - ShapeType = contentPartDefinition.Name, - Description = S["Placement for a {0} part", displayName] - }); - - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - ShapeType = contentPartDefinition.Name, - DisplayType = "Detail", - Description = S["Placement for a {0} part in detail views", displayName] - }); - - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - ShapeType = contentPartDefinition.Name, - DisplayType = "Summary", - Description = S["Placement for a {0} part in summary views", displayName] - }); - - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - ShapeType = $"{contentPartDefinition.Name}_Edit", - Description = S["Placement in admin editor for a {0} part", displayName] - }); - - }).Location("Shortcuts"); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry { ShapeType = contentPartDefinition.Name, Description = S["Placement for a {0} part", displayName] } + ); + + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + ShapeType = contentPartDefinition.Name, + DisplayType = "Detail", + Description = S["Placement for a {0} part in detail views", displayName] + } + ); + + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + ShapeType = contentPartDefinition.Name, + DisplayType = "Summary", + Description = S["Placement for a {0} part in summary views", displayName] + } + ); + + model.ContentSettingsEntries.Add( + new ContentSettingsEntry { ShapeType = $"{contentPartDefinition.Name}_Edit", Description = S["Placement in admin editor for a {0} part", displayName] } + ); + } + ) + .Location("Shortcuts"); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentPartFieldDefinitionDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentPartFieldDefinitionDisplayDriver.cs index d3fed6a3a05..46ad8e04885 100644 --- a/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentPartFieldDefinitionDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentPartFieldDefinitionDisplayDriver.cs @@ -17,48 +17,55 @@ public PlacementContentPartFieldDefinitionDisplayDriver(IStringLocalizer("PlacementSettings", model => - { - var shapeType = contentPartFieldDefinition.FieldDefinition.Name; - var partName = contentPartFieldDefinition.PartDefinition.Name; - var differentiator = $"{contentPartFieldDefinition.PartDefinition.Name}-{contentPartFieldDefinition.Name}"; - var displayName = contentPartFieldDefinition.DisplayName(); - - model.ContentSettingsEntries.Add( - new ContentSettingsEntry + return Initialize( + "PlacementSettings", + model => { - ShapeType = shapeType, - Differentiator = differentiator, - Description = S["Placement for the {0} field in a {1}", displayName, partName] - }); + var shapeType = contentPartFieldDefinition.FieldDefinition.Name; + var partName = contentPartFieldDefinition.PartDefinition.Name; + var differentiator = $"{contentPartFieldDefinition.PartDefinition.Name}-{contentPartFieldDefinition.Name}"; + var displayName = contentPartFieldDefinition.DisplayName(); - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - ShapeType = shapeType, - Differentiator = differentiator, - DisplayType = "Detail", - Description = S["Placement for the {0} field in a {1} in detail views", displayName, partName] - }); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + ShapeType = shapeType, + Differentiator = differentiator, + Description = S["Placement for the {0} field in a {1}", displayName, partName] + } + ); - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - ShapeType = shapeType, - Differentiator = differentiator, - DisplayType = "Summary", - Description = S["Placement for the {0} field in a {1} in summary views", displayName, partName] - }); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + ShapeType = shapeType, + Differentiator = differentiator, + DisplayType = "Detail", + Description = S["Placement for the {0} field in a {1} in detail views", displayName, partName] + } + ); - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - ShapeType = $"{shapeType}_Edit", - Differentiator = differentiator, - Description = S["Placement in admin editor for the {0} field in a {1}", displayName, partName] - }); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + ShapeType = shapeType, + Differentiator = differentiator, + DisplayType = "Summary", + Description = S["Placement for the {0} field in a {1} in summary views", displayName, partName] + } + ); - }).Location("Shortcuts"); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + ShapeType = $"{shapeType}_Edit", + Differentiator = differentiator, + Description = S["Placement in admin editor for the {0} field in a {1}", displayName, partName] + } + ); + } + ) + .Location("Shortcuts"); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentTypePartDefinitionDriver.cs b/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentTypePartDefinitionDriver.cs index 0cb4dfd7596..baee9af431e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentTypePartDefinitionDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Placements/Settings/PlacementContentTypePartDefinitionDriver.cs @@ -17,47 +17,54 @@ public PlacementContentTypePartDefinitionDriver(IStringLocalizer("PlacementSettings", model => - { - var contentType = contentTypePartDefinition.ContentTypeDefinition.Name; - var partName = contentTypePartDefinition.Name; - var displayName = contentTypePartDefinition.ContentTypeDefinition.DisplayName; - - model.ContentSettingsEntries.Add( - new ContentSettingsEntry + return Initialize( + "PlacementSettings", + model => { - ShapeType = partName, - ContentType = contentType, - Description = S["Placement for the {0} part in a {1} type", partName, displayName] - }); + var contentType = contentTypePartDefinition.ContentTypeDefinition.Name; + var partName = contentTypePartDefinition.Name; + var displayName = contentTypePartDefinition.ContentTypeDefinition.DisplayName; - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - ShapeType = partName, - ContentType = contentType, - DisplayType = "Detail", - Description = S["Placement for the {0} part in a {1} type in detail views", partName, displayName] - }); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + ShapeType = partName, + ContentType = contentType, + Description = S["Placement for the {0} part in a {1} type", partName, displayName] + } + ); - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - ShapeType = partName, - ContentType = contentType, - DisplayType = "Summary", - Description = S["Placement for the {0} part in a {1} type in summary views", partName, displayName] - }); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + ShapeType = partName, + ContentType = contentType, + DisplayType = "Detail", + Description = S["Placement for the {0} part in a {1} type in detail views", partName, displayName] + } + ); - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - ShapeType = $"{partName}_Edit", - ContentType = contentType, - Description = S["Placement in admin editor for the {0} part in a {1} type", partName, displayName] - }); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + ShapeType = partName, + ContentType = contentType, + DisplayType = "Summary", + Description = S["Placement for the {0} part in a {1} type in summary views", partName, displayName] + } + ); - }).Location("Shortcuts"); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + ShapeType = $"{partName}_Edit", + ContentType = contentType, + Description = S["Placement in admin editor for the {0} part in a {1} type", partName, displayName] + } + ); + } + ) + .Location("Shortcuts"); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.PublishLater/Drivers/PublishLaterPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.PublishLater/Drivers/PublishLaterPartDisplayDriver.cs index cfa862e0128..9a55d8e18fe 100644 --- a/src/OrchardCore.Modules/OrchardCore.PublishLater/Drivers/PublishLaterPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.PublishLater/Drivers/PublishLaterPartDisplayDriver.cs @@ -18,10 +18,7 @@ public class PublishLaterPartDisplayDriver : ContentPartDisplayDriver( - $"{nameof(PublishLaterPart)}_SummaryAdmin", - model => PopulateViewModel(part, model)) - .Location("SummaryAdmin", "Meta:25"); + return Initialize($"{nameof(PublishLaterPart)}_SummaryAdmin", model => PopulateViewModel(part, model)).Location("SummaryAdmin", "Meta:25"); } public override IDisplayResult Edit(PublishLaterPart part, BuildPartEditorContext context) { - return Initialize(GetEditorShapeType(context), - model => PopulateViewModel(part, model)) - .Location("Actions:10"); + return Initialize(GetEditorShapeType(context), model => PopulateViewModel(part, model)).Location("Actions:10"); } public override async Task UpdateAsync(PublishLaterPart part, IUpdateModel updater, UpdatePartEditorContext context) @@ -70,9 +62,7 @@ private async ValueTask PopulateViewModel(PublishLaterPart part, PublishLaterPar { viewModel.ContentItem = part.ContentItem; viewModel.ScheduledPublishUtc = part.ScheduledPublishUtc; - viewModel.ScheduledPublishLocalDateTime = part.ScheduledPublishUtc.HasValue ? - (await _localClock.ConvertToLocalAsync(part.ScheduledPublishUtc.Value)).DateTime : - null; + viewModel.ScheduledPublishLocalDateTime = part.ScheduledPublishUtc.HasValue ? (await _localClock.ConvertToLocalAsync(part.ScheduledPublishUtc.Value)).DateTime : null; } } } diff --git a/src/OrchardCore.Modules/OrchardCore.PublishLater/Indexes/PublishLaterPartIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.PublishLater/Indexes/PublishLaterPartIndexProvider.cs index ab6374a410b..d617897d783 100644 --- a/src/OrchardCore.Modules/OrchardCore.PublishLater/Indexes/PublishLaterPartIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.PublishLater/Indexes/PublishLaterPartIndexProvider.cs @@ -28,7 +28,7 @@ public override async Task UpdatedAsync(UpdateContentContext context) var part = context.ContentItem.As(); // Validate that the content definition contains this part, this prevents indexing parts - // that have been removed from the type definition, but are still present in the elements. + // that have been removed from the type definition, but are still present in the elements. if (part != null) { // Lazy initialization because of ISession cyclic dependency. @@ -45,12 +45,15 @@ public override async Task UpdatedAsync(UpdateContentContext context) } public string CollectionName { get; set; } + public Type ForType() => typeof(ContentItem); + public void Describe(IDescriptor context) => Describe((DescribeContext)context); public void Describe(DescribeContext context) { - context.For() + context + .For() .When(contentItem => contentItem.Has() || _partRemoved.Contains(contentItem.ContentItemId)) .Map(contentItem => { diff --git a/src/OrchardCore.Modules/OrchardCore.PublishLater/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.PublishLater/Migrations.cs index cf361cb78f9..e25076b0699 100644 --- a/src/OrchardCore.Modules/OrchardCore.PublishLater/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.PublishLater/Migrations.cs @@ -19,25 +19,17 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("PublishLaterPart", builder => builder - .Attachable() - .WithDescription("Adds the ability to schedule content items to be published at a given future date and time.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "PublishLaterPart", + builder => builder.Attachable().WithDescription("Adds the ability to schedule content items to be published at a given future date and time.") + ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId") - .Column("ScheduledPublishDateTimeUtc") - .Column("Published") - .Column("Latest") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table.Column("ContentItemId").Column("ScheduledPublishDateTimeUtc").Column("Published").Column("Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_PublishLaterPartIndex_DocumentId", - "Id", - "DocumentId", - "ContentItemId", - "ScheduledPublishDateTimeUtc", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_PublishLaterPartIndex_DocumentId", "Id", "DocumentId", "ContentItemId", "ScheduledPublishDateTimeUtc", "Published", "Latest") ); return 3; @@ -49,14 +41,10 @@ public async Task UpdateFrom1Async() // The 'ScheduledPublishUtc' column and related index are kept on existing databases, // this because dropping an index and altering a column don't work on all providers. - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn(nameof(PublishLaterPartIndex.ScheduledPublishDateTimeUtc)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn(nameof(PublishLaterPartIndex.ScheduledPublishDateTimeUtc))); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex($"IDX_PublishLaterPartIndex_ScheduledPublishDateTimeUtc", - "DocumentId", - "ScheduledPublishDateTimeUtc") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex($"IDX_PublishLaterPartIndex_ScheduledPublishDateTimeUtc", "DocumentId", "ScheduledPublishDateTimeUtc") ); return 2; @@ -78,13 +66,7 @@ await SchemaBuilder.AlterIndexTableAsync(table => await SchemaBuilder.AlterIndexTableAsync(table => { - table.CreateIndex("IDX_PublishLaterPartIndex_ScheduledPublishDateTimeUtc", - "Id", - "DocumentId", - "ContentItemId", - "ScheduledPublishDateTimeUtc", - "Published", - "Latest"); + table.CreateIndex("IDX_PublishLaterPartIndex_ScheduledPublishDateTimeUtc", "Id", "DocumentId", "ContentItemId", "ScheduledPublishDateTimeUtc", "Published", "Latest"); }); return 3; diff --git a/src/OrchardCore.Modules/OrchardCore.PublishLater/Services/ScheduledPublishingBackgroundTask.cs b/src/OrchardCore.Modules/OrchardCore.PublishLater/Services/ScheduledPublishingBackgroundTask.cs index 30a8f0a7605..f5c69a066e9 100644 --- a/src/OrchardCore.Modules/OrchardCore.PublishLater/Services/ScheduledPublishingBackgroundTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.PublishLater/Services/ScheduledPublishingBackgroundTask.cs @@ -13,10 +13,7 @@ namespace OrchardCore.PublishLater.Services; -[BackgroundTask( - Title = "Scheduled Content Items Publisher", - Schedule = "* * * * *", - Description = "Publishes content items when their scheduled publish date time arrives.")] +[BackgroundTask(Title = "Scheduled Content Items Publisher", Schedule = "* * * * *", Description = "Publishes content items when their scheduled publish date time arrives.")] public class ScheduledPublishingBackgroundTask : IBackgroundTask { private readonly ILogger _logger; diff --git a/src/OrchardCore.Modules/OrchardCore.PublishLater/Startup.cs b/src/OrchardCore.Modules/OrchardCore.PublishLater/Startup.cs index e984eae1aa3..ebe1d0b89e9 100644 --- a/src/OrchardCore.Modules/OrchardCore.PublishLater/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.PublishLater/Startup.cs @@ -17,7 +17,6 @@ namespace OrchardCore.PublishLater { public class Startup : StartupBase { - public override void ConfigureServices(IServiceCollection services) { services.Configure(o => @@ -25,9 +24,7 @@ public override void ConfigureServices(IServiceCollection services) o.MemberAccessStrategy.Register(); }); - services - .AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddDataMigration(); diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Queries/AdminMenu.cs index 894630c941f..9b9a7880f73 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/AdminMenu.cs @@ -20,17 +20,23 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Search"], NavigationConstants.AdminMenuSearchPosition, search => search - .AddClass("search") - .Id("search") - .Add(S["Queries"], S["Queries"].PrefixPosition(), contentItems => contentItems - .Add(S["All queries"], "1", queries => queries - .Action("Index", "Admin", "OrchardCore.Queries") - .Permission(Permissions.ManageQueries) - .LocalNav() - ) - ) + builder.Add( + S["Search"], + NavigationConstants.AdminMenuSearchPosition, + search => + search + .AddClass("search") + .Id("search") + .Add( + S["Queries"], + S["Queries"].PrefixPosition(), + contentItems => + contentItems.Add( + S["All queries"], + "1", + queries => queries.Action("Index", "Admin", "OrchardCore.Queries").Permission(Permissions.ManageQueries).LocalNav() + ) + ) ); return Task.CompletedTask; diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Controllers/AdminController.cs index bb5f1dbaa2d..9bddb93ed1a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Controllers/AdminController.cs @@ -46,7 +46,8 @@ public AdminController( INotifier notifier, IQueryManager queryManager, IEnumerable querySources, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _displayManager = displayManager; _authorizationService = authorizationService; @@ -77,10 +78,7 @@ public async Task Index(ContentOptions options, PagerParameters p queries = queries.Where(q => q.Name.Contains(options.Search, StringComparison.OrdinalIgnoreCase)); } - var results = queries - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize) - .ToList(); + var results = queries.Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -100,28 +98,17 @@ public async Task Index(ContentOptions options, PagerParameters p foreach (var query in results) { - model.Queries.Add(new QueryEntry - { - Query = query, - Shape = await _displayManager.BuildDisplayAsync(query, _updateModelAccessor.ModelUpdater, "SummaryAdmin") - }); + model.Queries.Add(new QueryEntry { Query = query, Shape = await _displayManager.BuildDisplayAsync(query, _updateModelAccessor.ModelUpdater, "SummaryAdmin") }); } - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(QueriesIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(QueriesIndexViewModel model) => RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Create(string id) { diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Controllers/ApiController.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Controllers/ApiController.cs index 95a471f2212..8680acd90b5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Controllers/ApiController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Controllers/ApiController.cs @@ -17,10 +17,7 @@ public class ApiController : Controller private readonly IAuthorizationService _authorizationService; private readonly IQueryManager _queryManager; - public ApiController( - IAuthorizationService authorizationService, - IQueryManager queryManager - ) + public ApiController(IAuthorizationService authorizationService, IQueryManager queryManager) { _authorizationService = authorizationService; _queryManager = queryManager; @@ -28,9 +25,7 @@ IQueryManager queryManager [HttpPost, HttpGet] [Route("{name}")] - public async Task Query( - string name, - string parameters) + public async Task Query(string name, string parameters) { var query = await _queryManager.GetQueryAsync(name); @@ -52,9 +47,7 @@ public async Task Query( parameters = await reader.ReadToEndAsync(); } - var queryParameters = !string.IsNullOrEmpty(parameters) ? - JConvert.DeserializeObject>(parameters) - : []; + var queryParameters = !string.IsNullOrEmpty(parameters) ? JConvert.DeserializeObject>(parameters) : []; var result = await _queryManager.ExecuteQueryAsync(query, queryParameters); return new ObjectResult(result); diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Deployment/AllQueriesDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Deployment/AllQueriesDeploymentSource.cs index 7c7b4643f07..ca36dce5856 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Deployment/AllQueriesDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Deployment/AllQueriesDeploymentSource.cs @@ -24,11 +24,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan var queries = await _queryManager.ListQueriesAsync(); - result.Steps.Add(new JsonObject - { - ["name"] = "Queries", - ["Queries"] = JArray.FromObject(queries), - }); + result.Steps.Add(new JsonObject { ["name"] = "Queries", ["Queries"] = JArray.FromObject(queries), }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Deployment/AllQueriesDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Deployment/AllQueriesDeploymentStepDriver.cs index e49ea719392..d9d2c48e640 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Deployment/AllQueriesDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Deployment/AllQueriesDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class AllQueriesDeploymentStepDriver : DisplayDriver stringLocalizer) + public QueryBasedContentDeploymentStepDriver(IQueryManager queryManager, IStringLocalizer stringLocalizer) { _queryManager = queryManager; S = stringLocalizer; @@ -27,28 +25,39 @@ public QueryBasedContentDeploymentStepDriver( public override IDisplayResult Display(QueryBasedContentDeploymentStep step) { - return - Combine( - View("QueryBasedContentDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("QueryBasedContentDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("QueryBasedContentDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("QueryBasedContentDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(QueryBasedContentDeploymentStep step) { - return Initialize("QueryBasedContentDeploymentStep_Fields_Edit", model => - { - model.QueryName = step.QueryName; - model.QueryParameters = step.QueryParameters; - model.ExportAsSetupRecipe = step.ExportAsSetupRecipe; - }).Location("Content"); + return Initialize( + "QueryBasedContentDeploymentStep_Fields_Edit", + model => + { + model.QueryName = step.QueryName; + model.QueryParameters = step.QueryParameters; + model.ExportAsSetupRecipe = step.ExportAsSetupRecipe; + } + ) + .Location("Content"); } public override async Task UpdateAsync(QueryBasedContentDeploymentStep step, IUpdateModel updater) { var queryBasedContentViewModel = new QueryBasedContentDeploymentStepViewModel(); - if (await updater.TryUpdateModelAsync(queryBasedContentViewModel, Prefix, viewModel => viewModel.QueryName, viewModel => viewModel.QueryParameters, viewModel => viewModel.ExportAsSetupRecipe)) + if ( + await updater.TryUpdateModelAsync( + queryBasedContentViewModel, + Prefix, + viewModel => viewModel.QueryName, + viewModel => viewModel.QueryParameters, + viewModel => viewModel.ExportAsSetupRecipe + ) + ) { var query = await _queryManager.LoadQueryAsync(queryBasedContentViewModel.QueryName); if (!query.ResultsOfType()) diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Drivers/QueryDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Drivers/QueryDisplayDriver.cs index 1253b8f681c..a7c9c93b73a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Drivers/QueryDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Drivers/QueryDisplayDriver.cs @@ -22,40 +22,56 @@ public QueryDisplayDriver(IQueryManager queryManager, IStringLocalizer - { - model.Name = query.Name; - model.Source = query.Source; - model.Schema = query.Schema; - model.Query = query; - }).Location("Content:1"), - Dynamic("Query_Buttons_SummaryAdmin", model => - { - model.Name = query.Name; - model.Source = query.Source; - model.Schema = query.Schema; - model.Query = query; - }).Location("Actions:5") + Dynamic( + "Query_Fields_SummaryAdmin", + model => + { + model.Name = query.Name; + model.Source = query.Source; + model.Schema = query.Schema; + model.Query = query; + } + ) + .Location("Content:1"), + Dynamic( + "Query_Buttons_SummaryAdmin", + model => + { + model.Name = query.Name; + model.Source = query.Source; + model.Schema = query.Schema; + model.Query = query; + } + ) + .Location("Actions:5") ); } public override IDisplayResult Edit(Query query, IUpdateModel updater) { return Combine( - Initialize("Query_Fields_Edit", model => - { - model.Name = query.Name; - model.Source = query.Source; - model.Schema = query.Schema; - model.Query = query; - }).Location("Content:1"), - Initialize("Query_Fields_Buttons", model => - { - model.Name = query.Name; - model.Source = query.Source; - model.Schema = query.Schema; - model.Query = query; - }).Location("Actions:5") + Initialize( + "Query_Fields_Edit", + model => + { + model.Name = query.Name; + model.Source = query.Source; + model.Schema = query.Schema; + model.Query = query; + } + ) + .Location("Content:1"), + Initialize( + "Query_Fields_Buttons", + model => + { + model.Name = query.Name; + model.Source = query.Source; + model.Schema = query.Schema; + model.Query = query; + } + ) + .Location("Actions:5") ); } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Liquid/LiquidQueriesAccessor.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Liquid/LiquidQueriesAccessor.cs index adc2334b6cc..eef1623abce 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Liquid/LiquidQueriesAccessor.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Liquid/LiquidQueriesAccessor.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Liquid /// /// This is a placeholder class that allows modules to extend the `Queries` property in the current Liquid scope. /// - public class LiquidQueriesAccessor - { - } + public class LiquidQueriesAccessor { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Manifest.cs index bb8d5dd827a..64e4b0dbbf7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Manifest.cs @@ -1,11 +1,6 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Queries", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Queries", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Queries", diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Permissions.cs index e8766208f81..b9f5c1e38ea 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Permissions.cs @@ -11,10 +11,7 @@ public class Permissions : IPermissionProvider private static readonly Permission _executeApi = new("ExecuteApi_{0}", "Execute Api - {0}", new[] { ManageQueries, ExecuteApiAll }); - private readonly IEnumerable _generalPermissions = - [ - ManageQueries, - ]; + private readonly IEnumerable _generalPermissions = [ManageQueries,]; private readonly IQueryManager _queryManager; @@ -25,11 +22,7 @@ public Permissions(IQueryManager queryManager) public async Task> GetPermissionsAsync() { - var list = new List() - { - ManageQueries, - ExecuteApiAll, - }; + var list = new List() { ManageQueries, ExecuteApiAll, }; foreach (var query in await _queryManager.ListQueriesAsync()) { @@ -40,23 +33,11 @@ public async Task> GetPermissionsAsync() } public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _generalPermissions, - }, - ]; - - public static Permission CreatePermissionForQuery(string name) - => new( - string.Format(_executeApi.Name, name), - string.Format(_executeApi.Description, name), - _executeApi.ImpliedBy - ); + [ + new PermissionStereotype { Name = "Administrator", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Editor", Permissions = _generalPermissions, }, + ]; + + public static Permission CreatePermissionForQuery(string name) => + new(string.Format(_executeApi.Name, name), string.Format(_executeApi.Description, name), _executeApi.ImpliedBy); } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/QueryGlobalMethodProvider.cs b/src/OrchardCore.Modules/OrchardCore.Queries/QueryGlobalMethodProvider.cs index b9fdd9c044a..a02876222a8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/QueryGlobalMethodProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/QueryGlobalMethodProvider.cs @@ -18,18 +18,21 @@ public QueryGlobalMethodProvider() _executeQuery = new GlobalMethod { Name = "executeQuery", - Method = serviceProvider => (Func)((name, parameters) => - { - var queryManager = serviceProvider.GetRequiredService(); - var query = queryManager.GetQueryAsync(name).GetAwaiter().GetResult(); - if (query == null) - { - return null; - } + Method = serviceProvider => + (Func)( + (name, parameters) => + { + var queryManager = serviceProvider.GetRequiredService(); + var query = queryManager.GetQueryAsync(name).GetAwaiter().GetResult(); + if (query == null) + { + return null; + } - var result = queryManager.ExecuteQueryAsync(query, (IDictionary)parameters).GetAwaiter().GetResult(); - return result.Items; - }), + var result = queryManager.ExecuteQueryAsync(query, (IDictionary)parameters).GetAwaiter().GetResult(); + return result.Items; + } + ), }; } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Recipes/QueryStep.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Recipes/QueryStep.cs index 56f988b7913..efa1b981bb0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Recipes/QueryStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Recipes/QueryStep.cs @@ -18,10 +18,7 @@ public class QueryStep : IRecipeStepHandler private readonly IEnumerable _querySources; private readonly ILogger _logger; - public QueryStep( - IQueryManager queryManager, - IEnumerable querySources, - ILogger logger) + public QueryStep(IQueryManager queryManager, IEnumerable querySources, ILogger logger) { _queryManager = queryManager; _querySources = querySources; @@ -44,7 +41,11 @@ public async Task ExecuteAsync(RecipeExecutionContext context) if (sample == null) { - _logger.LogError("Could not find query source: '{QuerySource}'. The query '{QueryName}' will not be imported.", sourceName, token[nameof(Query.Name)].ToString()); + _logger.LogError( + "Could not find query source: '{QuerySource}'. The query '{QueryName}' will not be imported.", + sourceName, + token[nameof(Query.Name)].ToString() + ); continue; } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Services/QueryManager.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Services/QueryManager.cs index 0f475ca98c6..c21103bee50 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Services/QueryManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Services/QueryManager.cs @@ -75,8 +75,7 @@ public async Task SaveQueryAsync(string name, Query query) public Task ExecuteQueryAsync(Query query, IDictionary parameters) { - var querySource = _querySources.FirstOrDefault(q => q.Name == query.Source) - ?? throw new ArgumentException("Query source not found: " + query.Source); + var querySource = _querySources.FirstOrDefault(q => q.Name == query.Source) ?? throw new ArgumentException("Query source not found: " + query.Source); return querySource.ExecuteQueryAsync(query, parameters); } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/AdminMenu.cs index c8b70beb92f..9796da71270 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/AdminMenu.cs @@ -20,16 +20,20 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Search"], search => search - .Add(S["Queries"], S["Queries"].PrefixPosition(), queries => queries - .Add(S["Run SQL Query"], S["Run SQL Query"].PrefixPosition(), sql => sql - .Action("Query", "Admin", "OrchardCore.Queries") - .Permission(Permissions.ManageSqlQueries) - .LocalNav() - ) + builder.Add( + S["Search"], + search => + search.Add( + S["Queries"], + S["Queries"].PrefixPosition(), + queries => + queries.Add( + S["Run SQL Query"], + S["Run SQL Query"].PrefixPosition(), + sql => sql.Action("Query", "Admin", "OrchardCore.Queries").Permission(Permissions.ManageSqlQueries).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Controllers/AdminController.cs index e725dd18a30..1705f789cb2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Controllers/AdminController.cs @@ -33,8 +33,8 @@ public AdminController( IStore store, ILiquidTemplateManager liquidTemplateManager, IStringLocalizer stringLocalizer, - IOptions templateOptions) - + IOptions templateOptions + ) { _authorizationService = authorizationService; _store = store; @@ -47,11 +47,7 @@ public AdminController( public Task Query(string query) { query = string.IsNullOrWhiteSpace(query) ? "" : System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(query)); - return Query(new AdminQueryViewModel - { - DecodedQuery = query, - FactoryName = _store.Configuration.ConnectionFactory.GetType().FullName - }); + return Query(new AdminQueryViewModel { DecodedQuery = query, FactoryName = _store.Configuration.ConnectionFactory.GetType().FullName }); } [HttpPost] @@ -81,7 +77,11 @@ public async Task Query(AdminQueryViewModel model) var parameters = JConvert.DeserializeObject>(model.Parameters); - var tokenizedQuery = await _liquidTemplateManager.RenderStringAsync(model.DecodedQuery, NullEncoder.Default, parameters.Select(x => new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions)))); + var tokenizedQuery = await _liquidTemplateManager.RenderStringAsync( + model.DecodedQuery, + NullEncoder.Default, + parameters.Select(x => new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions))) + ); if (SqlParser.TryParse(tokenizedQuery, _store.Configuration.Schema, dialect, _store.Configuration.TablePrefix, parameters, out var rawQuery, out var messages)) { diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Drivers/SqlQueryDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Drivers/SqlQueryDisplayDriver.cs index d0ce86cca59..a4ec3918063 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Drivers/SqlQueryDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Drivers/SqlQueryDisplayDriver.cs @@ -19,30 +19,42 @@ public SqlQueryDisplayDriver(IStringLocalizer stringLocal public override IDisplayResult Display(SqlQuery query, IUpdateModel updater) { return Combine( - Dynamic("SqlQuery_SummaryAdmin", model => - { - model.Query = query; - }).Location("Content:5"), - Dynamic("SqlQuery_Buttons_SummaryAdmin", model => - { - model.Query = query; - }).Location("Actions:2") + Dynamic( + "SqlQuery_SummaryAdmin", + model => + { + model.Query = query; + } + ) + .Location("Content:5"), + Dynamic( + "SqlQuery_Buttons_SummaryAdmin", + model => + { + model.Query = query; + } + ) + .Location("Actions:2") ); } public override IDisplayResult Edit(SqlQuery query, IUpdateModel updater) { - return Initialize("SqlQuery_Edit", model => - { - model.Query = query.Template; - model.ReturnDocuments = query.ReturnDocuments; + return Initialize( + "SqlQuery_Edit", + model => + { + model.Query = query.Template; + model.ReturnDocuments = query.ReturnDocuments; - // Extract query from the query string if we come from the main query editor. - if (string.IsNullOrEmpty(query.Template)) - { - updater.TryUpdateModelAsync(model, "", m => m.Query); - } - }).Location("Content:5"); + // Extract query from the query string if we come from the main query editor. + if (string.IsNullOrEmpty(query.Template)) + { + updater.TryUpdateModelAsync(model, "", m => m.Query); + } + } + ) + .Location("Content:5"); } public override async Task UpdateAsync(SqlQuery model, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/GraphQL/SqlQueryFieldTypeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/GraphQL/SqlQueryFieldTypeProvider.cs index e8dad56d815..9c7af15df83 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/GraphQL/SqlQueryFieldTypeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/GraphQL/SqlQueryFieldTypeProvider.cs @@ -30,6 +30,7 @@ public SqlQueryFieldTypeProvider(IHttpContextAccessor httpContextAccessor, ILogg _httpContextAccessor = httpContextAccessor; _logger = logger; } + public Task GetIdentifierAsync() { var queryManager = _httpContextAccessor.HttpContext.RequestServices.GetService(); @@ -92,10 +93,7 @@ private static FieldType BuildSchemaBasedFieldType(SqlQuery query, JsonNode quer return null; } - var typetype = new ObjectGraphType - { - Name = fieldTypeName - }; + var typetype = new ObjectGraphType { Name = fieldTypeName }; foreach (var child in properties) { @@ -133,7 +131,7 @@ private static FieldType BuildSchemaBasedFieldType(SqlQuery query, JsonNode quer return source[context.FieldDefinition.Metadata["Name"].ToString()].ToObject(); }), }; - + field.Metadata.Add("Name", name); typetype.AddField(field); } @@ -141,9 +139,7 @@ private static FieldType BuildSchemaBasedFieldType(SqlQuery query, JsonNode quer var fieldType = new FieldType { - Arguments = new QueryArguments( - new QueryArgument { Name = "parameters" } - ), + Arguments = new QueryArguments(new QueryArgument { Name = "parameters" }), Name = fieldTypeName, Description = "Represents the " + query.Source + " Query : " + query.Name, @@ -159,9 +155,7 @@ async ValueTask ResolveAsync(IResolveFieldContext context) var parameters = context.GetArgument("parameters"); - var queryParameters = parameters != null ? - JConvert.DeserializeObject>(parameters) - : []; + var queryParameters = parameters != null ? JConvert.DeserializeObject>(parameters) : []; var result = await queryManager.ExecuteQueryAsync(iquery, queryParameters); @@ -181,9 +175,7 @@ private static FieldType BuildContentTypeFieldType(ISchema schema, string conten var fieldType = new FieldType { - Arguments = new QueryArguments( - new QueryArgument { Name = "parameters" } - ), + Arguments = new QueryArguments(new QueryArgument { Name = "parameters" }), Name = fieldTypeName, Description = "Represents the " + query.Source + " Query : " + query.Name, @@ -199,9 +191,7 @@ async ValueTask ResolveAsync(IResolveFieldContext context) var parameters = context.GetArgument("parameters"); - var queryParameters = parameters != null ? - JConvert.DeserializeObject>(parameters) - : []; + var queryParameters = parameters != null ? JConvert.DeserializeObject>(parameters) : []; var result = await queryManager.ExecuteQueryAsync(iquery, queryParameters); return result.Items; diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Permissions.cs index ab11836c034..029b4e421bc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/Permissions.cs @@ -8,25 +8,10 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageSqlQueries = new("ManageSqlQueries", "Manage SQL Queries"); - private readonly IEnumerable _allPermissions = - [ - ManageSqlQueries, - ]; + private readonly IEnumerable _allPermissions = [ManageSqlQueries,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _allPermissions, - }, - ]; + [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, }, new PermissionStereotype { Name = "Editor", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlGrammar.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlGrammar.cs index eb48ec77bae..8bf046cf06b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlGrammar.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlGrammar.cs @@ -4,7 +4,8 @@ namespace OrchardCore.Queries.Sql { public class SqlGrammar : Grammar { - public SqlGrammar() : base(false) + public SqlGrammar() + : base(false) { var comment = new CommentTerminal("comment", "/*", "*/"); var lineComment = new CommentTerminal("line_comment", "--", "\n", "\r\n"); @@ -150,8 +151,17 @@ public SqlGrammar() : base(false) orderDirOptional.Rule = Empty | "ASC" | "DESC"; // Select stmt. - selectStatement.Rule = SELECT + optionalSelectRestriction + selectorList + fromClauseOpt + whereClauseOptional + - groupClauseOpt + havingClauseOpt + orderClauseOpt + limitClauseOpt + offsetClauseOpt; + selectStatement.Rule = + SELECT + + optionalSelectRestriction + + selectorList + + fromClauseOpt + + whereClauseOptional + + groupClauseOpt + + havingClauseOpt + + orderClauseOpt + + limitClauseOpt + + offsetClauseOpt; optionalSelectRestriction.Rule = Empty | "ALL" | "DISTINCT"; selectorList.Rule = columnItemList | "*"; columnItemList.Rule = MakePlusRule(columnItemList, comma, columnItem); @@ -189,10 +199,28 @@ public SqlGrammar() : base(false) unExpr.Rule = unOp + term; unOp.Rule = NOT | "+" | "-" | "~"; binExpr.Rule = expression + binOp + expression; - binOp.Rule = ToTerm("+") | "-" | "*" | "/" | "%" // Arithmetic. - | "&" | "|" | "^" // Bit. - | "=" | ">" | "<" | ">=" | "<=" | "<>" | "!=" | "!<" | "!>" - | "AND" | "OR" | "LIKE" | "NOT LIKE"; + binOp.Rule = + ToTerm("+") + | "-" + | "*" + | "/" + | "%" // Arithmetic. + | "&" + | "|" + | "^" // Bit. + | "=" + | ">" + | "<" + | ">=" + | "<=" + | "<>" + | "!=" + | "!<" + | "!>" + | "AND" + | "OR" + | "LIKE" + | "NOT LIKE"; betweenExpr.Rule = expression + notOpt + "BETWEEN" + expression + "AND" + expression; inExpr.Rule = expression + notOpt + "IN" + "(" + functionArguments + ")"; notOpt.Rule = Empty | NOT; diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlParser.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlParser.cs index 0445e0eee45..5ec8a9c7827 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlParser.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlParser.cs @@ -30,12 +30,7 @@ public class SqlParser private string _groupBy; private string _orderBy; - private SqlParser( - ParseTree tree, - string schema, - ISqlDialect dialect, - string tablePrefix, - IDictionary parameters) + private SqlParser(ParseTree tree, string schema, ISqlDialect dialect, string tablePrefix, IDictionary parameters) { _tree = tree; _schema = schema; @@ -46,7 +41,15 @@ private SqlParser( _modes = new Stack(); } - public static bool TryParse(string sql, string schema, ISqlDialect dialect, string tablePrefix, IDictionary parameters, out string query, out IEnumerable messages) + public static bool TryParse( + string sql, + string schema, + ISqlDialect dialect, + string tablePrefix, + IDictionary parameters, + out string query, + out IEnumerable messages + ) { try { @@ -56,10 +59,7 @@ public static bool TryParse(string sql, string schema, ISqlDialect dialect, stri { query = null; - messages = tree - .ParserMessages - .Select(x => $"{x.Message} at line:{x.Location.Line}, col:{x.Location.Column}") - .ToArray(); + messages = tree.ParserMessages.Select(x => $"{x.Message} at line:{x.Location.Line}, col:{x.Location.Column}").ToArray(); return false; } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlParserException.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlParserException.cs index e7daf5013fd..1c16bd14cc0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlParserException.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlParserException.cs @@ -4,8 +4,7 @@ namespace OrchardCore.Queries.Sql { public class SqlParserException : Exception { - public SqlParserException(string message) : base(message) - { - } + public SqlParserException(string message) + : base(message) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlQuery.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlQuery.cs index 533aa81a07d..5a55e2eb102 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlQuery.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlQuery.cs @@ -4,12 +4,12 @@ namespace OrchardCore.Queries.Sql { public class SqlQuery : Query { - public SqlQuery() : base("Sql") - { - } + public SqlQuery() + : base("Sql") { } public string Template { get; set; } public bool ReturnDocuments { get; set; } + public override bool ResultsOfType() => ReturnDocuments ? typeof(T) == typeof(ContentItem) : base.ResultsOfType(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlQuerySource.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlQuerySource.cs index 555b43c186c..619f2d4ba51 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlQuerySource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlQuerySource.cs @@ -21,11 +21,7 @@ public class SqlQuerySource : IQuerySource private readonly ISession _session; private readonly TemplateOptions _templateOptions; - public SqlQuerySource( - ILiquidTemplateManager liquidTemplateManager, - IDbConnectionAccessor dbConnectionAccessor, - ISession session, - IOptions templateOptions) + public SqlQuerySource(ILiquidTemplateManager liquidTemplateManager, IDbConnectionAccessor dbConnectionAccessor, ISession session, IOptions templateOptions) { _liquidTemplateManager = liquidTemplateManager; _dbConnectionAccessor = dbConnectionAccessor; @@ -45,12 +41,25 @@ public async Task ExecuteQueryAsync(Query query, IDictionary new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions)))); + var tokenizedQuery = await _liquidTemplateManager.RenderStringAsync( + sqlQuery.Template, + NullEncoder.Default, + parameters.Select(x => new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions))) + ); var dialect = _session.Store.Configuration.SqlDialect; - if (!SqlParser.TryParse(tokenizedQuery, _session.Store.Configuration.Schema, dialect, _session.Store.Configuration.TablePrefix, parameters, out var rawQuery, out var messages)) + if ( + !SqlParser.TryParse( + tokenizedQuery, + _session.Store.Configuration.Schema, + dialect, + _session.Store.Configuration.TablePrefix, + parameters, + out var rawQuery, + out var messages + ) + ) { sqlQueryResults.Items = Array.Empty(); diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Startup.cs index 7a40452c722..ff00a997075 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Startup.cs @@ -32,18 +32,21 @@ public override void ConfigureServices(IServiceCollection services) services.AddDeployment(); services.AddSingleton(); - services.Configure(o => - { - o.Scope.SetValue("Queries", new ObjectValue(new LiquidQueriesAccessor())); - o.MemberAccessStrategy.Register(async (obj, name, context) => + services + .Configure(o => { - var liquidTemplateContext = (LiquidTemplateContext)context; - var queryManager = liquidTemplateContext.Services.GetRequiredService(); + o.Scope.SetValue("Queries", new ObjectValue(new LiquidQueriesAccessor())); + o.MemberAccessStrategy.Register( + async (obj, name, context) => + { + var liquidTemplateContext = (LiquidTemplateContext)context; + var queryManager = liquidTemplateContext.Services.GetRequiredService(); - return FluidValue.Create(await queryManager.GetQueryAsync(name), context.Options); - }); - }) - .AddLiquidFilter("query"); + return FluidValue.Create(await queryManager.GetQueryAsync(name), context.Options); + } + ); + }) + .AddLiquidFilter("query"); } } diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/AdminMenu.cs index 10c8a6e3239..d1a68c55ade 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/AdminMenu.cs @@ -8,11 +8,7 @@ namespace OrchardCore.ReCaptcha { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", ReCaptchaSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", ReCaptchaSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -28,16 +24,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Settings"], settings => settings - .Add(S["reCaptcha"], S["reCaptcha"].PrefixPosition(), reCaptcha => reCaptcha - .Permission(Permissions.ManageReCaptchaSettings) - .Action("Index", "Admin", _routeValues) - .LocalNav() - ) + builder.Add( + S["Security"], + security => + security.Add( + S["Settings"], + settings => + settings.Add( + S["reCaptcha"], + S["reCaptcha"].PrefixPosition(), + reCaptcha => reCaptcha.Permission(Permissions.ManageReCaptchaSettings).Action("Index", "Admin", _routeValues).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Drivers/ReCaptchaSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Drivers/ReCaptchaSettingsDisplayDriver.cs index 25fb57581d4..617f7a7d935 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Drivers/ReCaptchaSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Drivers/ReCaptchaSettingsDisplayDriver.cs @@ -24,7 +24,8 @@ public ReCaptchaSettingsDisplayDriver( IShellHost shellHost, ShellSettings shellSettings, IHttpContextAccessor httpContextAccessor, - IAuthorizationService authorizationService) + IAuthorizationService authorizationService + ) { _shellHost = shellHost; _shellSettings = shellSettings; @@ -41,11 +42,14 @@ public override async Task EditAsync(ReCaptchaSettings settings, return null; } - return Initialize("ReCaptchaSettings_Edit", model => - { - model.SiteKey = settings.SiteKey; - model.SecretKey = settings.SecretKey; - }) + return Initialize( + "ReCaptchaSettings_Edit", + model => + { + model.SiteKey = settings.SiteKey; + model.SecretKey = settings.SecretKey; + } + ) .Location("Content") .OnGroup(GroupId); } diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/Migrations.cs index c96f6bc10ef..10b5f586085 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/Migrations.cs @@ -16,12 +16,9 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("ReCaptchaPart", part => part - .WithDescription("Provides captcha properties.")); + await _contentDefinitionManager.AlterPartDefinitionAsync("ReCaptchaPart", part => part.WithDescription("Provides captcha properties.")); - await _contentDefinitionManager.AlterTypeDefinitionAsync("ReCaptcha", type => type - .WithPart("ReCaptchaPart") - .Stereotype("Widget")); + await _contentDefinitionManager.AlterTypeDefinitionAsync("ReCaptcha", type => type.WithPart("ReCaptchaPart").Stereotype("Widget")); return 1; } diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/ReCaptchaPart.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/ReCaptchaPart.cs index cd4fd2847f9..d56e94d288e 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/ReCaptchaPart.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/ReCaptchaPart.cs @@ -2,7 +2,5 @@ namespace OrchardCore.ReCaptcha.Forms { - public class ReCaptchaPart : ContentPart - { - } + public class ReCaptchaPart : ContentPart { } } diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/ReCaptchaPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/ReCaptchaPartDisplayDriver.cs index a09409f0247..9672d302757 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/ReCaptchaPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/ReCaptchaPartDisplayDriver.cs @@ -17,22 +17,29 @@ public ReCaptchaPartDisplayDriver(ISiteService siteService) public override IDisplayResult Display(ReCaptchaPart part, BuildPartDisplayContext context) { - return Initialize("ReCaptchaPart", async model => - { - var siteSettings = await _siteService.GetSiteSettingsAsync(); - var settings = siteSettings.As(); - model.SettingsAreConfigured = settings.IsValid(); - }).Location("Detail", "Content"); + return Initialize( + "ReCaptchaPart", + async model => + { + var siteSettings = await _siteService.GetSiteSettingsAsync(); + var settings = siteSettings.As(); + model.SettingsAreConfigured = settings.IsValid(); + } + ) + .Location("Detail", "Content"); } public override IDisplayResult Edit(ReCaptchaPart part, BuildPartEditorContext context) { - return Initialize("ReCaptchaPart_Fields_Edit", async model => - { - var siteSettings = await _siteService.GetSiteSettingsAsync(); - var settings = siteSettings.As(); - model.SettingsAreConfigured = settings.IsValid(); - }); + return Initialize( + "ReCaptchaPart_Fields_Edit", + async model => + { + var siteSettings = await _siteService.GetSiteSettingsAsync(); + var settings = siteSettings.As(); + model.SettingsAreConfigured = settings.IsValid(); + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/Startup.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/Startup.cs index 801d73fff82..22ce6b94022 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Forms/Startup.cs @@ -17,8 +17,7 @@ public override void ConfigureServices(IServiceCollection services) o.MemberAccessStrategy.Register(); }); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddDataMigration(); } diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Manifest.cs index 4d091b73954..40850a695a7 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Manifest.cs @@ -1,20 +1,13 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "ReCaptcha", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion)] +[assembly: Module(Name = "ReCaptcha", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] -[assembly: Feature( - Id = "OrchardCore.ReCaptcha", - Name = "ReCaptcha", - Category = "Security", - Description = "Provides core ReCaptcha functionality.")] +[assembly: Feature(Id = "OrchardCore.ReCaptcha", Name = "ReCaptcha", Category = "Security", Description = "Provides core ReCaptcha functionality.")] [assembly: Feature( Id = "OrchardCore.ReCaptcha.Users", Name = "ReCaptcha Users", Description = "Provides ReCaptcha functionality to harness login, register, forgot password and forms against robots.", Category = "Security", - Dependencies = ["OrchardCore.ReCaptcha", "OrchardCore.Users"])] + Dependencies = ["OrchardCore.ReCaptcha", "OrchardCore.Users"] +)] diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Permissions.cs index 65b987b4f52..2a3133e7232 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageReCaptchaSettings = new("ManageReCaptchaSettings", "Manage ReCaptcha Settings"); - private readonly IEnumerable _allPermissions = - [ - ManageReCaptchaSettings, - ]; + private readonly IEnumerable _allPermissions = [ManageReCaptchaSettings,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/ReCaptchaLoginFilter.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/ReCaptchaLoginFilter.cs index e2908768b92..499d546927c 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/ReCaptchaLoginFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/ReCaptchaLoginFilter.cs @@ -18,11 +18,7 @@ public class ReCaptchaLoginFilter : IAsyncResultFilter private ReCaptchaSettings _reCaptchaSettings; - public ReCaptchaLoginFilter( - ILayoutAccessor layoutAccessor, - ISiteService siteService, - ReCaptchaService reCaptchaService, - IShapeFactory shapeFactory) + public ReCaptchaLoginFilter(ILayoutAccessor layoutAccessor, ISiteService siteService, ReCaptchaService reCaptchaService, IShapeFactory shapeFactory) { _layoutAccessor = layoutAccessor; _siteService = siteService; @@ -32,8 +28,7 @@ public ReCaptchaLoginFilter( public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { - if (!context.IsViewOrPageResult() - || !string.Equals("OrchardCore.Users", Convert.ToString(context.RouteData.Values["area"]), StringComparison.OrdinalIgnoreCase)) + if (!context.IsViewOrPageResult() || !string.Equals("OrchardCore.Users", Convert.ToString(context.RouteData.Values["area"]), StringComparison.OrdinalIgnoreCase)) { await next(); return; diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Startup.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Startup.cs index 0e55ae780bd..8c2b6ba1310 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Startup.cs @@ -45,10 +45,12 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); - services.Configure((options) => - { - options.Filters.Add(); - }); + services.Configure( + (options) => + { + options.Filters.Add(); + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Workflows/ValidateReCaptchaTask.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Workflows/ValidateReCaptchaTask.cs index 5d5167c1e63..1a4bce7c8a0 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Workflows/ValidateReCaptchaTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Workflows/ValidateReCaptchaTask.cs @@ -15,11 +15,7 @@ public class ValidateReCaptchaTask : TaskActivity private readonly IUpdateModelAccessor _updateModelAccessor; protected readonly IStringLocalizer S; - public ValidateReCaptchaTask( - ReCaptchaService reCaptchaService, - IUpdateModelAccessor updateModelAccessor, - IStringLocalizer localizer - ) + public ValidateReCaptchaTask(ReCaptchaService reCaptchaService, IUpdateModelAccessor updateModelAccessor, IStringLocalizer localizer) { _reCaptchaService = reCaptchaService; _updateModelAccessor = updateModelAccessor; @@ -41,13 +37,15 @@ public override async Task ExecuteAsync(WorkflowExecuti { var outcome = "Valid"; - await _reCaptchaService.ValidateCaptchaAsync((key, error) => - { - var updater = _updateModelAccessor.ModelUpdater; - outcome = "Invalid"; + await _reCaptchaService.ValidateCaptchaAsync( + (key, error) => + { + var updater = _updateModelAccessor.ModelUpdater; + outcome = "Invalid"; - updater?.ModelState.TryAddModelError(Constants.ReCaptchaServerResponseHeaderName, S["Captcha validation failed. Try again."]); - }); + updater?.ModelState.TryAddModelError(Constants.ReCaptchaServerResponseHeaderName, S["Captcha validation failed. Try again."]); + } + ); return Outcomes("Done", outcome); } diff --git a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Workflows/ValidateReCaptchaTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Workflows/ValidateReCaptchaTaskDisplayDriver.cs index 78bf5755479..57968fa7a8d 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Workflows/ValidateReCaptchaTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReCaptcha/Workflows/ValidateReCaptchaTaskDisplayDriver.cs @@ -2,7 +2,5 @@ namespace OrchardCore.ReCaptcha.Workflows { - public class ValidateReCaptchaTaskDisplayDriver : ActivityDisplayDriver - { - } + public class ValidateReCaptchaTaskDisplayDriver : ActivityDisplayDriver { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Recipes/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Recipes/AdminMenu.cs index 5fa3e8f23a4..2d2abb1c8bd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Recipes/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Recipes/AdminMenu.cs @@ -21,15 +21,15 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Recipes"], S["Recipes"].PrefixPosition(), recipes => recipes - .AddClass("recipes").Id("recipes") - .Permission(StandardPermissions.SiteOwner) - .Action("Index", "Admin", "OrchardCore.Recipes") - .LocalNav() + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Recipes"], + S["Recipes"].PrefixPosition(), + recipes => recipes.AddClass("recipes").Id("recipes").Permission(StandardPermissions.SiteOwner).Action("Index", "Admin", "OrchardCore.Recipes").LocalNav() ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Recipes/Commands/RecipesCommands.cs b/src/OrchardCore.Modules/OrchardCore.Recipes/Commands/RecipesCommands.cs index 11f8b2d4deb..12d2d10cabe 100644 --- a/src/OrchardCore.Modules/OrchardCore.Recipes/Commands/RecipesCommands.cs +++ b/src/OrchardCore.Modules/OrchardCore.Recipes/Commands/RecipesCommands.cs @@ -11,9 +11,8 @@ public class RecipesCommands : DefaultCommandHandler { private readonly IEnumerable _recipeHarvesters; - public RecipesCommands( - IEnumerable recipeHarvesters, - IStringLocalizer localizer) : base(localizer) + public RecipesCommands(IEnumerable recipeHarvesters, IStringLocalizer localizer) + : base(localizer) { _recipeHarvesters = recipeHarvesters; } diff --git a/src/OrchardCore.Modules/OrchardCore.Recipes/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Recipes/Controllers/AdminController.cs index 6f1513a2b52..ea8cab17575 100644 --- a/src/OrchardCore.Modules/OrchardCore.Recipes/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Recipes/Controllers/AdminController.cs @@ -43,7 +43,8 @@ public AdminController( IEnumerable environmentProviders, INotifier notifier, IHtmlLocalizer localizer, - ILogger logger) + ILogger logger + ) { _shellHost = shellHost; _shellSettings = shellSettings; @@ -68,17 +69,19 @@ public async Task Index() var features = await _shellFeaturesManager.GetAvailableFeaturesAsync(); var recipes = await GetRecipesAsync(features); - var model = recipes.Select(recipe => new RecipeViewModel - { - Name = recipe.Name, - DisplayName = recipe.DisplayName, - FileName = recipe.RecipeFileInfo.Name, - BasePath = recipe.BasePath, - Tags = recipe.Tags, - IsSetupRecipe = recipe.IsSetupRecipe, - Feature = features.FirstOrDefault(f => recipe.BasePath.Contains(f.Extension.SubPath))?.Name ?? "Application", - Description = recipe.Description - }).ToArray(); + var model = recipes + .Select(recipe => new RecipeViewModel + { + Name = recipe.Name, + DisplayName = recipe.DisplayName, + FileName = recipe.RecipeFileInfo.Name, + BasePath = recipe.BasePath, + Tags = recipe.Tags, + IsSetupRecipe = recipe.IsSetupRecipe, + Feature = features.FirstOrDefault(f => recipe.BasePath.Contains(f.Extension.SubPath))?.Name ?? "Application", + Description = recipe.Description + }) + .ToArray(); return View(model); } @@ -119,10 +122,13 @@ public async Task Execute(string basePath, string fileName) private async Task> GetRecipesAsync(IEnumerable features) { var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); - var recipes = recipeCollections.SelectMany(x => x) - .Where(r => !r.IsSetupRecipe && - (r.Tags == null || !r.Tags.Contains("hidden", StringComparer.InvariantCultureIgnoreCase)) && - features.Any(f => r.BasePath != null && f.Extension?.SubPath != null && r.BasePath.Contains(f.Extension.SubPath, StringComparison.OrdinalIgnoreCase))); + var recipes = recipeCollections + .SelectMany(x => x) + .Where(r => + !r.IsSetupRecipe + && (r.Tags == null || !r.Tags.Contains("hidden", StringComparer.InvariantCultureIgnoreCase)) + && features.Any(f => r.BasePath != null && f.Extension?.SubPath != null && r.BasePath.Contains(f.Extension.SubPath, StringComparison.OrdinalIgnoreCase)) + ); return recipes; } diff --git a/src/OrchardCore.Modules/OrchardCore.Recipes/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Recipes/Manifest.cs index 935e5d732df..591f3232650 100644 --- a/src/OrchardCore.Modules/OrchardCore.Recipes/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Recipes/Manifest.cs @@ -1,20 +1,12 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Recipes", Name = "Recipes", Description = "The Recipes module allows you to execute recipe steps from json files.", - Dependencies = - [ - "OrchardCore.Recipes.Core", - "OrchardCore.Scripting", - ], + Dependencies = ["OrchardCore.Recipes.Core", "OrchardCore.Scripting",], Category = "Infrastructure", IsAlwaysEnabled = true )] diff --git a/src/OrchardCore.Modules/OrchardCore.Recipes/RecipeSteps/CommandStep.cs b/src/OrchardCore.Modules/OrchardCore.Recipes/RecipeSteps/CommandStep.cs index 0a98156f2bc..74089efe805 100644 --- a/src/OrchardCore.Modules/OrchardCore.Recipes/RecipeSteps/CommandStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Recipes/RecipeSteps/CommandStep.cs @@ -20,10 +20,7 @@ public class CommandStep : IRecipeStepHandler private readonly ICommandParametersParser _commandParameterParser; private readonly ILogger _logger; - public CommandStep(ICommandManager commandManager, - ICommandParser commandParser, - ICommandParametersParser commandParameterParser, - ILogger logger) + public CommandStep(ICommandManager commandManager, ICommandParser commandParser, ICommandParametersParser commandParameterParser, ILogger logger) { _commandManager = commandManager; _commandParser = commandParser; diff --git a/src/OrchardCore.Modules/OrchardCore.Recipes/Services/RecipeDeploymentTargetHandler.cs b/src/OrchardCore.Modules/OrchardCore.Recipes/Services/RecipeDeploymentTargetHandler.cs index cdd31f5ffa4..a55bc5ae91d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Recipes/Services/RecipeDeploymentTargetHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Recipes/Services/RecipeDeploymentTargetHandler.cs @@ -20,11 +20,13 @@ public class RecipeDeploymentTargetHandler : IDeploymentTargetHandler private readonly IEnumerable _environmentProviders; private readonly ILogger _logger; - public RecipeDeploymentTargetHandler(IShellHost shellHost, + public RecipeDeploymentTargetHandler( + IShellHost shellHost, ShellSettings shellSettings, IRecipeExecutor recipeExecutor, IEnumerable environmentProviders, - ILogger logger) + ILogger logger + ) { _shellHost = shellHost; _shellSettings = shellSettings; diff --git a/src/OrchardCore.Modules/OrchardCore.Redis/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Redis/Manifest.cs index 64187e24de2..9889f5db92e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Redis/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Redis/Manifest.cs @@ -1,18 +1,8 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Redis", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Redis", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] -[assembly: Feature( - Id = "OrchardCore.Redis", - Name = "Redis", - Description = "Redis configuration support.", - Category = "Distributed" -)] +[assembly: Feature(Id = "OrchardCore.Redis", Name = "Redis", Description = "Redis configuration support.", Category = "Distributed")] [assembly: Feature( Id = "OrchardCore.Redis.Cache", diff --git a/src/OrchardCore.Modules/OrchardCore.Redis/Options/RedisKeyManagementOptionsSetup.cs b/src/OrchardCore.Modules/OrchardCore.Redis/Options/RedisKeyManagementOptionsSetup.cs index 593fe5ade14..c7a34fa79eb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Redis/Options/RedisKeyManagementOptionsSetup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Redis/Options/RedisKeyManagementOptionsSetup.cs @@ -19,16 +19,18 @@ public RedisKeyManagementOptionsSetup(IRedisService redis, ShellSettings shellSe public void Configure(KeyManagementOptions options) { var redis = _redis; - options.XmlRepository = new RedisXmlRepository(() => - { - if (redis.Database == null) + options.XmlRepository = new RedisXmlRepository( + () => { - redis.ConnectAsync().GetAwaiter().GetResult(); - } + if (redis.Database == null) + { + redis.ConnectAsync().GetAwaiter().GetResult(); + } - return redis.Database; - }, - $"({redis.InstancePrefix}{_tenant}:DataProtection-Keys"); + return redis.Database; + }, + $"({redis.InstancePrefix}{_tenant}:DataProtection-Keys" + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisBus.cs b/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisBus.cs index 58a7bec351c..1a9a8b6bf20 100644 --- a/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisBus.cs +++ b/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisBus.cs @@ -42,17 +42,20 @@ public async Task SubscribeAsync(string channel, Action handler) { var subscriber = _redis.Connection.GetSubscriber(); - await subscriber.SubscribeAsync(RedisChannel.Literal(_channelPrefix + channel), (redisChannel, redisValue) => - { - var tokens = redisValue.ToString().Split('/').ToArray(); - - if (tokens.Length != 2 || tokens[0].Length == 0 || tokens[0].Equals(_hostName, StringComparison.OrdinalIgnoreCase)) + await subscriber.SubscribeAsync( + RedisChannel.Literal(_channelPrefix + channel), + (redisChannel, redisValue) => { - return; - } + var tokens = redisValue.ToString().Split('/').ToArray(); - handler(channel, tokens[1]); - }); + if (tokens.Length != 2 || tokens[0].Length == 0 || tokens[0].Equals(_hostName, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + handler(channel, tokens[1]); + } + ); } catch (Exception e) { diff --git a/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisCacheWrapper.cs b/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisCacheWrapper.cs index 31327781423..cdf30a47650 100644 --- a/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisCacheWrapper.cs +++ b/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisCacheWrapper.cs @@ -30,6 +30,5 @@ public class RedisCacheWrapper : IDistributedCache public void Set(string key, byte[] value, DistributedCacheEntryOptions options) => _cache.Set(key, value, options); - public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default) - => _cache.SetAsync(key, value, options, token); + public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default) => _cache.SetAsync(key, value, options, token); } diff --git a/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisDatabaseFactory.cs b/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisDatabaseFactory.cs index 53b4b7f7be6..8f296fe031d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisDatabaseFactory.cs +++ b/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisDatabaseFactory.cs @@ -35,23 +35,32 @@ public RedisDatabaseFactory(IHostApplicationLifetime lifetime, ILogger CreateAsync(RedisOptions options) => - _factories.GetOrAdd(options.Configuration, new Lazy>(async () => - { - try - { - if (_logger.IsEnabled(LogLevel.Debug)) + _factories + .GetOrAdd( + options.Configuration, + new Lazy>(async () => { - _logger.LogDebug("Creating a new instance of '{name}'. A single instance per configuration should be created across tenants. Total instances prior creating is '{count}'.", nameof(ConnectionMultiplexer), _factories.Count); - } + try + { + if (_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug( + "Creating a new instance of '{name}'. A single instance per configuration should be created across tenants. Total instances prior creating is '{count}'.", + nameof(ConnectionMultiplexer), + _factories.Count + ); + } - return (await ConnectionMultiplexer.ConnectAsync(options.ConfigurationOptions)).GetDatabase(); - } - catch (Exception e) - { - _logger.LogError(e, "Unable to connect to Redis."); - throw; - } - })).Value; + return (await ConnectionMultiplexer.ConnectAsync(options.ConfigurationOptions)).GetDatabase(); + } + catch (Exception e) + { + _logger.LogError(e, "Unable to connect to Redis."); + throw; + } + }) + ) + .Value; public void Dispose() { diff --git a/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisLock.cs b/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisLock.cs index 41849aa82ba..3fbce3e7bd8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisLock.cs +++ b/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisLock.cs @@ -64,8 +64,11 @@ public async Task AcquireLockAsync(string key, TimeSpan? expiration = n { if (_logger.IsEnabled(LogLevel.Debug)) { - _logger.LogDebug("Timeout elapsed before acquiring the named lock '{LockName}' after the given timeout of '{Timeout}'.", - _prefix + key, timeout.ToString()); + _logger.LogDebug( + "Timeout elapsed before acquiring the named lock '{LockName}' after the given timeout of '{Timeout}'.", + _prefix + key, + timeout.ToString() + ); } } } @@ -188,9 +191,7 @@ public void Dispose() private static TimeSpan GetDelay(double retries) { - var delay = _baseDelay - * (1.0 + ((Math.Pow(1.8, retries - 1.0) - 1.0) - * (0.6 + new Random().NextDouble() * 0.4))); + var delay = _baseDelay * (1.0 + ((Math.Pow(1.8, retries - 1.0) - 1.0) * (0.6 + new Random().NextDouble() * 0.4))); return TimeSpan.FromMilliseconds(Math.Min(delay, _maxDelay)); diff --git a/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisTagCache.cs b/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisTagCache.cs index 95af43a1f5f..8a7854749b7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisTagCache.cs +++ b/src/OrchardCore.Modules/OrchardCore.Redis/Services/RedisTagCache.cs @@ -16,11 +16,7 @@ public class RedisTagCache : ITagCache private readonly IEnumerable _tagRemovedEventHandlers; private readonly ILogger _logger; - public RedisTagCache( - IRedisService redis, - ShellSettings shellSettings, - IEnumerable tagRemovedEventHandlers, - ILogger logger) + public RedisTagCache(IRedisService redis, ShellSettings shellSettings, IEnumerable tagRemovedEventHandlers, ILogger logger) { _redis = redis; _prefix = redis.InstancePrefix + shellSettings.Name + ":Tag:"; diff --git a/src/OrchardCore.Modules/OrchardCore.Redis/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Redis/Startup.cs index 26310280e78..c804cb9c3af 100644 --- a/src/OrchardCore.Modules/OrchardCore.Redis/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Redis/Startup.cs @@ -69,8 +69,8 @@ public override void ConfigureServices(IServiceCollection services) // Callback for accepting any certificate as long as it exists, while ignoring other SSL policy errors. // This allows the use of self-signed certificates on the Redis server. - private static bool IgnoreCertificateErrors(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) - => (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == 0; + private static bool IgnoreCertificateErrors(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => + (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == 0; } [Feature("OrchardCore.Redis.Cache")] diff --git a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/LinkTag.cs b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/LinkTag.cs index 0b833f180de..dc02d6ffe8c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/LinkTag.cs +++ b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/LinkTag.cs @@ -30,13 +30,27 @@ public static async ValueTask WriteToAsync(List argu { switch (argument.Name) { - case "src": src = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "rel": rel = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "condition": condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "title": title = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "type": type = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "append_version": appendVersion = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; - default: (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "src": + src = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "rel": + rel = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "condition": + condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "title": + title = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "type": + type = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "append_version": + appendVersion = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); + break; + default: + (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/MetaTag.cs b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/MetaTag.cs index 0b40655c353..108b2028a6b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/MetaTag.cs +++ b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/MetaTag.cs @@ -30,13 +30,27 @@ public static async ValueTask WriteToAsync(List argu { switch (argument.Name) { - case "name": name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "property": property = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "content": content = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "http_equiv": httpEquiv = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "charset": charset = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "separator": separator = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - default: (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "name": + name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "property": + property = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "content": + content = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "http_equiv": + httpEquiv = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "charset": + charset = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "separator": + separator = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + default: + (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ResourcesTag.cs b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ResourcesTag.cs index 72bacba9cb8..3cf60541090 100644 --- a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ResourcesTag.cs +++ b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ResourcesTag.cs @@ -25,7 +25,9 @@ public static async ValueTask WriteToAsync(List argu switch (argument.Name) { #pragma warning disable CA1806 // Do not ignore method results - case "type": Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), out type); break; + case "type": + Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), out type); + break; #pragma warning restore CA1806 // Do not ignore method results } } diff --git a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ScriptBlock.cs b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ScriptBlock.cs index 7ea8588f8da..099440f5dbc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ScriptBlock.cs +++ b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ScriptBlock.cs @@ -17,7 +17,13 @@ public class ScriptBlock { private static readonly char[] _separators = [',', ' ']; - public static async ValueTask WriteToAsync(List argumentsList, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync( + List argumentsList, + IReadOnlyList statements, + TextWriter writer, + TextEncoder encoder, + TemplateContext context + ) { var services = ((LiquidTemplateContext)context).Services; var resourceManager = services.GetRequiredService(); @@ -37,14 +43,30 @@ public static async ValueTask WriteToAsync(List argu { switch (argument.Name) { - case "name": name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "condition": condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "culture": culture = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "debug": debug = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; - case "depends_on": dependsOn = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "version": version = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "at": Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), ignoreCase: true, out at); break; - default: (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "name": + name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "condition": + condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "culture": + culture = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "debug": + debug = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); + break; + case "depends_on": + dependsOn = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "version": + version = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "at": + Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), ignoreCase: true, out at); + break; + default: + (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ScriptTag.cs b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ScriptTag.cs index 21cb0690e97..037664dea15 100644 --- a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ScriptTag.cs +++ b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/ScriptTag.cs @@ -40,20 +40,48 @@ public static async ValueTask WriteToAsync(List argu { switch (argument.Name) { - case "name": name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "src": src = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "append_version": appendVersion = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; - case "cdn_src": cdnSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "debug_src": debugSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "debug_cdn_src": debugCdnSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "use_cdn": useCdn = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; - case "condition": condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "culture": culture = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "debug": debug = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; - case "depends_on": dependsOn = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "version": version = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "at": Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), ignoreCase: true, out at); break; - default: (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "name": + name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "src": + src = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "append_version": + appendVersion = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); + break; + case "cdn_src": + cdnSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "debug_src": + debugSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "debug_cdn_src": + debugCdnSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "use_cdn": + useCdn = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); + break; + case "condition": + condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "culture": + culture = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "debug": + debug = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); + break; + case "depends_on": + dependsOn = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "version": + version = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "at": + Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), ignoreCase: true, out at); + break; + default: + (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; } } @@ -277,7 +305,6 @@ public static async ValueTask WriteToAsync(List argu { resourceManager.RenderLocalScript(setting, writer); } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/StyleBlock.cs b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/StyleBlock.cs index 69f91eb61a2..d14602e73b7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/StyleBlock.cs +++ b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/StyleBlock.cs @@ -17,7 +17,13 @@ public class StyleBlock { private static readonly char[] _separators = [',', ' ']; - public static async ValueTask WriteToAsync(List argumentsList, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync( + List argumentsList, + IReadOnlyList statements, + TextWriter writer, + TextEncoder encoder, + TemplateContext context + ) { var services = ((LiquidTemplateContext)context).Services; var resourceManager = services.GetRequiredService(); @@ -36,13 +42,27 @@ public static async ValueTask WriteToAsync(List argu { switch (argument.Name) { - case "name": name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "condition": condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "culture": culture = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "debug": debug = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; - case "depends_on": dependsOn = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "at": Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), ignoreCase: true, out at); break; - default: (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "name": + name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "condition": + condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "culture": + culture = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "debug": + debug = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); + break; + case "depends_on": + dependsOn = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "at": + Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), ignoreCase: true, out at); + break; + default: + (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/StyleTag.cs b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/StyleTag.cs index d83c8d57153..7975197bb98 100644 --- a/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/StyleTag.cs +++ b/src/OrchardCore.Modules/OrchardCore.Resources/Liquid/StyleTag.cs @@ -40,20 +40,48 @@ public static async ValueTask WriteToAsync(List argu { switch (argument.Name) { - case "name": name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "src": src = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "append_version": appendversion = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; - case "cdn_src": cdnSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "debug_src": debugSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "debug_cdn_src": debugCdnSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "use_cdn": useCdn = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; - case "condition": condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "culture": culture = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "debug": debug = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; - case "depends_on": dependsOn = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "version": version = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "at": Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), ignoreCase: true, out at); break; - default: (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "name": + name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "src": + src = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "append_version": + appendversion = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); + break; + case "cdn_src": + cdnSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "debug_src": + debugSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "debug_cdn_src": + debugCdnSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "use_cdn": + useCdn = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); + break; + case "condition": + condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "culture": + culture = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "debug": + debug = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); + break; + case "depends_on": + dependsOn = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "version": + version = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "at": + Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), ignoreCase: true, out at); + break; + default: + (customAttributes ??= [])[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Resources/ResourceManagementOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Resources/ResourceManagementOptionsConfiguration.cs index d29aa803543..e445734927c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Resources/ResourceManagementOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Resources/ResourceManagementOptionsConfiguration.cs @@ -11,17 +11,16 @@ public class ResourceManagementOptionsConfiguration : IConfigureOptions resourceOptions, - IHostEnvironment env, - IHttpContextAccessor httpContextAccessor) + public ResourceManagementOptionsConfiguration(IOptions resourceOptions, IHostEnvironment env, IHttpContextAccessor httpContextAccessor) { _resourceOptions = resourceOptions.Value; _env = env; @@ -36,56 +35,80 @@ ResourceManifest BuildManifest() .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.min.js", "~/OrchardCore.Resources/Scripts/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.7.1.min.js", "https://code.jquery.com/jquery-3.7.1.js") - .SetCdnIntegrity("sha384-1H217gwSVyLSIfaLxHbE7dRb3v4mYCKbpQvzx0cegeju1MVsGrX5xXxAvs/HgeFs", "sha384-wsqsSADZR1YRBEZ4/kKHNSmU+aX8ojbnKUMN4RyD3jDkxw5mHtoe2z/T/n4l56U/") + .SetCdnIntegrity( + "sha384-1H217gwSVyLSIfaLxHbE7dRb3v4mYCKbpQvzx0cegeju1MVsGrX5xXxAvs/HgeFs", + "sha384-wsqsSADZR1YRBEZ4/kKHNSmU+aX8ojbnKUMN4RyD3jDkxw5mHtoe2z/T/n4l56U/" + ) .SetVersion("3.7.1"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.slim.min.js", "~/OrchardCore.Resources/Scripts/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.7.1.slim.min.js", "https://code.jquery.com/jquery-3.7.1.slim.js") - .SetCdnIntegrity("sha384-5AkRS45j4ukf+JbWAfHL8P4onPA9p0KwwP7pUdjSQA3ss9edbJUJc/XcYAiheSSz", "sha384-5yyt26go0PtGiMk9qStZt+lySzAg8ZSY0i7q6l05kHEEChYiHvf0NsjlexoEdASI") + .SetCdnIntegrity( + "sha384-5AkRS45j4ukf+JbWAfHL8P4onPA9p0KwwP7pUdjSQA3ss9edbJUJc/XcYAiheSSz", + "sha384-5yyt26go0PtGiMk9qStZt+lySzAg8ZSY0i7q6l05kHEEChYiHvf0NsjlexoEdASI" + ) .SetVersion("3.7.1"); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.6.0/jquery.min.js", "~/OrchardCore.Resources/Scripts/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.6.0.min.js", "https://code.jquery.com/jquery-3.6.0.js") - .SetCdnIntegrity("sha384-vtXRMe3mGCbOeY7l30aIg8H9p3GdeSe4IFlP6G8JMa7o7lXvnz3GFKzPxzJdPfGK", "sha384-S58meLBGKxIiQmJ/pJ8ilvFUcGcqgla+mWH9EEKGm6i6rKxSTA2kpXJQJ8n7XK4w") + .SetCdnIntegrity( + "sha384-vtXRMe3mGCbOeY7l30aIg8H9p3GdeSe4IFlP6G8JMa7o7lXvnz3GFKzPxzJdPfGK", + "sha384-S58meLBGKxIiQmJ/pJ8ilvFUcGcqgla+mWH9EEKGm6i6rKxSTA2kpXJQJ8n7XK4w" + ) .SetVersion("3.6.0"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.6.0/jquery.slim.min.js", "~/OrchardCore.Resources/Scripts/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.6.0.slim.min.js", "https://code.jquery.com/jquery-3.6.0.slim.js") - .SetCdnIntegrity("sha384-Qg00WFl9r0Xr6rUqNLv1ffTSSKEFFCDCKVyHZ+sVt8KuvG99nWw5RNvbhuKgif9z", "sha384-fuUlMletgG/KCb0NwIZTW6aMv/YBbXe0Wt71nwLRreZZpesG/N/aURjEZCG6mtYn") + .SetCdnIntegrity( + "sha384-Qg00WFl9r0Xr6rUqNLv1ffTSSKEFFCDCKVyHZ+sVt8KuvG99nWw5RNvbhuKgif9z", + "sha384-fuUlMletgG/KCb0NwIZTW6aMv/YBbXe0Wt71nwLRreZZpesG/N/aURjEZCG6mtYn" + ) .SetVersion("3.6.0"); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.5.1.min.js", "https://code.jquery.com/jquery-3.5.1.js") - .SetCdnIntegrity("sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2", "sha384-/LjQZzcpTzaYn7qWqRIWYC5l8FWEZ2bIHIz0D73Uzba4pShEcdLdZyZkI4Kv676E") + .SetCdnIntegrity( + "sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2", + "sha384-/LjQZzcpTzaYn7qWqRIWYC5l8FWEZ2bIHIz0D73Uzba4pShEcdLdZyZkI4Kv676E" + ) .SetVersion("3.5.1"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.slim.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.5.1.slim.min.js", "https://code.jquery.com/jquery-3.5.1.slim.js") - .SetCdnIntegrity("sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj", "sha384-x6NENSfxadikq2gB4e6/qompriNc+y1J3eqWg3hAAMNBs4dFU303XMTcU3uExJgZ") + .SetCdnIntegrity( + "sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj", + "sha384-x6NENSfxadikq2gB4e6/qompriNc+y1J3eqWg3hAAMNBs4dFU303XMTcU3uExJgZ" + ) .SetVersion("3.5.1"); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.4.1.min.js", "https://code.jquery.com/jquery-3.4.1.js") - .SetCdnIntegrity("sha384-vk5WoKIaW/vJyUAd9n/wmopsmNhiy+L2Z+SBxGYnUkunIxVxAv/UtMOhba/xskxh", "sha384-mlceH9HlqLp7GMKHrj5Ara1+LvdTZVMx4S1U43/NxCvAkzIo8WJ0FE7duLel3wVo") + .SetCdnIntegrity( + "sha384-vk5WoKIaW/vJyUAd9n/wmopsmNhiy+L2Z+SBxGYnUkunIxVxAv/UtMOhba/xskxh", + "sha384-mlceH9HlqLp7GMKHrj5Ara1+LvdTZVMx4S1U43/NxCvAkzIo8WJ0FE7duLel3wVo" + ) .SetVersion("3.4.1"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.slim.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.4.1.slim.min.js", "https://code.jquery.com/jquery-3.4.1.slim.js") - .SetCdnIntegrity("sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n", "sha384-teRaFq/YbXOM/9FZ1qTavgUgTagWUPsk6xapwcjkrkBHoWvKdZZuAeV8hhaykl+G") + .SetCdnIntegrity( + "sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n", + "sha384-teRaFq/YbXOM/9FZ1qTavgUgTagWUPsk6xapwcjkrkBHoWvKdZZuAeV8hhaykl+G" + ) .SetVersion("3.4.1"); manifest @@ -93,7 +116,10 @@ ResourceManifest BuildManifest() .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.easing.min.js", "~/OrchardCore.Resources/Scripts/jquery.easing.js") .SetCdn("https://cdn.jsdelivr.net/npm/jquery.easing@1.4.1/jquery.easing.min.js", "https://cdn.jsdelivr.net/npm/jquery.easing@1.4.1/jquery.easing.js") - .SetCdnIntegrity("sha384-leGYpHE9Tc4N9OwRd98xg6YFpB9shlc/RkilpFi0ljr3QD4tFoFptZvgnnzzwG4Q", "sha384-fwPA0FyfPOiDsglgAC4ZWmBGwpXSZNkq9IG+cM9HL4CkpNQo4xgCDkOIPdWypLMX") + .SetCdnIntegrity( + "sha384-leGYpHE9Tc4N9OwRd98xg6YFpB9shlc/RkilpFi0ljr3QD4tFoFptZvgnnzzwG4Q", + "sha384-fwPA0FyfPOiDsglgAC4ZWmBGwpXSZNkq9IG+cM9HL4CkpNQo4xgCDkOIPdWypLMX" + ) .SetVersion("1.4.1"); manifest @@ -101,14 +127,20 @@ ResourceManifest BuildManifest() .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-ui.min.js", "~/OrchardCore.Resources/Scripts/jquery-ui.js") .SetCdn("https://code.jquery.com/ui/1.12.1/jquery-ui.min.js", "https://code.jquery.com/ui/1.12.1/jquery-ui.js") - .SetCdnIntegrity("sha384-Dziy8F2VlJQLMShA6FHWNul/veM9bCkRUaLqr199K94ntO5QUrLJBEbYegdSkkqX", "sha384-JPbtLYL10d/Z1crlc6GGGGM3PavCzzoUJ1UxH0bXHOfguWHQ6XAWrIzW+MBGGXe5") + .SetCdnIntegrity( + "sha384-Dziy8F2VlJQLMShA6FHWNul/veM9bCkRUaLqr199K94ntO5QUrLJBEbYegdSkkqX", + "sha384-JPbtLYL10d/Z1crlc6GGGGM3PavCzzoUJ1UxH0bXHOfguWHQ6XAWrIzW+MBGGXe5" + ) .SetVersion("1.12.1"); manifest .DefineStyle("jQuery-ui") .SetUrl("~/OrchardCore.Resources/Styles/jquery-ui.min.css", "~/OrchardCore.Resources/Styles/jquery-ui.css") .SetCdn("https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.min.css", "https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css") - .SetCdnIntegrity("sha384-kcAOn9fN4XSd+TGsNu2OQKSuV5ngOwt7tg73O4EpaD91QXvrfgvf0MR7/2dUjoI6", "sha384-xewr6kSkq3dBbEtB6Z/3oFZmknWn7nHqhLVLrYgzEFRbU/DHSxW7K3B44yWUN60D") + .SetCdnIntegrity( + "sha384-kcAOn9fN4XSd+TGsNu2OQKSuV5ngOwt7tg73O4EpaD91QXvrfgvf0MR7/2dUjoI6", + "sha384-xewr6kSkq3dBbEtB6Z/3oFZmknWn7nHqhLVLrYgzEFRbU/DHSxW7K3B44yWUN60D" + ) .SetVersion("1.12.1"); manifest @@ -116,33 +148,48 @@ ResourceManifest BuildManifest() .SetDependencies("jQuery-ui") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-ui-i18n.min.js", "~/OrchardCore.Resources/Scripts/jquery-ui-i18n.js") .SetCdn("https://code.jquery.com/ui/1.7.2/i18n/jquery-ui-i18n.min.js", "https://code.jquery.com/ui/1.7.2/i18n/jquery-ui-i18n.min.js") - .SetCdnIntegrity("sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd", "sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd") + .SetCdnIntegrity( + "sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd", + "sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd" + ) .SetVersion("1.7.2"); manifest .DefineScript("bootstrap") .SetDependencies("jQuery") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.js") - .SetCdnIntegrity("sha384-vhJnz1OVIdLktyixHY4Uk3OHEwdQqPppqYR8+5mjsauETgLOcEynD9oPHhhz18Nw", "sha384-it0Suwx+VjMafDIVf5t+ozEbrflmNjEddSX5LstI/Xdw3nv4qP/a4e8K4k5hH6l4") + .SetCdnIntegrity( + "sha384-vhJnz1OVIdLktyixHY4Uk3OHEwdQqPppqYR8+5mjsauETgLOcEynD9oPHhhz18Nw", + "sha384-it0Suwx+VjMafDIVf5t+ozEbrflmNjEddSX5LstI/Xdw3nv4qP/a4e8K4k5hH6l4" + ) .SetVersion("3.4.0"); manifest .DefineStyle("bootstrap") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.css") - .SetCdnIntegrity("sha384-PmY9l28YgO4JwMKbTvgaS7XNZJ30MK9FAZjjzXtlqyZCqBY6X6bXIkM++IkyinN+", "sha384-/5bQ8UYbZnrNY3Mfy6zo9QLgIQD/0CximLKk733r8/pQnXn2mgvhvKhcy43gZtJV") + .SetCdnIntegrity( + "sha384-PmY9l28YgO4JwMKbTvgaS7XNZJ30MK9FAZjjzXtlqyZCqBY6X6bXIkM++IkyinN+", + "sha384-/5bQ8UYbZnrNY3Mfy6zo9QLgIQD/0CximLKk733r8/pQnXn2mgvhvKhcy43gZtJV" + ) .SetVersion("3.4.0"); manifest .DefineStyle("bootstrap-theme") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.css") - .SetCdnIntegrity("sha384-jzngWsPS6op3fgRCDTESqrEJwRKck+CILhJVO5VvaAZCq8JYf8HsR/HPpBOOPZfR", "sha384-RtiWe5OsslAYZ9AVyorBziI2VQL7E27rzWygBJh7wrZuVPyK5jeQLLytnJIpJqfD") + .SetCdnIntegrity( + "sha384-jzngWsPS6op3fgRCDTESqrEJwRKck+CILhJVO5VvaAZCq8JYf8HsR/HPpBOOPZfR", + "sha384-RtiWe5OsslAYZ9AVyorBziI2VQL7E27rzWygBJh7wrZuVPyK5jeQLLytnJIpJqfD" + ) .SetVersion("3.4.0"); manifest .DefineScript("popper") .SetUrl("~/OrchardCore.Resources/Vendor/popper-1.16.1/popper.min.js", "~/OrchardCore.Resources/Vendor/popper-1.16.1/popper.js") .SetCdn("https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js", "https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.js") - .SetCdnIntegrity("sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN", "sha384-cpSm/ilDFOWiMuF2bj03ZzJinb48NO9IGCXcYDtUzdP5y64Ober65chnoOj1XFoA") + .SetCdnIntegrity( + "sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN", + "sha384-cpSm/ilDFOWiMuF2bj03ZzJinb48NO9IGCXcYDtUzdP5y64Ober65chnoOj1XFoA" + ) .SetVersion("1.16.1"); manifest @@ -150,7 +197,10 @@ ResourceManifest BuildManifest() .SetDependencies("jQuery", "popper") .SetUrl("~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.min.js", "~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.js") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.js") - .SetCdnIntegrity("sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2", "sha384-acUSOMj/FOTIzZ4qpiZXd/6avQezsTkra+wBPeduOyUIA5anC5YcLndJ3Wn4b4pF") + .SetCdnIntegrity( + "sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2", + "sha384-acUSOMj/FOTIzZ4qpiZXd/6avQezsTkra+wBPeduOyUIA5anC5YcLndJ3Wn4b4pF" + ) .SetVersion("4.6.1"); manifest @@ -158,29 +208,41 @@ ResourceManifest BuildManifest() .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.bundle.min.js", "~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.bundle.js") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.js") - .SetCdnIntegrity("sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF", "sha384-fAPB/5gOv3oOdZZ9/se34OICi8gkYHlNY5skCVFZPzGe+F2puEgM5hu8ctpXyKFM") + .SetCdnIntegrity( + "sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF", + "sha384-fAPB/5gOv3oOdZZ9/se34OICi8gkYHlNY5skCVFZPzGe+F2puEgM5hu8ctpXyKFM" + ) .SetVersion("4.6.1"); manifest .DefineStyle("bootstrap") .SetUrl("~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.min.css", "~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.css") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css", "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.css") - .SetCdnIntegrity("sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn", "sha384-ztSeENTvhymkwcI8wMyrHLHIyPJgek5ErHOMw9p96EzJKwbiuJBWBDuPJpGNqOar") + .SetCdnIntegrity( + "sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn", + "sha384-ztSeENTvhymkwcI8wMyrHLHIyPJgek5ErHOMw9p96EzJKwbiuJBWBDuPJpGNqOar" + ) .SetVersion("4.6.1"); manifest - .DefineScript("popperjs") - .SetUrl("~/OrchardCore.Resources/Scripts/popper.min.js", "~/OrchardCore.Resources/Scripts/popper.js") - .SetCdn("https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js", "https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.js") - .SetCdnIntegrity("sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r", "sha384-yBknSWNrSUPkBtbhhCJ07i/BOmbrigRhLKPzTAny+TT4uGAwIdfNTAkBd/3VzXbg") - .SetVersion("2.11.8"); + .DefineScript("popperjs") + .SetUrl("~/OrchardCore.Resources/Scripts/popper.min.js", "~/OrchardCore.Resources/Scripts/popper.js") + .SetCdn("https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js", "https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.js") + .SetCdnIntegrity( + "sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r", + "sha384-yBknSWNrSUPkBtbhhCJ07i/BOmbrigRhLKPzTAny+TT4uGAwIdfNTAkBd/3VzXbg" + ) + .SetVersion("2.11.8"); manifest .DefineScript("bootstrap") .SetDependencies("popperjs") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap.min.js", "~/OrchardCore.Resources/Scripts/bootstrap.js") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.js") - .SetCdnIntegrity("sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+", "sha384-0OXpCFnSQ8aVy03XgJ/CRB6pSELypcPWNcgqPnyguU/ADjPf/kx/dG4WfXjjU64D") + .SetCdnIntegrity( + "sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+", + "sha384-0OXpCFnSQ8aVy03XgJ/CRB6pSELypcPWNcgqPnyguU/ADjPf/kx/dG4WfXjjU64D" + ) .SetVersion("5.3.2"); manifest @@ -188,43 +250,67 @@ ResourceManifest BuildManifest() .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap.bundle.min.js", "~/OrchardCore.Resources/Scripts/bootstrap.bundle.js") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.js") - .SetCdnIntegrity("sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL", "sha384-6yr0NH5/NO/eJn8MXILS94sAfqCcf2wpWTTxRwskNor6dIjwbYjw1/PZpr654rQ5") + .SetCdnIntegrity( + "sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL", + "sha384-6yr0NH5/NO/eJn8MXILS94sAfqCcf2wpWTTxRwskNor6dIjwbYjw1/PZpr654rQ5" + ) .SetVersion("5.3.2"); manifest .DefineStyle("bootstrap") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap.min.css", "~/OrchardCore.Resources/Styles/bootstrap.css") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css", "https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.css") - .SetCdnIntegrity("sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN", "sha384-8dbpXuP2nso7zrhApj0aSxeb0ZitbTeO0hTKxRcXavYE0vv4nhBEqvv+o+0X94A8") + .SetCdnIntegrity( + "sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN", + "sha384-8dbpXuP2nso7zrhApj0aSxeb0ZitbTeO0hTKxRcXavYE0vv4nhBEqvv+o+0X94A8" + ) .SetVersion("5.3.2"); manifest .DefineStyle("bootstrap-rtl") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap.rtl.min.css", "~/OrchardCore.Resources/Styles/bootstrap.rtl.css") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.rtl.min.css", "https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.rtl.css") - .SetCdnIntegrity("sha384-nU14brUcp6StFntEOOEBvcJm4huWjB0OcIeQ3fltAfSmuZFrkAif0T+UtNGlKKQv", "sha384-CEku08bnqQAT/vzi6/zxMQmSyxoOTK1jx7mbT8P7etf/YhPbxASCX5BIVuAK9sfy") + .SetCdnIntegrity( + "sha384-nU14brUcp6StFntEOOEBvcJm4huWjB0OcIeQ3fltAfSmuZFrkAif0T+UtNGlKKQv", + "sha384-CEku08bnqQAT/vzi6/zxMQmSyxoOTK1jx7mbT8P7etf/YhPbxASCX5BIVuAK9sfy" + ) .SetVersion("5.3.2"); manifest .DefineStyle("bootstrap-select") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap-select.min.css", "~/OrchardCore.Resources/Styles/bootstrap-select.css") - .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/css/bootstrap-select.min.css", "https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/css/bootstrap-select.css") - .SetCdnIntegrity("sha384-xF1Y2i6HgC34+4EWddbDhlQuru7cLSKRcPT3hoL3mPoKoV+624vVSZJmegPX77vS", "sha384-DtuOZ7LbR+xAYzDGD4YLpe9eiAayUBwZRqAcoy+RepIoV53tAoJbXnr4AX1xTJ43") + .SetCdn( + "https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/css/bootstrap-select.min.css", + "https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/css/bootstrap-select.css" + ) + .SetCdnIntegrity( + "sha384-xF1Y2i6HgC34+4EWddbDhlQuru7cLSKRcPT3hoL3mPoKoV+624vVSZJmegPX77vS", + "sha384-DtuOZ7LbR+xAYzDGD4YLpe9eiAayUBwZRqAcoy+RepIoV53tAoJbXnr4AX1xTJ43" + ) .SetVersion("1.14.0"); manifest .DefineScript("bootstrap-select") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap-select.min.js", "~/OrchardCore.Resources/Scripts/bootstrap-select.js") - .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/js/bootstrap-select.min.js", "https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/js/bootstrap-select.js") - .SetCdnIntegrity("sha384-0O3sg2SQIGn4393xwamQISjphC8DIXjCzlhj1gPAMC5xGg+2perF5Mehr5njv0fZ", "sha384-2b0aLFg/Ejp4OF57nW0BUqNzm259RHYYMf/mpKClBijsEH2P+4ea2oWAq0twd8L0") + .SetCdn( + "https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/js/bootstrap-select.min.js", + "https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/js/bootstrap-select.js" + ) + .SetCdnIntegrity( + "sha384-0O3sg2SQIGn4393xwamQISjphC8DIXjCzlhj1gPAMC5xGg+2perF5Mehr5njv0fZ", + "sha384-2b0aLFg/Ejp4OF57nW0BUqNzm259RHYYMf/mpKClBijsEH2P+4ea2oWAq0twd8L0" + ) .SetVersion("1.14.0"); manifest .DefineStyle("nouislider") .SetUrl("~/OrchardCore.Resources/Styles/nouislider.min.css", "~/OrchardCore.Resources/Styles/nouislider.css") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/15.7.0/nouislider.min.css", "https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/15.7.0/nouislider.css") - .SetCdnIntegrity("sha384-PSZaVsyG9jDu8hFaSJev5s/9poIJlX7cuxSGdqCgXRHpo2DzIaZAyCd2rG/DJJmV", "sha384-SW0/EWtnMakMnwC9RHA27DeNtNCLsJ0l+oZrXlFbb2123lhLdZIbiDiwRPogNY8T") + .SetCdnIntegrity( + "sha384-PSZaVsyG9jDu8hFaSJev5s/9poIJlX7cuxSGdqCgXRHpo2DzIaZAyCd2rG/DJJmV", + "sha384-SW0/EWtnMakMnwC9RHA27DeNtNCLsJ0l+oZrXlFbb2123lhLdZIbiDiwRPogNY8T" + ) .SetVersion("15.7.0"); manifest @@ -232,63 +318,90 @@ ResourceManifest BuildManifest() .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/nouislider/nouislider.min.js", "~/OrchardCore.Resources/Scripts/nouislider/nouislider.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/15.7.0/nouislider.min.js", "https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/15.7.0/nouislider.js") - .SetCdnIntegrity("sha384-/gBUOLHADjY2rp6bHB0IyW9AC28q4OsnirJScje4l1crgYW7Qarx3dH8zcqcUgmy", "sha384-ZRTsSqAkR2D5UR6P8ew9nDImNmAueqBx3QIljDVMucOjF3eVskkMIk50HUW239mY") + .SetCdnIntegrity( + "sha384-/gBUOLHADjY2rp6bHB0IyW9AC28q4OsnirJScje4l1crgYW7Qarx3dH8zcqcUgmy", + "sha384-ZRTsSqAkR2D5UR6P8ew9nDImNmAueqBx3QIljDVMucOjF3eVskkMIk50HUW239mY" + ) .SetVersion("15.7.0"); manifest .DefineStyle("codemirror") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/codemirror.min.css", "~/OrchardCore.Resources/Styles/codemirror/codemirror.css") .SetCdn(CodeMirrorUrl + "codemirror.min.css", CodeMirrorUrl + "codemirror.css") - .SetCdnIntegrity("sha384-zaeBlB/vwYsDRSlFajnDd7OydJ0cWk+c2OWybl3eSUf6hW2EbhlCsQPqKr3gkznT", "sha384-bsaAhvdduZPAwUb7RRLRvDgtEtOsggrgjkr/EjPO1i/vdoi+DmdLaG79UOt6M5hD") + .SetCdnIntegrity( + "sha384-zaeBlB/vwYsDRSlFajnDd7OydJ0cWk+c2OWybl3eSUf6hW2EbhlCsQPqKr3gkznT", + "sha384-bsaAhvdduZPAwUb7RRLRvDgtEtOsggrgjkr/EjPO1i/vdoi+DmdLaG79UOt6M5hD" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/codemirror.min.js", "~/OrchardCore.Resources/Scripts/codemirror/codemirror.js") .SetCdn(CodeMirrorUrl + "codemirror.min.js", CodeMirrorUrl + "codemirror.js") - .SetCdnIntegrity("sha384-FIV1f0SplvlwhOxrMYdXpUcnVM79A9u4ffl0lEOVVZunLMuGpxFyQmnBHl24EQFR", "sha384-VAGlhrJE9eY6OkSfl3ioNR4jWUGp1mLeF/ECkHxBUEfTB9u2xVVH14acAUBDc3Y8") + .SetCdnIntegrity( + "sha384-FIV1f0SplvlwhOxrMYdXpUcnVM79A9u4ffl0lEOVVZunLMuGpxFyQmnBHl24EQFR", + "sha384-VAGlhrJE9eY6OkSfl3ioNR4jWUGp1mLeF/ECkHxBUEfTB9u2xVVH14acAUBDc3Y8" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-addon-display-autorefresh") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/display/autorefresh.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/autorefresh.js") .SetCdn(CodeMirrorUrl + "addon/display/autorefresh.min.js", CodeMirrorUrl + "addon/display/autorefresh.js") - .SetCdnIntegrity("sha384-pn83o6MtS8kicn/sV6AhRaBqXQ5tau8NzA2ovcobkcc1uRFP7D8CMhRx231QwKST", "sha384-B1M1WS08oqd1y3zKAPdhkOSNwy+NYMREyK9qXNWl+QfXDlqj+Y+TYuBUkc/uAnox") + .SetCdnIntegrity( + "sha384-pn83o6MtS8kicn/sV6AhRaBqXQ5tau8NzA2ovcobkcc1uRFP7D8CMhRx231QwKST", + "sha384-B1M1WS08oqd1y3zKAPdhkOSNwy+NYMREyK9qXNWl+QfXDlqj+Y+TYuBUkc/uAnox" + ) .SetVersion(CodeMirrorVersion); manifest .DefineStyle("codemirror-addon-display-fullscreen") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/addon/display/fullscreen.min.css", "~/OrchardCore.Resources/Styles/codemirror/addon/display/fullscreen.css") .SetCdn(CodeMirrorUrl + "addon/display/fullscreen.min.css", CodeMirrorUrl + "addon/display/fullscreen.css") - .SetCdnIntegrity("sha384-uuIczW2AGKADJpvg6YiNBJQWE7duDkgQDkndYEsbUGaLm8SPJZzlly6hcEo0aTlW", "sha384-+glu1jsbG+T5ocmkeMvIYh5w07IXKxmJZaCdkNbVfpEr3xi+M0gopFSR/oLKXxio") + .SetCdnIntegrity( + "sha384-uuIczW2AGKADJpvg6YiNBJQWE7duDkgQDkndYEsbUGaLm8SPJZzlly6hcEo0aTlW", + "sha384-+glu1jsbG+T5ocmkeMvIYh5w07IXKxmJZaCdkNbVfpEr3xi+M0gopFSR/oLKXxio" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-addon-display-fullscreen") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.js") .SetCdn(CodeMirrorUrl + "addon/display/fullscreen.min.js", CodeMirrorUrl + "addon/display/fullscreen.js") - .SetCdnIntegrity("sha384-mlEZFcWl5HzvZ6rIROEnNm825OC0Gw5KMZkilPtaJL7BGiluUu4c8Ws3IaNauZTh", "sha384-vU/yRPnV0VIhELETYT5fG/k7uMzeHddzkMo4NFrLzHdJepeb46v0b61P8FADXtN4") + .SetCdnIntegrity( + "sha384-mlEZFcWl5HzvZ6rIROEnNm825OC0Gw5KMZkilPtaJL7BGiluUu4c8Ws3IaNauZTh", + "sha384-vU/yRPnV0VIhELETYT5fG/k7uMzeHddzkMo4NFrLzHdJepeb46v0b61P8FADXtN4" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-addon-edit-closetag") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/edit/closetag.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/edit/closetag.js") .SetCdn(CodeMirrorUrl + "addon/edit/closetag.min.js", CodeMirrorUrl + "addon/edit/closetag.js") - .SetCdnIntegrity("sha384-WIyvbwMte2q6VXgBkN7prVo9ZSmBm47nI2ftVjoJLPY4yOu9gmI6lqaNXjBwHU5k", "sha384-i4ai3UXE5wIk3ILN77PB9DhNmku+sefNKDTHXRvsrYX2bxWzm+EDmoBui5wsNU2v") + .SetCdnIntegrity( + "sha384-WIyvbwMte2q6VXgBkN7prVo9ZSmBm47nI2ftVjoJLPY4yOu9gmI6lqaNXjBwHU5k", + "sha384-i4ai3UXE5wIk3ILN77PB9DhNmku+sefNKDTHXRvsrYX2bxWzm+EDmoBui5wsNU2v" + ) .SetVersion(CodeMirrorVersion); manifest .DefineStyle("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/addon/hint/show-hint.min.css", "~/OrchardCore.Resources/Styles/codemirror/addon/hint/show-hint.css") .SetCdn(CodeMirrorUrl + "addon/hint/show-hint.min.css", CodeMirrorUrl + "addon/hint/show-hint.css") - .SetCdnIntegrity("sha384-qqTWkykzuDLx4yDYa7bVrwNwBHuqVvklDUMVaU4eezgNUEgGbP8Zv6i3u8OmtuWg", "sha384-ZZbLvEvLoXKrHo3Tkh7W8amMgoHFkDzWe8IAm1ZgxsG5y35H+fJCVMWwr0YBAEGA") + .SetCdnIntegrity( + "sha384-qqTWkykzuDLx4yDYa7bVrwNwBHuqVvklDUMVaU4eezgNUEgGbP8Zv6i3u8OmtuWg", + "sha384-ZZbLvEvLoXKrHo3Tkh7W8amMgoHFkDzWe8IAm1ZgxsG5y35H+fJCVMWwr0YBAEGA" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/hint/show-hint.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/hint/show-hint.js") .SetCdn(CodeMirrorUrl + "addon/hint/show-hint.min.js", CodeMirrorUrl + "addon/hint/show-hint.js") - .SetCdnIntegrity("sha384-8i/ZCyq/QakicQDFEJhSl5oJEzzChdhEHhFBvtlxJMWdzohX6j+7O7L7NGgVjaL2", "sha384-X99dMoDW1QAOqOa49NoR3mVQPZMAmWdk1EtGVfWHdqFrD0mKdc4TVCugISfW0wEv") + .SetCdnIntegrity( + "sha384-8i/ZCyq/QakicQDFEJhSl5oJEzzChdhEHhFBvtlxJMWdzohX6j+7O7L7NGgVjaL2", + "sha384-X99dMoDW1QAOqOa49NoR3mVQPZMAmWdk1EtGVfWHdqFrD0mKdc4TVCugISfW0wEv" + ) .SetVersion(CodeMirrorVersion); manifest @@ -296,110 +409,179 @@ ResourceManifest BuildManifest() .SetDependencies("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/hint/sql-hint.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/hint/sql-hint.js") .SetCdn(CodeMirrorUrl + "addon/hint/sql-hint.min.js", CodeMirrorUrl + "addon/hint/sql-hint.js") - .SetCdnIntegrity("sha384-TT6FzU/qfXKsyGpknyPBSW9YUv9boLL9TStdfYRJTMjLDdUaQwWceBVs8I326z16", "sha384-v0PZIWVaXK+SdJWDH/8f3lMh+4SXRujsh67aPj27BlUq4ocyn0Yime8qyi8AArtz") + .SetCdnIntegrity( + "sha384-TT6FzU/qfXKsyGpknyPBSW9YUv9boLL9TStdfYRJTMjLDdUaQwWceBVs8I326z16", + "sha384-v0PZIWVaXK+SdJWDH/8f3lMh+4SXRujsh67aPj27BlUq4ocyn0Yime8qyi8AArtz" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-addon-mode-multiplex") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/mode/multiplex.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/mode/multiplex.js") .SetCdn(CodeMirrorUrl + "addon/mode/multiplex.min.js", CodeMirrorUrl + "addon/mode/multiplex.js") - .SetCdnIntegrity("sha384-Qr/1hjoJmzEf6ToQLo1nr8/GF5ekpaqUx0DM71QHZ4N8+c8l8aqlQ25whgApmChE", "sha384-pgj6NfGJNeIBDFqYM8m/ah3J269WhaJDiT0fN/C0c335qDMJAbfz/O2rVB53w+1D") + .SetCdnIntegrity( + "sha384-Qr/1hjoJmzEf6ToQLo1nr8/GF5ekpaqUx0DM71QHZ4N8+c8l8aqlQ25whgApmChE", + "sha384-pgj6NfGJNeIBDFqYM8m/ah3J269WhaJDiT0fN/C0c335qDMJAbfz/O2rVB53w+1D" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-addon-mode-simple") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/mode/simple.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/mode/simple.js") .SetCdn(CodeMirrorUrl + "addon/mode/simple.min.js", CodeMirrorUrl + "addon/mode/simple.js") - .SetCdnIntegrity("sha384-5+aYjV0V2W3IwhAYp/9WOrGMv1TaYkCjnkkW7Hv3yJQo28MergRCSRaUIUzDUs2J", "sha384-qeu+SDWpTAqXUyXdqdwbMDeYSQiv6rErEHLJ/cITY3wtuYhN2LdBSBZeS7Jyn8nv") + .SetCdnIntegrity( + "sha384-5+aYjV0V2W3IwhAYp/9WOrGMv1TaYkCjnkkW7Hv3yJQo28MergRCSRaUIUzDUs2J", + "sha384-qeu+SDWpTAqXUyXdqdwbMDeYSQiv6rErEHLJ/cITY3wtuYhN2LdBSBZeS7Jyn8nv" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-addon-selection-active-line") - .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/selection/active-line.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/selection/active-line.js") + .SetUrl( + "~/OrchardCore.Resources/Scripts/codemirror/addon/selection/active-line.min.js", + "~/OrchardCore.Resources/Scripts/codemirror/addon/selection/active-line.js" + ) .SetCdn(CodeMirrorUrl + "addon/selection/active-line.min.js", CodeMirrorUrl + "addon/selection/active-line.js") - .SetCdnIntegrity("sha384-hcxaXyAtJ30s2NeDu1OHWsQRiHiWuYLTbI596+YFb+f2pFhzO0mDuahZziRPPDxg", "sha384-QhD10EHRrst6CIOzeEBXQhUT95YVJN1EV8uX2Jb5S3+qw/ozbvUE5Zn5uILnZg96") + .SetCdnIntegrity( + "sha384-hcxaXyAtJ30s2NeDu1OHWsQRiHiWuYLTbI596+YFb+f2pFhzO0mDuahZziRPPDxg", + "sha384-QhD10EHRrst6CIOzeEBXQhUT95YVJN1EV8uX2Jb5S3+qw/ozbvUE5Zn5uILnZg96" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-mode-css") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/css/css.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/css/css.js") .SetCdn(CodeMirrorUrl + "mode/css/css.min.js", CodeMirrorUrl + "mode/css/css.js") - .SetCdnIntegrity("sha384-fpeIC2FZuPmw7mIsTvgB5BNc8QVxQC/nWg2W+CgPYOAiBiYVuHe2E8HiTWHBMIJQ", "sha384-ZD4C1ohrucZOfP7+jQSuBELICO7Z73CFD5stbjic1D3DbZk88mqj3KsRjSml/NCK") + .SetCdnIntegrity( + "sha384-fpeIC2FZuPmw7mIsTvgB5BNc8QVxQC/nWg2W+CgPYOAiBiYVuHe2E8HiTWHBMIJQ", + "sha384-ZD4C1ohrucZOfP7+jQSuBELICO7Z73CFD5stbjic1D3DbZk88mqj3KsRjSml/NCK" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-mode-htmlmixed") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/htmlmixed/htmlmixed.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/htmlmixed/htmlmixed.js") .SetCdn(CodeMirrorUrl + "mode/htmlmixed/htmlmixed.min.js", CodeMirrorUrl + "mode/htmlmixed/htmlmixed.js") - .SetCdnIntegrity("sha384-xYIbc5F55vPi7pb/lUnFj3wu24HlpAMZdtBHkNrb2YhPzJV3pX7+eqXT2PXSNMrw", "sha384-0MH/N0DfWPIbCXDe9I7tmLw0dsJ4gKQUijwCcpaTgGxrTTrypsJwEOOqi5yhkQiK") + .SetCdnIntegrity( + "sha384-xYIbc5F55vPi7pb/lUnFj3wu24HlpAMZdtBHkNrb2YhPzJV3pX7+eqXT2PXSNMrw", + "sha384-0MH/N0DfWPIbCXDe9I7tmLw0dsJ4gKQUijwCcpaTgGxrTTrypsJwEOOqi5yhkQiK" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-mode-javascript") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/javascript/javascript.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/javascript/javascript.js") .SetCdn(CodeMirrorUrl + "mode/javascript/javascript.min.js", CodeMirrorUrl + "mode/javascript/javascript.js") - .SetCdnIntegrity("sha384-kmQrbJf09Uo1WRLMDVGoVG3nM6F48frIhcj7f3FDUjeRzsiHwyBWDjMUIttnIeAf", "sha384-fgstVTG7RpZvquT2ZtQeU9iJXfvK9wTstlhasVKML77E5oe3Wi0AfLzY2grsjwmh") + .SetCdnIntegrity( + "sha384-kmQrbJf09Uo1WRLMDVGoVG3nM6F48frIhcj7f3FDUjeRzsiHwyBWDjMUIttnIeAf", + "sha384-fgstVTG7RpZvquT2ZtQeU9iJXfvK9wTstlhasVKML77E5oe3Wi0AfLzY2grsjwmh" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-mode-sql") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/sql/sql.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/sql/sql.js") .SetCdn(CodeMirrorUrl + "mode/sql/sql.min.js", CodeMirrorUrl + "mode/sql/sql.js") - .SetCdnIntegrity("sha384-cof/65v3Fn+7YeqmMp8aCI1xZ2yeX8JnWhQYdMzaO7VDpBOtLjfdwx6pEfUo7SFT", "sha384-Llr4/OHf89ufsfG7HbSwqB7KTd1d4hXok/Yxi72qWvLwtd6pz6nqJdOGlDdpjw6I") + .SetCdnIntegrity( + "sha384-cof/65v3Fn+7YeqmMp8aCI1xZ2yeX8JnWhQYdMzaO7VDpBOtLjfdwx6pEfUo7SFT", + "sha384-Llr4/OHf89ufsfG7HbSwqB7KTd1d4hXok/Yxi72qWvLwtd6pz6nqJdOGlDdpjw6I" + ) .SetVersion(CodeMirrorVersion); manifest .DefineScript("codemirror-mode-xml") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/xml/xml.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/xml/xml.js") .SetCdn(CodeMirrorUrl + "mode/xml/xml.min.js", CodeMirrorUrl + "mode/xml/xml.js") - .SetCdnIntegrity("sha384-xPpkMo5nDgD98fIcuRVYhxkZV6/9Y4L8s3p0J5c4MxgJkyKJ8BJr+xfRkq7kn6Tw", "sha384-KX/+LdYWr3JcKfT7HK55DC3oPVJwnJSympb1qoO14sxVDtDIg+xHPVLltqJEbitI") + .SetCdnIntegrity( + "sha384-xPpkMo5nDgD98fIcuRVYhxkZV6/9Y4L8s3p0J5c4MxgJkyKJ8BJr+xfRkq7kn6Tw", + "sha384-KX/+LdYWr3JcKfT7HK55DC3oPVJwnJSympb1qoO14sxVDtDIg+xHPVLltqJEbitI" + ) .SetVersion(CodeMirrorVersion); manifest .DefineStyle("font-awesome") .SetUrl("~/OrchardCore.Resources/Styles/font-awesome.min.css", "~/OrchardCore.Resources/Styles/font-awesome.css") .SetCdn("https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css", "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css") - .SetCdnIntegrity("sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN", "sha384-FckWOBo7yuyMS7In0aXZ0aoVvnInlnFMwCv77x9sZpFgOonQgnBj1uLwenWVtsEj") + .SetCdnIntegrity( + "sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN", + "sha384-FckWOBo7yuyMS7In0aXZ0aoVvnInlnFMwCv77x9sZpFgOonQgnBj1uLwenWVtsEj" + ) .SetVersion("4.7.0"); manifest .DefineStyle("font-awesome") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.min.css", "~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.css") - .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.css") - .SetCdnIntegrity("sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm", "sha384-7rgjkhkxJ95zOzIjk97UrBOe14KgYpH9+zQm5BdgzjQELBU6kHf4WwoQzHfTx5sw") + .SetCdn( + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css", + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.css" + ) + .SetCdnIntegrity( + "sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm", + "sha384-7rgjkhkxJ95zOzIjk97UrBOe14KgYpH9+zQm5BdgzjQELBU6kHf4WwoQzHfTx5sw" + ) .SetVersion("5.15.4"); manifest .DefineScript("font-awesome") - .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/all.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/all.js") - .SetCdnIntegrity("sha384-rOA1PnstxnOBLzCLMcre8ybwbTmemjzdNlILg8O7z1lUkLXozs4DHonlDtnE7fpc", "sha384-HfU7cInvKb8zxQuLKtKr/suuRgcSH1OYsdJU+8lGA/t8nyNgdJF09UIkRzg1iefj") + .SetCdn( + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/all.min.js", + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/all.js" + ) + .SetCdnIntegrity( + "sha384-rOA1PnstxnOBLzCLMcre8ybwbTmemjzdNlILg8O7z1lUkLXozs4DHonlDtnE7fpc", + "sha384-HfU7cInvKb8zxQuLKtKr/suuRgcSH1OYsdJU+8lGA/t8nyNgdJF09UIkRzg1iefj" + ) .SetVersion("5.15.4"); manifest .DefineScript("font-awesome-v4-shims") - .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/v4-shims.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/v4-shims.js") - .SetCdnIntegrity("sha384-bx00wqJq+zY9QLCMa/zViZPu1f0GJ3VXwF4GSw3GbfjwO28QCFr4qadCrNmJQ/9N", "sha384-SGuqaGE4bcW7Xl5T06BsUPUA91qaNtT53uGOcGpavQMje3goIFJbDsC0VAwtgL5g") + .SetCdn( + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/v4-shims.min.js", + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/v4-shims.js" + ) + .SetCdnIntegrity( + "sha384-bx00wqJq+zY9QLCMa/zViZPu1f0GJ3VXwF4GSw3GbfjwO28QCFr4qadCrNmJQ/9N", + "sha384-SGuqaGE4bcW7Xl5T06BsUPUA91qaNtT53uGOcGpavQMje3goIFJbDsC0VAwtgL5g" + ) .SetVersion("5.15.4"); manifest .DefineStyle("font-awesome") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.min.css", "~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.css") - .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/css/all.min.css", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/css/all.css") - .SetCdnIntegrity("sha384-t1nt8BQoYMLFN5p42tRAtuAAFQaCQODekUVeKKZrEnEyp4H2R0RHFz0KWpmj7i8g", "sha384-nrXXWLUi1MQU4ppkxCt05kh8YtWDU5Nf6gJikuch3OWafB4DxebHYZyah2r0+pVZ") + .SetCdn( + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/css/all.min.css", + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/css/all.css" + ) + .SetCdnIntegrity( + "sha384-t1nt8BQoYMLFN5p42tRAtuAAFQaCQODekUVeKKZrEnEyp4H2R0RHFz0KWpmj7i8g", + "sha384-nrXXWLUi1MQU4ppkxCt05kh8YtWDU5Nf6gJikuch3OWafB4DxebHYZyah2r0+pVZ" + ) .SetVersion("6.5.1"); manifest .DefineScript("font-awesome") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/js/all.min.js", "~/OrchardCore.Resources/Vendor/fontawesome-free/js/all.js") - .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/js/all.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/js/all.js") - .SetCdnIntegrity("sha384-3ve3u7etWcm2heCe4TswfZSAYSg2jR/EJxRHuKM5foOiKS8IJL/xRlvmjCaHELBz", "sha384-IkmLcEDxkvCioiswmdraONwAU9uwbPWUbvuHAGrejK3zNlL74FCwCjvnTGJcrdbQ") + .SetCdn( + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/js/all.min.js", + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/js/all.js" + ) + .SetCdnIntegrity( + "sha384-3ve3u7etWcm2heCe4TswfZSAYSg2jR/EJxRHuKM5foOiKS8IJL/xRlvmjCaHELBz", + "sha384-IkmLcEDxkvCioiswmdraONwAU9uwbPWUbvuHAGrejK3zNlL74FCwCjvnTGJcrdbQ" + ) .SetVersion("6.5.1"); manifest .DefineScript("font-awesome-v4-shims") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/js/v4-shims.min.js", "~/OrchardCore.Resources/Vendor/fontawesome-free/js/v4-shims.js") - .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/js/v4-shims.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/js/v4-shims.js") - .SetCdnIntegrity("sha384-HJMj0TodsrM5KmHW8l+5NnGnq9DLtu9LlpFYFFXVne/+pnZYGxIWtFFGRQSbcPo9", "sha384-J7/Cp2KkX6wV+2gGoFn8nB3/z3uoSut1tZKtmf4gqqGUwM1L0YI3n6rJst683v9Z") + .SetCdn( + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/js/v4-shims.min.js", + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/js/v4-shims.js" + ) + .SetCdnIntegrity( + "sha384-HJMj0TodsrM5KmHW8l+5NnGnq9DLtu9LlpFYFFXVne/+pnZYGxIWtFFGRQSbcPo9", + "sha384-J7/Cp2KkX6wV+2gGoFn8nB3/z3uoSut1tZKtmf4gqqGUwM1L0YI3n6rJst683v9Z" + ) .SetVersion("6.5.1"); manifest @@ -407,14 +589,20 @@ ResourceManifest BuildManifest() .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-resizable.min.js", "~/OrchardCore.Resources/Scripts/jquery-resizable.js") .SetCdn("https://cdn.jsdelivr.net/npm/jquery-resizable-dom@0.35.0/dist/jquery-resizable.min.js") - .SetCdnIntegrity("sha384-1LMjDEezsSgzlRgsyFIAvLW7FWSdFIHqBGjUa+ad5EqtK1FORC8XpTJ/pahxj5GB", "sha384-0yk9X0IG0cXxuN9yTTkps/3TNNI9ZcaKKhh8dgqOEAWGXxIYS5xaY2as6b32Ov3P") + .SetCdnIntegrity( + "sha384-1LMjDEezsSgzlRgsyFIAvLW7FWSdFIHqBGjUa+ad5EqtK1FORC8XpTJ/pahxj5GB", + "sha384-0yk9X0IG0cXxuN9yTTkps/3TNNI9ZcaKKhh8dgqOEAWGXxIYS5xaY2as6b32Ov3P" + ) .SetVersion("0.35.0"); manifest .DefineStyle("trumbowyg") .SetUrl("~/OrchardCore.Resources/Styles/trumbowyg.min.css", "~/OrchardCore.Resources/Styles/trumbowyg.css") .SetCdn("https://cdn.jsdelivr.net/npm/trumbowyg@2.27.3/dist/ui/trumbowyg.min.css", "https://cdn.jsdelivr.net/npm/trumbowyg@2.27.3/dist/ui/trumbowyg.css") - .SetCdnIntegrity("sha384-BMSJyRuWWysKSQXUwY6xhPnRLhIEIKVrndBFiMT8osUv0Jy4u+kVojiTB4oIk9Cy", "sha384-+WI6uKHvRRdOtp4c41xrQHz3liE5QZxjkFUx8KwLRMiMgSPpkoMnUMOjO7k8WH1Q") + .SetCdnIntegrity( + "sha384-BMSJyRuWWysKSQXUwY6xhPnRLhIEIKVrndBFiMT8osUv0Jy4u+kVojiTB4oIk9Cy", + "sha384-+WI6uKHvRRdOtp4c41xrQHz3liE5QZxjkFUx8KwLRMiMgSPpkoMnUMOjO7k8WH1Q" + ) .SetVersion("2.27.3"); manifest @@ -422,7 +610,10 @@ ResourceManifest BuildManifest() .SetDependencies("jquery-resizable") .SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg.min.js", "~/OrchardCore.Resources/Scripts/trumbowyg.js") .SetCdn("https://cdn.jsdelivr.net/npm/trumbowyg@2.27.3/dist/trumbowyg.min.js", "https://cdn.jsdelivr.net/npm/trumbowyg@2.27.3/dist/trumbowyg.js") - .SetCdnIntegrity("sha384-OZd+lx/Xv8IR7nJZmRKR4NJhT0urUXigW5V7FOEtmrFRf1BKKVc0DWhdiCh8UX8+", "sha384-nWqhxDAuUls0N/CYl8px54jeiP9i8+J64k1UPiM6DMC/u/qRY+jfkprB5VndU7B4") + .SetCdnIntegrity( + "sha384-OZd+lx/Xv8IR7nJZmRKR4NJhT0urUXigW5V7FOEtmrFRf1BKKVc0DWhdiCh8UX8+", + "sha384-nWqhxDAuUls0N/CYl8px54jeiP9i8+J64k1UPiM6DMC/u/qRY+jfkprB5VndU7B4" + ) .SetVersion("2.27.3"); manifest @@ -447,51 +638,74 @@ ResourceManifest BuildManifest() .DefineScript("vuejs") .SetUrl("~/OrchardCore.Resources/Scripts/vue.min.js", "~/OrchardCore.Resources/Scripts/vue.js") .SetCdn("https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js", "https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js") - .SetCdnIntegrity("sha384-ULpZhk1pvhc/UK5ktA9kwb2guy9ovNSTyxPNHANnA35YjBQgdwI+AhLkixDvdlw4", "sha384-t1tHLsbM7bYMJCXlhr0//00jSs7ZhsAhxgm191xFsyzvieTMCbUWKMhFg9I6ci8q") + .SetCdnIntegrity( + "sha384-ULpZhk1pvhc/UK5ktA9kwb2guy9ovNSTyxPNHANnA35YjBQgdwI+AhLkixDvdlw4", + "sha384-t1tHLsbM7bYMJCXlhr0//00jSs7ZhsAhxgm191xFsyzvieTMCbUWKMhFg9I6ci8q" + ) .SetVersion("2.6.14"); manifest .DefineScript("vue-multiselect") .SetDependencies("vuejs") .SetUrl("~/OrchardCore.Resources/Scripts/vue-multiselect.min.js", "~/OrchardCore.Resources/Scripts/vue-multiselect.min.js") - .SetCdn("https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.js", "https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.js") - .SetCdnIntegrity("sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU", "sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU") + .SetCdn( + "https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.js", + "https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.js" + ) + .SetCdnIntegrity( + "sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU", + "sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU" + ) .SetVersion("2.1.6"); manifest .DefineStyle("vue-multiselect") .SetUrl("~/OrchardCore.Resources/Styles/vue-multiselect.min.css", "~/OrchardCore.Resources/Styles/vue-multiselect.min.css") - .SetCdn("https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.css", "https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.css") - .SetCdnIntegrity("sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM", "sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM") + .SetCdn( + "https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.css", + "https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.css" + ) + .SetCdnIntegrity( + "sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM", + "sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM" + ) .SetVersion("2.1.6"); manifest .DefineScript("Sortable") .SetUrl("~/OrchardCore.Resources/Scripts/Sortable.min.js", "~/OrchardCore.Resources/Scripts/Sortable.js") .SetCdn("https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js", "https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.js") - .SetCdnIntegrity("sha384-eeLEhtwdMwD3X9y+8P3Cn7Idl/M+w8H4uZqkgD/2eJVkWIN1yKzEj6XegJ9dL3q0", "sha384-OFIl93h6jYoAF+hATXncsLYMiLo81FpuReH3fgCI4wep7qNCmiA2I0bwcvVqHSBj") + .SetCdnIntegrity( + "sha384-eeLEhtwdMwD3X9y+8P3Cn7Idl/M+w8H4uZqkgD/2eJVkWIN1yKzEj6XegJ9dL3q0", + "sha384-OFIl93h6jYoAF+hATXncsLYMiLo81FpuReH3fgCI4wep7qNCmiA2I0bwcvVqHSBj" + ) .SetVersion("1.15.0"); manifest .DefineScript("vuedraggable") .SetDependencies("vuejs", "Sortable") .SetUrl("~/OrchardCore.Resources/Scripts/vuedraggable.umd.min.js", "~/OrchardCore.Resources/Scripts/vuedraggable.umd.js") - .SetCdn("https://cdn.jsdelivr.net/npm/vuedraggable@2.24.3/dist/vuedraggable.umd.min.js", "https://cdn.jsdelivr.net/npm/vuedraggable@2.24.3/dist/vuedraggable.umd.js") - .SetCdnIntegrity("sha384-qUA1xXJiX23E4GOeW/XHtsBkV9MUcHLSjhi3FzO08mv8+W8bv5AQ1cwqLskycOTs", "sha384-+jB9vXc/EaIJTlNiZG2tv+TUpKm6GR9HCRZb3VkI3lscZWqrCYDbX2ZXffNJldL9") + .SetCdn( + "https://cdn.jsdelivr.net/npm/vuedraggable@2.24.3/dist/vuedraggable.umd.min.js", + "https://cdn.jsdelivr.net/npm/vuedraggable@2.24.3/dist/vuedraggable.umd.js" + ) + .SetCdnIntegrity( + "sha384-qUA1xXJiX23E4GOeW/XHtsBkV9MUcHLSjhi3FzO08mv8+W8bv5AQ1cwqLskycOTs", + "sha384-+jB9vXc/EaIJTlNiZG2tv+TUpKm6GR9HCRZb3VkI3lscZWqrCYDbX2ZXffNJldL9" + ) .SetVersion("2.24.3"); manifest .DefineScript("js-cookie") .SetUrl("~/OrchardCore.Resources/Scripts/js.cookie.min.js", "~/OrchardCore.Resources/Scripts/js.cookie.js") .SetCdn("https://cdn.jsdelivr.net/npm/js-cookie@3.0.5/dist/js.cookie.min.js", "https://cdn.jsdelivr.net/npm/js-cookie@3.0.5/dist/js.cookie.js") - .SetCdnIntegrity("sha384-/vxhYfM1LENRhdpZ8dwEsQn/X4VhpbEZSiU4m/FwR+PVpzar4fkEOw8FP9Y+OfQN", "sha384-b1TD0tFP+Ao4jmFaQw9RQxezUooFrLdlqfDfoh1SKv5L3jG7dD44QiwD+UzckH8W") + .SetCdnIntegrity( + "sha384-/vxhYfM1LENRhdpZ8dwEsQn/X4VhpbEZSiU4m/FwR+PVpzar4fkEOw8FP9Y+OfQN", + "sha384-b1TD0tFP+Ao4jmFaQw9RQxezUooFrLdlqfDfoh1SKv5L3jG7dD44QiwD+UzckH8W" + ) .SetVersion("3.0.5"); - manifest - .DefineScript("monaco-loader") - .SetUrl("~/OrchardCore.Resources/Scripts/monaco/vs/loader.js") - .SetPosition(ResourcePosition.Last) - .SetVersion(MonacoEditorVersion); + manifest.DefineScript("monaco-loader").SetUrl("~/OrchardCore.Resources/Scripts/monaco/vs/loader.js").SetPosition(ResourcePosition.Last).SetVersion(MonacoEditorVersion); manifest .DefineScript("monaco") diff --git a/src/OrchardCore.Modules/OrchardCore.ReverseProxy/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.ReverseProxy/AdminMenu.cs index 4231c4812d7..6bbe7961f11 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReverseProxy/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReverseProxy/AdminMenu.cs @@ -8,11 +8,7 @@ namespace OrchardCore.ReverseProxy { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", ReverseProxySettingsDisplayDriver.GroupId}, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", ReverseProxySettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -28,18 +24,25 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Reverse Proxy"], S["Reverse Proxy"].PrefixPosition(), entry => entry - .AddClass("reverseproxy") - .Id("reverseproxy") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageReverseProxySettings) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Reverse Proxy"], + S["Reverse Proxy"].PrefixPosition(), + entry => + entry + .AddClass("reverseproxy") + .Id("reverseproxy") + .Action("Index", "Admin", _routeValues) + .Permission(Permissions.ManageReverseProxySettings) + .LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Drivers/ReverseProxySettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Drivers/ReverseProxySettingsDisplayDriver.cs index ee440e581c3..7b75052c79f 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Drivers/ReverseProxySettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Drivers/ReverseProxySettingsDisplayDriver.cs @@ -25,7 +25,8 @@ public ReverseProxySettingsDisplayDriver( IShellHost shellHost, ShellSettings shellSettings, IHttpContextAccessor httpContextAccessor, - IAuthorizationService authorizationService) + IAuthorizationService authorizationService + ) { _shellHost = shellHost; _shellSettings = shellSettings; @@ -42,12 +43,17 @@ public override async Task EditAsync(ReverseProxySettings settin return null; } - return Initialize("ReverseProxySettings_Edit", model => - { - model.EnableXForwardedFor = settings.ForwardedHeaders.HasFlag(ForwardedHeaders.XForwardedFor); - model.EnableXForwardedHost = settings.ForwardedHeaders.HasFlag(ForwardedHeaders.XForwardedHost); - model.EnableXForwardedProto = settings.ForwardedHeaders.HasFlag(ForwardedHeaders.XForwardedProto); - }).Location("Content:2").OnGroup(GroupId); + return Initialize( + "ReverseProxySettings_Edit", + model => + { + model.EnableXForwardedFor = settings.ForwardedHeaders.HasFlag(ForwardedHeaders.XForwardedFor); + model.EnableXForwardedHost = settings.ForwardedHeaders.HasFlag(ForwardedHeaders.XForwardedHost); + model.EnableXForwardedProto = settings.ForwardedHeaders.HasFlag(ForwardedHeaders.XForwardedProto); + } + ) + .Location("Content:2") + .OnGroup(GroupId); } public override async Task UpdateAsync(ReverseProxySettings section, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Extensions/OrchardCoreBuilderExtensions.cs b/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Extensions/OrchardCoreBuilderExtensions.cs index bfa6e78e732..f3fc7dd1221 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Extensions/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Extensions/OrchardCoreBuilderExtensions.cs @@ -8,12 +8,14 @@ public static class OrchardCoreBuilderExtensions { public static OrchardCoreBuilder ConfigureReverseProxySettings(this OrchardCoreBuilder builder) { - builder.ConfigureServices((tenantServices, serviceProvider) => - { - var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_ReverseProxy"); + builder.ConfigureServices( + (tenantServices, serviceProvider) => + { + var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_ReverseProxy"); - tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); - }); + tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); + } + ); return builder; } diff --git a/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Permissions.cs index 76bd4546420..3dfe1720e43 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageReverseProxySettings = new("ManageReverseProxySettings", "Manage Reverse Proxy Settings"); - private readonly IEnumerable _allPermissions = - [ - ManageReverseProxySettings, - ]; + private readonly IEnumerable _allPermissions = [ManageReverseProxySettings,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Startup.cs b/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Startup.cs index 83f97488ff3..18f8c79d20d 100644 --- a/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.ReverseProxy/Startup.cs @@ -34,8 +34,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddSingleton(); - services.TryAddEnumerable(ServiceDescriptor - .Transient, ForwardedHeadersOptionsConfiguration>()); + services.TryAddEnumerable(ServiceDescriptor.Transient, ForwardedHeadersOptionsConfiguration>()); } } @@ -44,7 +43,10 @@ public class DeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddSiteSettingsPropertyDeploymentStep(S => S["Reverse Proxy settings"], S => S["Exports the Reverse Proxy settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Reverse Proxy settings"], + S => S["Exports the Reverse Proxy settings."] + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Roles/AdminMenu.cs index 3d86d657a5c..4763fb44ebf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/AdminMenu.cs @@ -20,15 +20,15 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Roles"], S["Roles"].PrefixPosition(), roles => roles - .AddClass("roles").Id("roles") - .Action("Index", "Admin", "OrchardCore.Roles") - .Permission(Permissions.ManageRoles) - .LocalNav() + builder.Add( + S["Security"], + security => + security.Add( + S["Roles"], + S["Roles"].PrefixPosition(), + roles => roles.AddClass("roles").Id("roles").Action("Index", "Admin", "OrchardCore.Roles").Permission(Permissions.ManageRoles).LocalNav() ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Roles/Controllers/AdminController.cs index d779b29abf4..b0fa71e1262 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/Controllers/AdminController.cs @@ -42,7 +42,8 @@ public AdminController( IRoleService roleService, INotifier notifier, IStringLocalizer stringLocalizer, - IHtmlLocalizer htmlLocalizer) + IHtmlLocalizer htmlLocalizer + ) { _documentStore = documentStore; _roleManager = roleManager; @@ -64,10 +65,7 @@ public async Task Index() var roles = await _roleService.GetRolesAsync(); - var model = new RolesViewModel - { - RoleEntries = roles.Select(BuildRoleEntry).ToList() - }; + var model = new RolesViewModel { RoleEntries = roles.Select(BuildRoleEntry).ToList() }; return View(model); } @@ -273,18 +271,17 @@ private PermissionGroupKey GetGroupKey(IFeatureInfo feature, string category) var title = string.IsNullOrWhiteSpace(feature.Name) ? S["{0} Feature", feature.Id] : feature.Name; - return new PermissionGroupKey(feature.Id, title) - { - Source = feature.Id, - }; + return new PermissionGroupKey(feature.Id, title) { Source = feature.Id, }; } private async Task> GetEffectivePermissions(Role role, IEnumerable allPermissions) { // Create a fake user to check the actual permissions. If the role is anonymous // IsAuthenticated needs to be false. - var fakeIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, role.RoleName) }, - !string.Equals(role.RoleName, "Anonymous", StringComparison.OrdinalIgnoreCase) ? "FakeAuthenticationType" : null); + var fakeIdentity = new ClaimsIdentity( + new[] { new Claim(ClaimTypes.Role, role.RoleName) }, + !string.Equals(role.RoleName, "Anonymous", StringComparison.OrdinalIgnoreCase) ? "FakeAuthenticationType" : null + ); // Add role claims fakeIdentity.AddClaims(role.RoleClaims.Select(c => c.ToClaim())); diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/Deployment/AllRolesDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Roles/Deployment/AllRolesDeploymentSource.cs index 80bf4a3c077..2f18013d6cf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/Deployment/AllRolesDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/Deployment/AllRolesDeploymentSource.cs @@ -42,21 +42,20 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan if (currentRole != null) { - permissions.Add(JObject.FromObject( - new RolesStepRoleModel - { - Name = currentRole.RoleName, - Description = currentRole.RoleDescription, - Permissions = currentRole.RoleClaims.Where(x => x.ClaimType == Permission.ClaimType).Select(x => x.ClaimValue).ToArray() - })); + permissions.Add( + JObject.FromObject( + new RolesStepRoleModel + { + Name = currentRole.RoleName, + Description = currentRole.RoleDescription, + Permissions = currentRole.RoleClaims.Where(x => x.ClaimType == Permission.ClaimType).Select(x => x.ClaimValue).ToArray() + } + ) + ); } } - result.Steps.Add(new JsonObject - { - ["name"] = "Roles", - ["Roles"] = permissions, - }); + result.Steps.Add(new JsonObject { ["name"] = "Roles", ["Roles"] = permissions, }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/Deployment/AllRolesDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Roles/Deployment/AllRolesDeploymentStepDriver.cs index 29f7069eb17..93599496092 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/Deployment/AllRolesDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/Deployment/AllRolesDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class AllRolesDeploymentStepDriver : DisplayDriver> GetPermissionsAsync() { - var roleNames = (await _roleService.GetRoleNamesAsync()) - .Where(roleName => !RoleHelper.SystemRoleNames.Contains(roleName)) - .ToList(); + var roleNames = (await _roleService.GetRoleNamesAsync()).Where(roleName => !RoleHelper.SystemRoleNames.Contains(roleName)).ToList(); - var list = new List(roleNames.Count + 3) - { - ManageRoles, - AssignRoles, - SiteOwner, - }; + var list = new List(roleNames.Count + 3) { ManageRoles, AssignRoles, SiteOwner, }; foreach (var roleName in roleNames) { @@ -41,16 +34,5 @@ public async Task> GetPermissionsAsync() return list; } - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = - [ - ManageRoles, - SiteOwner, - ], - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = [ManageRoles, SiteOwner,], },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/Services/RoleStore.cs b/src/OrchardCore.Modules/OrchardCore.Roles/Services/RoleStore.cs index de696464c1c..9f1bbe4d809 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/Services/RoleStore.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/Services/RoleStore.cs @@ -24,11 +24,7 @@ public class RoleStore : IRoleClaimStore, IQueryableRoleStore private bool _updating; - public RoleStore( - IServiceProvider serviceProvider, - IDocumentManager documentManager, - IStringLocalizer stringLocalizer, - ILogger logger) + public RoleStore(IServiceProvider serviceProvider, IDocumentManager documentManager, IStringLocalizer stringLocalizer, ILogger logger) { _serviceProvider = serviceProvider; _documentManager = documentManager; @@ -72,8 +68,7 @@ public async Task CreateAsync(IRole role, CancellationToken canc var roleCreatedEventHandlers = _serviceProvider.GetRequiredService>(); - await roleCreatedEventHandlers.InvokeAsync((handler, roleToCreate) => - handler.RoleCreatedAsync(roleToCreate.RoleName), roleToCreate, _logger); + await roleCreatedEventHandlers.InvokeAsync((handler, roleToCreate) => handler.RoleCreatedAsync(roleToCreate.RoleName), roleToCreate, _logger); return IdentityResult.Success; } @@ -84,16 +79,14 @@ public async Task DeleteAsync(IRole role, CancellationToken canc var roleToRemove = (Role)role; - if (string.Equals(roleToRemove.NormalizedRoleName, "ANONYMOUS") || - string.Equals(roleToRemove.NormalizedRoleName, "AUTHENTICATED")) + if (string.Equals(roleToRemove.NormalizedRoleName, "ANONYMOUS") || string.Equals(roleToRemove.NormalizedRoleName, "AUTHENTICATED")) { return IdentityResult.Failed(new IdentityError { Description = S["Can't delete system roles."] }); } var roleRemovedEventHandlers = _serviceProvider.GetRequiredService>(); - await roleRemovedEventHandlers.InvokeAsync((handler, roleToRemove) => - handler.RoleRemovedAsync(roleToRemove.RoleName), roleToRemove, _logger); + await roleRemovedEventHandlers.InvokeAsync((handler, roleToRemove) => handler.RoleRemovedAsync(roleToRemove.RoleName), roleToRemove, _logger); var roles = await LoadRolesAsync(); roleToRemove = roles.Roles.FirstOrDefault(r => string.Equals(r.RoleName, roleToRemove.RoleName, StringComparison.OrdinalIgnoreCase)); @@ -223,9 +216,7 @@ public Task RemoveClaimAsync(IRole role, Claim claim, CancellationToken cancella #endregion IRoleClaimStore #pragma warning disable CA1816 - public void Dispose() - { - } + public void Dispose() { } #pragma warning restore CA1816 } } diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/Services/RoleUpdater.cs b/src/OrchardCore.Modules/OrchardCore.Roles/Services/RoleUpdater.cs index fcdb5c85455..8c713023e95 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/Services/RoleUpdater.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/Services/RoleUpdater.cs @@ -30,7 +30,8 @@ public RoleUpdater( IDocumentManager documentManager, IEnumerable permissionProviders, ITypeFeatureProvider typeFeatureProvider, - ILogger logger) + ILogger logger + ) { _shellDescriptor = shellDescriptor; _extensionManager = extensionManager; @@ -52,8 +53,7 @@ private async Task UpdateRolesForInstalledFeatureAsync(IFeatureInfo feature) { _installedFeatures.Add(feature.Id); - var providers = _permissionProviders - .Where(provider => _typeFeatureProvider.GetFeatureForDependency(provider.GetType()).Id == feature.Id); + var providers = _permissionProviders.Where(provider => _typeFeatureProvider.GetFeatureForDependency(provider.GetType()).Id == feature.Id); if (!providers.Any()) { @@ -73,8 +73,7 @@ private async Task UpdateRolesForInstalledFeatureAsync(IFeatureInfo feature) continue; } - var permissions = (stereotype.Permissions ?? []) - .Select(stereotype => stereotype.Name); + var permissions = (stereotype.Permissions ?? []).Select(stereotype => stereotype.Name); if (UpdateRole(role, permissions, _logger)) { @@ -96,8 +95,7 @@ private async Task UpdateRolesForEnabledFeatureAsync(IFeatureInfo feature) return; } - var providers = _permissionProviders - .Where(provider => _typeFeatureProvider.GetFeatureForDependency(provider.GetType()).Id == feature.Id); + var providers = _permissionProviders.Where(provider => _typeFeatureProvider.GetFeatureForDependency(provider.GetType()).Id == feature.Id); if (!providers.Any()) { @@ -108,8 +106,7 @@ private async Task UpdateRolesForEnabledFeatureAsync(IFeatureInfo feature) var rolesDocument = await _documentManager.GetOrCreateMutableAsync(); foreach (var role in rolesDocument.Roles) { - if (!rolesDocument.MissingFeaturesByRole.TryGetValue(role.RoleName, out var missingFeatures) || - !missingFeatures.Contains(feature.Id)) + if (!rolesDocument.MissingFeaturesByRole.TryGetValue(role.RoleName, out var missingFeatures) || !missingFeatures.Contains(feature.Id)) { continue; } @@ -136,10 +133,7 @@ private async Task UpdateRoleForInstalledFeaturesAsync(string roleName) } // Get installed features that are no more enabled. - var missingFeatures = _shellDescriptor.Installed - .Except(_shellDescriptor.Features) - .Select(feature => feature.Id) - .ToArray(); + var missingFeatures = _shellDescriptor.Installed.Except(_shellDescriptor.Features).Select(feature => feature.Id).ToArray(); // And defining at least one 'IPermissionProvider'. rolesDocument.MissingFeaturesByRole[roleName] = (await _extensionManager.LoadFeaturesAsync(missingFeatures)) @@ -158,9 +152,7 @@ private async Task UpdateRoleForInstalledFeaturesAsync(string roleName) return; } - var permissions = stereotypes - .SelectMany(stereotype => stereotype.Permissions ?? []) - .Select(stereotype => stereotype.Name); + var permissions = stereotypes.SelectMany(stereotype => stereotype.Permissions ?? []).Select(stereotype => stereotype.Name); UpdateRole(role, permissions, _logger); } @@ -186,9 +178,7 @@ private static bool UpdateRolesForEnabledFeature(Role role, IEnumerable stereotype.Permissions ?? []) - .Select(stereotype => stereotype.Name); + var permissions = stereotypes.SelectMany(stereotype => stereotype.Permissions ?? []).Select(stereotype => stereotype.Name); if (!permissions.Any()) { @@ -200,13 +190,9 @@ private static bool UpdateRolesForEnabledFeature(Role role, IEnumerable permissions, ILogger logger) { - var currentPermissions = role.RoleClaims - .Where(roleClaim => roleClaim.ClaimType == Permission.ClaimType) - .Select(roleClaim => roleClaim.ClaimValue); + var currentPermissions = role.RoleClaims.Where(roleClaim => roleClaim.ClaimType == Permission.ClaimType).Select(roleClaim => roleClaim.ClaimValue); - var distinctPermissions = currentPermissions - .Union(permissions) - .Distinct(); + var distinctPermissions = currentPermissions.Union(permissions).Distinct(); var additionalPermissions = distinctPermissions.Except(currentPermissions); if (!additionalPermissions.Any()) diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/Services/RolesPermissionsHandler.cs b/src/OrchardCore.Modules/OrchardCore.Roles/Services/RolesPermissionsHandler.cs index 127714ab505..eb30e44c92e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/Services/RolesPermissionsHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/Services/RolesPermissionsHandler.cs @@ -15,12 +15,10 @@ public class RolesPermissionsHandler : AuthorizationHandler _roleManager; private readonly IPermissionGrantingService _permissionGrantingService; + private IEnumerable _anonymousClaims = null, + _authenticatedClaims = null; - private IEnumerable _anonymousClaims = null, _authenticatedClaims = null; - - public RolesPermissionsHandler( - RoleManager roleManager, - IPermissionGrantingService permissionGrantingService) + public RolesPermissionsHandler(RoleManager roleManager, IPermissionGrantingService permissionGrantingService) { _roleManager = roleManager; _permissionGrantingService = permissionGrantingService; diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/ViewComponents/SelectRolesViewComponent.cs b/src/OrchardCore.Modules/OrchardCore.Roles/ViewComponents/SelectRolesViewComponent.cs index 34dfddedfa3..a509fa1dd69 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/ViewComponents/SelectRolesViewComponent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/ViewComponents/SelectRolesViewComponent.cs @@ -22,11 +22,7 @@ public async Task InvokeAsync(IEnumerable selected var roleSelections = await BuildRoleSelectionsAsync(selectedRoles, except); - var model = new SelectRolesViewModel - { - HtmlName = htmlName, - RoleSelections = roleSelections - }; + var model = new SelectRolesViewModel { HtmlName = htmlName, RoleSelections = roleSelections }; return View(model); } @@ -40,13 +36,7 @@ private async Task>> BuildRoleSelectionsAsync(IEnumerabl roleNames = roleNames.Except(except, StringComparer.OrdinalIgnoreCase); } - return roleNames.Select(x => new Selection - { - IsSelected = selectedRoles.Contains(x), - Item = x - }) - .OrderBy(x => x.Item) - .ToList(); + return roleNames.Select(x => new Selection { IsSelected = selectedRoles.Contains(x), Item = x }).OrderBy(x => x.Item).ToList(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/ViewModels/PermissionGroupKey.cs b/src/OrchardCore.Modules/OrchardCore.Roles/ViewModels/PermissionGroupKey.cs index 2a30f9ebe0f..ce0e550a2eb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/ViewModels/PermissionGroupKey.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/ViewModels/PermissionGroupKey.cs @@ -20,7 +20,8 @@ public PermissionGroupKey(string key) Key = key; } - public PermissionGroupKey(string key, string title) : this(key) + public PermissionGroupKey(string key, string title) + : this(key) { Title = title; } diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/Views/Workflows/Activities/GetUsersByRoleTask.cs b/src/OrchardCore.Modules/OrchardCore.Roles/Views/Workflows/Activities/GetUsersByRoleTask.cs index d420701388d..15d698e9c55 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/Views/Workflows/Activities/GetUsersByRoleTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/Views/Workflows/Activities/GetUsersByRoleTask.cs @@ -42,8 +42,7 @@ public IEnumerable Roles set => SetProperty(value); } - public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) - => Outcomes(S["Done"], S["Failed"]); + public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) => Outcomes(S["Done"], S["Failed"]); public override async Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/Views/Workflows/Activities/UnassignUserRoleTask.cs b/src/OrchardCore.Modules/OrchardCore.Roles/Views/Workflows/Activities/UnassignUserRoleTask.cs index 379df02529c..806878c8a82 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/Views/Workflows/Activities/UnassignUserRoleTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/Views/Workflows/Activities/UnassignUserRoleTask.cs @@ -19,7 +19,12 @@ public class UnassignUserRoleTask : TaskActivity private readonly IWorkflowExpressionEvaluator _expressionEvaluator; protected readonly IStringLocalizer S; - public UnassignUserRoleTask(UserManager userManager, IUserService userService, IWorkflowExpressionEvaluator expressionvaluator, IStringLocalizer localizer) + public UnassignUserRoleTask( + UserManager userManager, + IUserService userService, + IWorkflowExpressionEvaluator expressionvaluator, + IStringLocalizer localizer + ) { _userManager = userManager; _userService = userService; @@ -43,8 +48,7 @@ public IEnumerable Roles set => SetProperty(value); } - public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) - => Outcomes(S["Done"], S["Failed"]); + public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) => Outcomes(S["Done"], S["Failed"]); public override async Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/AllConditionDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/AllConditionDisplayDriver.cs index ec5af2949bb..458946f41da 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/AllConditionDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/AllConditionDisplayDriver.cs @@ -12,25 +12,32 @@ public class AllConditionDisplayDriver : DisplayDriver("ConditionGroup_Fields_Summary", m => - { - m.Entries = condition.Conditions.Select(x => new ConditionEntry { Condition = x }).ToArray(); - m.Condition = condition; - }).Location("Summary", "Content") - ); + return Combine( + View("AllCondition_Fields_Summary", condition).Location("Summary", "Content"), + View("AllCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content"), + Initialize( + "ConditionGroup_Fields_Summary", + m => + { + m.Entries = condition.Conditions.Select(x => new ConditionEntry { Condition = x }).ToArray(); + m.Condition = condition; + } + ) + .Location("Summary", "Content") + ); } public override IDisplayResult Edit(AllConditionGroup condition) { - return Initialize("AllCondition_Fields_Edit", m => - { - m.DisplayText = condition.DisplayText; - m.Condition = condition; - }).Location("Content"); + return Initialize( + "AllCondition_Fields_Edit", + m => + { + m.DisplayText = condition.DisplayText; + m.Condition = condition; + } + ) + .Location("Content"); } public override async Task UpdateAsync(AllConditionGroup condition, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/AnyConditionDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/AnyConditionDisplayDriver.cs index bdd5359d396..7da1f24ced4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/AnyConditionDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/AnyConditionDisplayDriver.cs @@ -12,25 +12,32 @@ public class AnyConditionDisplayDriver : DisplayDriver("ConditionGroup_Fields_Summary", m => - { - m.Entries = condition.Conditions.Select(x => new ConditionEntry { Condition = x }).ToArray(); - m.Condition = condition; - }).Location("Summary", "Content") - ); + return Combine( + View("AnyCondition_Fields_Summary", condition).Location("Summary", "Content"), + View("AnyCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content"), + Initialize( + "ConditionGroup_Fields_Summary", + m => + { + m.Entries = condition.Conditions.Select(x => new ConditionEntry { Condition = x }).ToArray(); + m.Condition = condition; + } + ) + .Location("Summary", "Content") + ); } public override IDisplayResult Edit(AnyConditionGroup condition) { - return Initialize("AnyCondition_Fields_Edit", m => - { - m.DisplayText = condition.DisplayText; - m.Condition = condition; - }).Location("Content"); + return Initialize( + "AnyCondition_Fields_Edit", + m => + { + m.DisplayText = condition.DisplayText; + m.Condition = condition; + } + ) + .Location("Content"); } public override async Task UpdateAsync(AnyConditionGroup condition, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/BooleanConditionDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/BooleanConditionDisplayDriver.cs index 20886c24d67..0055f126730 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/BooleanConditionDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/BooleanConditionDisplayDriver.cs @@ -11,20 +11,23 @@ public class BooleanConditionDisplayDriver : DisplayDriver("BooleanCondition_Fields_Edit", m => - { - m.Value = condition.Value; - m.Condition = condition; - }).Location("Content"); + return Initialize( + "BooleanCondition_Fields_Edit", + m => + { + m.Value = condition.Value; + m.Condition = condition; + } + ) + .Location("Content"); } public override async Task UpdateAsync(BooleanCondition condition, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/ContentTypeConditionDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/ContentTypeConditionDisplayDriver.cs index d0602ebbc67..176f125ca59 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/ContentTypeConditionDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/ContentTypeConditionDisplayDriver.cs @@ -19,24 +19,27 @@ public ContentTypeConditionDisplayDriver(IOptions opti public override IDisplayResult Display(ContentTypeCondition condition) { - return - Combine( - View("ContentTypeCondition_Fields_Summary", condition).Location("Summary", "Content"), - View("ContentTypeCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content") - ); + return Combine( + View("ContentTypeCondition_Fields_Summary", condition).Location("Summary", "Content"), + View("ContentTypeCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(ContentTypeCondition condition) { - return Initialize("ContentTypeCondition_Fields_Edit", m => - { - if (condition.Operation != null && _options.ConditionOperatorOptionByType.TryGetValue(condition.Operation.GetType(), out var option)) - { - m.SelectedOperation = option.Factory.Name; - } - m.Value = condition.Value; - m.Condition = condition; - }).Location("Content"); + return Initialize( + "ContentTypeCondition_Fields_Edit", + m => + { + if (condition.Operation != null && _options.ConditionOperatorOptionByType.TryGetValue(condition.Operation.GetType(), out var option)) + { + m.SelectedOperation = option.Factory.Name; + } + m.Value = condition.Value; + m.Condition = condition; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypeCondition condition, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/ContentTypeConditionEvaluatorDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/ContentTypeConditionEvaluatorDriver.cs index 59fe11dd09e..51efce3dce2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/ContentTypeConditionEvaluatorDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/ContentTypeConditionEvaluatorDriver.cs @@ -37,8 +37,7 @@ public override Task DisplayAsync(ContentItem contentItem, Build return Task.FromResult(null); } - public ValueTask EvaluateAsync(Condition condition) - => EvaluateAsync(condition as ContentTypeCondition); + public ValueTask EvaluateAsync(Condition condition) => EvaluateAsync(condition as ContentTypeCondition); private ValueTask EvaluateAsync(ContentTypeCondition condition) { diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/CultureConditionDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/CultureConditionDisplayDriver.cs index 6654d81562e..4b6450f93b7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/CultureConditionDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/CultureConditionDisplayDriver.cs @@ -19,24 +19,27 @@ public CultureConditionDisplayDriver(IOptions options) public override IDisplayResult Display(CultureCondition condition) { - return - Combine( - View("CultureCondition_Fields_Summary", condition).Location("Summary", "Content"), - View("CultureCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content") - ); + return Combine( + View("CultureCondition_Fields_Summary", condition).Location("Summary", "Content"), + View("CultureCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(CultureCondition condition) { - return Initialize("CultureCondition_Fields_Edit", m => - { - if (condition.Operation != null && _options.ConditionOperatorOptionByType.TryGetValue(condition.Operation.GetType(), out var option)) - { - m.SelectedOperation = option.Factory.Name; - } - m.Value = condition.Value; - m.Condition = condition; - }).Location("Content"); + return Initialize( + "CultureCondition_Fields_Edit", + m => + { + if (condition.Operation != null && _options.ConditionOperatorOptionByType.TryGetValue(condition.Operation.GetType(), out var option)) + { + m.SelectedOperation = option.Factory.Name; + } + m.Value = condition.Value; + m.Condition = condition; + } + ) + .Location("Content"); } public override async Task UpdateAsync(CultureCondition condition, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/HomepageConditionDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/HomepageConditionDisplayDriver.cs index 813e4be78c5..e0ec53393cc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/HomepageConditionDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/HomepageConditionDisplayDriver.cs @@ -11,20 +11,23 @@ public class HomepageConditionDisplayDriver : DisplayDriver("HomepageCondition_Fields_Edit", m => - { - m.Value = condition.Value; - m.Condition = condition; - }).Location("Content"); + return Initialize( + "HomepageCondition_Fields_Edit", + m => + { + m.Value = condition.Value; + m.Condition = condition; + } + ) + .Location("Content"); } public override async Task UpdateAsync(HomepageCondition condition, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/IsAnonymousConditionDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/IsAnonymousConditionDisplayDriver.cs index e2d9c139e96..d3eebce3d8d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/IsAnonymousConditionDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/IsAnonymousConditionDisplayDriver.cs @@ -8,11 +8,10 @@ public class IsAnonymousConditionDisplayDriver : DisplayDriver("JavascriptCondition_Fields_Edit", m => - { - m.Script = condition.Script; - m.Condition = condition; - }).Location("Content"); + return Initialize( + "JavascriptCondition_Fields_Edit", + m => + { + m.Script = condition.Script; + m.Condition = condition; + } + ) + .Location("Content"); } public override async Task UpdateAsync(JavascriptCondition condition, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/RoleConditionDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/RoleConditionDisplayDriver.cs index 70e3decf055..db482024c49 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/RoleConditionDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/RoleConditionDisplayDriver.cs @@ -19,24 +19,27 @@ public RoleConditionDisplayDriver(IOptions options) public override IDisplayResult Display(RoleCondition condition) { - return - Combine( - View("RoleCondition_Fields_Summary", condition).Location("Summary", "Content"), - View("RoleCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content") - ); + return Combine( + View("RoleCondition_Fields_Summary", condition).Location("Summary", "Content"), + View("RoleCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(RoleCondition condition) { - return Initialize("RoleCondition_Fields_Edit", m => - { - if (condition.Operation != null && _options.ConditionOperatorOptionByType.TryGetValue(condition.Operation.GetType(), out var option)) - { - m.SelectedOperation = option.Factory.Name; - } - m.Value = condition.Value; - m.Condition = condition; - }).Location("Content"); + return Initialize( + "RoleCondition_Fields_Edit", + m => + { + if (condition.Operation != null && _options.ConditionOperatorOptionByType.TryGetValue(condition.Operation.GetType(), out var option)) + { + m.SelectedOperation = option.Factory.Name; + } + m.Value = condition.Value; + m.Condition = condition; + } + ) + .Location("Content"); } public override async Task UpdateAsync(RoleCondition condition, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/RuleDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/RuleDisplayDriver.cs index bead121e265..14078a8646e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/RuleDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/RuleDisplayDriver.cs @@ -11,11 +11,15 @@ public override IDisplayResult Display(Rule rule) { return Combine( View("Rule_Fields_Summary", rule).Location("Summary", "Content"), - Initialize("ConditionGroup_Fields_Summary", m => - { - m.Entries = rule.Conditions.Select(x => new ConditionEntry { Condition = x }).ToArray(); - m.Condition = rule; - }).Location("Summary", "Content") + Initialize( + "ConditionGroup_Fields_Summary", + m => + { + m.Entries = rule.Conditions.Select(x => new ConditionEntry { Condition = x }).ToArray(); + m.Condition = rule; + } + ) + .Location("Summary", "Content") ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/UrlConditionDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/UrlConditionDisplayDriver.cs index dd170ce8695..5243910973b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/UrlConditionDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Drivers/UrlConditionDisplayDriver.cs @@ -19,24 +19,27 @@ public UrlConditionDisplayDriver(IOptions options) public override IDisplayResult Display(UrlCondition condition) { - return - Combine( - View("UrlCondition_Fields_Summary", condition).Location("Summary", "Content"), - View("UrlCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content") - ); + return Combine( + View("UrlCondition_Fields_Summary", condition).Location("Summary", "Content"), + View("UrlCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(UrlCondition condition) { - return Initialize("UrlCondition_Fields_Edit", m => - { - if (condition.Operation != null && _options.ConditionOperatorOptionByType.TryGetValue(condition.Operation.GetType(), out var option)) - { - m.SelectedOperation = option.Factory.Name; - } - m.Value = condition.Value; - m.Condition = condition; - }).Location("Content"); + return Initialize( + "UrlCondition_Fields_Edit", + m => + { + if (condition.Operation != null && _options.ConditionOperatorOptionByType.TryGetValue(condition.Operation.GetType(), out var option)) + { + m.SelectedOperation = option.Factory.Name; + } + m.Value = condition.Value; + m.Condition = condition; + } + ) + .Location("Content"); } public override async Task UpdateAsync(UrlCondition condition, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Manifest.cs index 6670cc5a1bc..f5bf01687cf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Manifest.cs @@ -1,19 +1,11 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Rules", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Rules", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Rules", Name = "Rules", Description = "The Rules module adds rule building capabilities.", - Dependencies = - [ - "OrchardCore.Scripting" - ], + Dependencies = ["OrchardCore.Scripting"], Category = "Infrastructure" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Models/AllConditionGroup.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Models/AllConditionGroup.cs index be35b1dc547..a0906033724 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Models/AllConditionGroup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Models/AllConditionGroup.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Rules.Models { - public class AllConditionGroup : DisplayTextConditionGroup - { - } + public class AllConditionGroup : DisplayTextConditionGroup { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Models/AnyConditionGroup.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Models/AnyConditionGroup.cs index 5b7d887f052..46f0ec7a0a9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Models/AnyConditionGroup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Models/AnyConditionGroup.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Rules.Models { - public class AnyConditionGroup : DisplayTextConditionGroup - { - } + public class AnyConditionGroup : DisplayTextConditionGroup { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Models/IsAnonymousCondition.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Models/IsAnonymousCondition.cs index 6da53467093..3c4184a10d9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Models/IsAnonymousCondition.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Models/IsAnonymousCondition.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Rules.Models { - public class IsAnonymousCondition : Condition - { - } + public class IsAnonymousCondition : Condition { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Models/IsAuthenticatedCondition.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Models/IsAuthenticatedCondition.cs index e597654cb10..3c184d51996 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Models/IsAuthenticatedCondition.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Models/IsAuthenticatedCondition.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Rules.Models { - public class IsAuthenticatedCondition : Condition - { - } + public class IsAuthenticatedCondition : Condition { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Models/StringOperators.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Models/StringOperators.cs index 38231a650c2..ad53e6c4fab 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Models/StringOperators.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Models/StringOperators.cs @@ -5,35 +5,19 @@ public abstract class StringOperator : ConditionOperator public bool CaseSensitive { get; set; } } - public class StringEqualsOperator : StringOperator - { - } + public class StringEqualsOperator : StringOperator { } - public class StringNotEqualsOperator : StringOperator, INegateOperator - { - } + public class StringNotEqualsOperator : StringOperator, INegateOperator { } - public class StringStartsWithOperator : StringOperator - { - } + public class StringStartsWithOperator : StringOperator { } - public class StringNotStartsWithOperator : StringOperator, INegateOperator - { - } + public class StringNotStartsWithOperator : StringOperator, INegateOperator { } - public class StringEndsWithOperator : StringOperator - { - } + public class StringEndsWithOperator : StringOperator { } - public class StringNotEndsWithOperator : StringOperator, INegateOperator - { - } + public class StringNotEndsWithOperator : StringOperator, INegateOperator { } - public class StringContainsOperator : StringOperator - { - } + public class StringContainsOperator : StringOperator { } - public class StringNotContainsOperator : StringOperator, INegateOperator - { - } + public class StringNotContainsOperator : StringOperator, INegateOperator { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/AllConditionEvaluator.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/AllConditionEvaluator.cs index 9a6ab5e334d..e26d65f8b0f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/AllConditionEvaluator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/AllConditionEvaluator.cs @@ -12,7 +12,7 @@ public AllConditionEvaluator(IConditionResolver conditionResolver) _conditionResolver = conditionResolver; } - public async override ValueTask EvaluateAsync(AllConditionGroup condition) + public override async ValueTask EvaluateAsync(AllConditionGroup condition) { foreach (var childCondition in condition.Conditions) { diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/AnyConditionEvaluator.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/AnyConditionEvaluator.cs index 2208270a29e..239aef0113d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/AnyConditionEvaluator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/AnyConditionEvaluator.cs @@ -12,7 +12,7 @@ public AnyConditionEvaluator(IConditionResolver conditionResolver) _conditionResolver = conditionResolver; } - public async override ValueTask EvaluateAsync(AnyConditionGroup condition) + public override async ValueTask EvaluateAsync(AnyConditionGroup condition) { foreach (var childCondition in condition.Conditions) { diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/BooleanConditionEvaluator.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/BooleanConditionEvaluator.cs index 6070a993a78..8f05321629e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/BooleanConditionEvaluator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/BooleanConditionEvaluator.cs @@ -5,7 +5,6 @@ namespace OrchardCore.Rules.Services { public class BooleanConditionEvaluator : ConditionEvaluator { - public override ValueTask EvaluateAsync(BooleanCondition condition) - => condition.Value ? True : False; + public override ValueTask EvaluateAsync(BooleanCondition condition) => condition.Value ? True : False; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/ConditionOperatorConfigureOptions.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/ConditionOperatorConfigureOptions.cs index 5e6530f3e28..18b78040508 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/ConditionOperatorConfigureOptions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/ConditionOperatorConfigureOptions.cs @@ -8,56 +8,57 @@ public class ConditionOperatorConfigureOptions : IConfigureOptions( - (S) => S["Equals"], - new StringEqualsOperatorComparer(), - typeof(StringEqualsOperator), - new ConditionOperatorFactory() - ), - new ConditionOperatorOption( - (S) => S["Does not equal"], - new StringNotEqualsOperatorComparer(), - typeof(StringNotEqualsOperator), - new ConditionOperatorFactory() - ), - new ConditionOperatorOption( - (S) => S["Starts with"], - new StringStartsWithOperatorComparer(), - typeof(StringStartsWithOperator), - new ConditionOperatorFactory() - ), - new ConditionOperatorOption( - (S) => S["Does not start with"], - new StringNotStartsWithOperatorComparer(), - typeof(StringNotStartsWithOperator), - new ConditionOperatorFactory() - ), - new ConditionOperatorOption( - (S) => S["Ends with"], - new StringEndsWithOperatorComparer(), - typeof(StringEndsWithOperator), - new ConditionOperatorFactory() - ), - new ConditionOperatorOption( - (S) => S["Does not end with"], - new StringNotEndsWithOperatorComparer(), - typeof(StringNotEndsWithOperator), - new ConditionOperatorFactory() - ), - new ConditionOperatorOption( - (S) => S["Contains"], - new StringContainsOperatorComparer(), - typeof(StringContainsOperator), - new ConditionOperatorFactory() - ), - new ConditionOperatorOption( - (S) => S["Does not contain"], - new StringNotContainsOperatorComparer(), - typeof(StringNotContainsOperator), - new ConditionOperatorFactory() - ) - ]); + [ + new ConditionOperatorOption( + (S) => S["Equals"], + new StringEqualsOperatorComparer(), + typeof(StringEqualsOperator), + new ConditionOperatorFactory() + ), + new ConditionOperatorOption( + (S) => S["Does not equal"], + new StringNotEqualsOperatorComparer(), + typeof(StringNotEqualsOperator), + new ConditionOperatorFactory() + ), + new ConditionOperatorOption( + (S) => S["Starts with"], + new StringStartsWithOperatorComparer(), + typeof(StringStartsWithOperator), + new ConditionOperatorFactory() + ), + new ConditionOperatorOption( + (S) => S["Does not start with"], + new StringNotStartsWithOperatorComparer(), + typeof(StringNotStartsWithOperator), + new ConditionOperatorFactory() + ), + new ConditionOperatorOption( + (S) => S["Ends with"], + new StringEndsWithOperatorComparer(), + typeof(StringEndsWithOperator), + new ConditionOperatorFactory() + ), + new ConditionOperatorOption( + (S) => S["Does not end with"], + new StringNotEndsWithOperatorComparer(), + typeof(StringNotEndsWithOperator), + new ConditionOperatorFactory() + ), + new ConditionOperatorOption( + (S) => S["Contains"], + new StringContainsOperatorComparer(), + typeof(StringContainsOperator), + new ConditionOperatorFactory() + ), + new ConditionOperatorOption( + (S) => S["Does not contain"], + new StringNotContainsOperatorComparer(), + typeof(StringNotContainsOperator), + new ConditionOperatorFactory() + ) + ] + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/CultureConditionEvaluator.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/CultureConditionEvaluator.cs index 374ad81a726..d4f41ce9db0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/CultureConditionEvaluator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/CultureConditionEvaluator.cs @@ -19,8 +19,9 @@ public override ValueTask EvaluateAsync(CultureCondition condition) var operatorComparer = _operatorResolver.GetOperatorComparer(condition.Operation); - var result = operatorComparer.Compare(condition.Operation, currentCulture.Name, condition.Value) || - operatorComparer.Compare(condition.Operation, currentCulture.Parent.Name, condition.Value); + var result = + operatorComparer.Compare(condition.Operation, currentCulture.Name, condition.Value) + || operatorComparer.Compare(condition.Operation, currentCulture.Parent.Name, condition.Value); return result ? True : False; } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/IsAnonymousConditionEvaluator.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/IsAnonymousConditionEvaluator.cs index 8d2234f0c15..f1509d8a796 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/IsAnonymousConditionEvaluator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/IsAnonymousConditionEvaluator.cs @@ -13,7 +13,6 @@ public IsAnonymousConditionEvaluator(IHttpContextAccessor httpContextAccessor) _httpContextAccessor = httpContextAccessor; } - public override ValueTask EvaluateAsync(IsAnonymousCondition condition) - => _httpContextAccessor.HttpContext.User?.Identity.IsAuthenticated != true ? True : False; + public override ValueTask EvaluateAsync(IsAnonymousCondition condition) => _httpContextAccessor.HttpContext.User?.Identity.IsAuthenticated != true ? True : False; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/IsAuthenticatedConditionEvaluator.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/IsAuthenticatedConditionEvaluator.cs index d0b147ac393..34ce70f6c7a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/IsAuthenticatedConditionEvaluator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/IsAuthenticatedConditionEvaluator.cs @@ -13,7 +13,6 @@ public IsAuthenticatedConditionEvaluator(IHttpContextAccessor httpContextAccesso _httpContextAccessor = httpContextAccessor; } - public override ValueTask EvaluateAsync(IsAuthenticatedCondition condition) - => _httpContextAccessor.HttpContext.User?.Identity.IsAuthenticated == true ? True : False; + public override ValueTask EvaluateAsync(IsAuthenticatedCondition condition) => _httpContextAccessor.HttpContext.User?.Identity.IsAuthenticated == true ? True : False; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/JavascriptConditionEvaluator.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/JavascriptConditionEvaluator.cs index 44454b42398..df87938b6d5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/JavascriptConditionEvaluator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/JavascriptConditionEvaluator.cs @@ -15,7 +15,6 @@ public class JavascriptConditionEvaluator : ConditionEvaluator private readonly IdentityOptions _options; private readonly IConditionOperatorResolver _operatorResolver; - public RoleConditionEvaluator( - IHttpContextAccessor httpContextAccessor, - IOptions options, - IConditionOperatorResolver operatorResolver) + public RoleConditionEvaluator(IHttpContextAccessor httpContextAccessor, IOptions options, IConditionOperatorResolver operatorResolver) { _httpContextAccessor = httpContextAccessor; _options = options.Value; @@ -33,15 +30,22 @@ public override ValueTask EvaluateAsync(RoleCondition condition) // Claim all if the operator is negative if (condition.Operation is INegateOperator) { - return (_httpContextAccessor.HttpContext.User?.Claims.Where(c => c.Type == roleClaimType).All(claim => - operatorComparer.Compare(condition.Operation, claim.Value, condition.Value)) - ).GetValueOrDefault() ? True : False; + return ( + _httpContextAccessor + .HttpContext.User?.Claims.Where(c => c.Type == roleClaimType) + .All(claim => operatorComparer.Compare(condition.Operation, claim.Value, condition.Value)) + ).GetValueOrDefault() + ? True + : False; } - return (_httpContextAccessor.HttpContext.User?.Claims.Any(claim => - claim.Type == roleClaimType && - operatorComparer.Compare(condition.Operation, claim.Value, condition.Value)) - ).GetValueOrDefault() ? True : False; + return ( + _httpContextAccessor.HttpContext.User?.Claims.Any(claim => + claim.Type == roleClaimType && operatorComparer.Compare(condition.Operation, claim.Value, condition.Value) + ) + ).GetValueOrDefault() + ? True + : False; } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/RuleMigrator.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/RuleMigrator.cs index 6421884fb12..fc302d58405 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/RuleMigrator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/RuleMigrator.cs @@ -20,7 +20,7 @@ public void Migrate(string existingRule, Rule rule) var factories = _factories.ToDictionary(x => x.Name); // Migrates well-known rules to well-known conditions. - // A javascript condition is automatically created for less well-known rules. + // A javascript condition is automatically created for less well-known rules. switch (existingRule) { case "true": diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/StringOperatorComparer.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/StringOperatorComparer.cs index f2990d374e0..95dafe6310d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/StringOperatorComparer.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/StringOperatorComparer.cs @@ -5,65 +5,49 @@ namespace OrchardCore.Rules.Services { public class StringEqualsOperatorComparer : OperatorComparer { - public override bool Compare(StringOperator conditionOperator, string a, string b) - => conditionOperator.CaseSensitive ? - string.Equals(a, b) : - string.Equals(a, b, StringComparison.OrdinalIgnoreCase); + public override bool Compare(StringOperator conditionOperator, string a, string b) => + conditionOperator.CaseSensitive ? string.Equals(a, b) : string.Equals(a, b, StringComparison.OrdinalIgnoreCase); } public class StringNotEqualsOperatorComparer : OperatorComparer { - public override bool Compare(StringOperator conditionOperator, string a, string b) - => conditionOperator.CaseSensitive ? - !string.Equals(a, b) : - !string.Equals(a, b, StringComparison.OrdinalIgnoreCase); + public override bool Compare(StringOperator conditionOperator, string a, string b) => + conditionOperator.CaseSensitive ? !string.Equals(a, b) : !string.Equals(a, b, StringComparison.OrdinalIgnoreCase); } public class StringStartsWithOperatorComparer : OperatorComparer { - public override bool Compare(StringOperator conditionOperator, string a, string b) - => conditionOperator.CaseSensitive ? - a.StartsWith(b) : - a.StartsWith(b, StringComparison.OrdinalIgnoreCase); + public override bool Compare(StringOperator conditionOperator, string a, string b) => + conditionOperator.CaseSensitive ? a.StartsWith(b) : a.StartsWith(b, StringComparison.OrdinalIgnoreCase); } public class StringNotStartsWithOperatorComparer : OperatorComparer { - public override bool Compare(StringOperator conditionOperator, string a, string b) - => conditionOperator.CaseSensitive ? - !a.StartsWith(b) : - !a.StartsWith(b, StringComparison.OrdinalIgnoreCase); + public override bool Compare(StringOperator conditionOperator, string a, string b) => + conditionOperator.CaseSensitive ? !a.StartsWith(b) : !a.StartsWith(b, StringComparison.OrdinalIgnoreCase); } public class StringEndsWithOperatorComparer : OperatorComparer { - public override bool Compare(StringOperator conditionOperator, string a, string b) - => conditionOperator.CaseSensitive ? - a.EndsWith(b) : - a.EndsWith(b, StringComparison.OrdinalIgnoreCase); + public override bool Compare(StringOperator conditionOperator, string a, string b) => + conditionOperator.CaseSensitive ? a.EndsWith(b) : a.EndsWith(b, StringComparison.OrdinalIgnoreCase); } public class StringNotEndsWithOperatorComparer : OperatorComparer { - public override bool Compare(StringOperator conditionOperator, string a, string b) - => conditionOperator.CaseSensitive ? - !a.EndsWith(b) : - !a.EndsWith(b, StringComparison.OrdinalIgnoreCase); + public override bool Compare(StringOperator conditionOperator, string a, string b) => + conditionOperator.CaseSensitive ? !a.EndsWith(b) : !a.EndsWith(b, StringComparison.OrdinalIgnoreCase); } public class StringContainsOperatorComparer : OperatorComparer { - public override bool Compare(StringOperator conditionOperator, string a, string b) - => conditionOperator.CaseSensitive ? - a.Contains(b) : - a.Contains(b, StringComparison.OrdinalIgnoreCase); + public override bool Compare(StringOperator conditionOperator, string a, string b) => + conditionOperator.CaseSensitive ? a.Contains(b) : a.Contains(b, StringComparison.OrdinalIgnoreCase); } public class StringNotContainsOperatorComparer : OperatorComparer { - public override bool Compare(StringOperator conditionOperator, string a, string b) - => conditionOperator.CaseSensitive ? - !a.Contains(b) : - !a.Contains(b, StringComparison.OrdinalIgnoreCase); + public override bool Compare(StringOperator conditionOperator, string a, string b) => + conditionOperator.CaseSensitive ? !a.Contains(b) : !a.Contains(b, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Startup.cs index 525cbef4e62..6862a78caef 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Startup.cs @@ -47,9 +47,7 @@ public override void ConfigureServices(IServiceCollection services) .AddCondition>(); // Url condition. - services - .AddScoped, UrlConditionDisplayDriver>() - .AddCondition>(); + services.AddScoped, UrlConditionDisplayDriver>().AddCondition>(); // Culture condition. services @@ -57,9 +55,7 @@ public override void ConfigureServices(IServiceCollection services) .AddCondition>(); // Role condition. - services - .AddScoped, RoleConditionDisplayDriver>() - .AddCondition>(); + services.AddScoped, RoleConditionDisplayDriver>().AddCondition>(); // Javascript condition. services diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/ViewComponents/SelectStringOperationViewComponent.cs b/src/OrchardCore.Modules/OrchardCore.Rules/ViewComponents/SelectStringOperationViewComponent.cs index dce865427a9..07b301eda6f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/ViewComponents/SelectStringOperationViewComponent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/ViewComponents/SelectStringOperationViewComponent.cs @@ -24,18 +24,14 @@ public IViewComponentResult Invoke(string selectedOperation, string htmlName) var stringOperators = _options.Operators.Where(x => typeof(StringOperator).IsAssignableFrom(x.Operator)); var items = stringOperators - .Select(x => - new SelectListItem( - x.DisplayText(_serviceProvider), - x.Operator.Name, - string.Equals(x.Factory.Name, selectedOperation, StringComparison.OrdinalIgnoreCase)) - ).ToList(); + .Select(x => new SelectListItem( + x.DisplayText(_serviceProvider), + x.Operator.Name, + string.Equals(x.Factory.Name, selectedOperation, StringComparison.OrdinalIgnoreCase) + )) + .ToList(); - var model = new SelectStringOperationViewModel - { - HtmlName = htmlName, - Items = items - }; + var model = new SelectStringOperationViewModel { HtmlName = htmlName, Items = items }; return View(model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Scripting/Providers/LogProvider.cs b/src/OrchardCore.Modules/OrchardCore.Scripting/Providers/LogProvider.cs index b95873d35c8..b8a1f838593 100644 --- a/src/OrchardCore.Modules/OrchardCore.Scripting/Providers/LogProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Scripting/Providers/LogProvider.cs @@ -13,42 +13,45 @@ public LogProvider(ILogger logger) _log = new GlobalMethod { Name = "log", - Method = serviceProvider => (Action)((level, text, param) => - { - try - { - if (!Enum.TryParse(level, true, out var logLevel)) - { - logLevel = LogLevel.Information; - } - if (param == null) + Method = serviceProvider => + (Action)( + (level, text, param) => { + try + { + if (!Enum.TryParse(level, true, out var logLevel)) + { + logLevel = LogLevel.Information; + } + if (param == null) + { #pragma warning disable CA2254 // Template should be a static expression - logger.Log(logLevel, text); + logger.Log(logLevel, text); #pragma warning restore CA2254 // Template should be a static expression - } - else - { - object[] args; - if (param is not Array) - { - args = [param]; - } - else - { - args = (object[])param; - } + } + else + { + object[] args; + if (param is not Array) + { + args = [param]; + } + else + { + args = (object[])param; + } #pragma warning disable CA2254 // Template should be a static expression - logger.Log(logLevel, text, args); + logger.Log(logLevel, text, args); #pragma warning restore CA2254 // Template should be a static expression + } + } + catch (Exception ex) + { + logger.Log(LogLevel.Error, ex, "Error logging text template {text} with param {param} from Scripting Engine.", text, param); + } } - } - catch (Exception ex) - { - logger.Log(LogLevel.Error, ex, "Error logging text template {text} with param {param} from Scripting Engine.", text, param); - } - }), + ), }; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/AdminMenu.cs index 6dc478b9795..438b119311a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/AdminMenu.cs @@ -8,9 +8,7 @@ namespace OrchardCore.Search.AzureAI; -public class AdminMenu( - IStringLocalizer stringLocalizer, - IOptions azureAISearchSettings) : INavigationProvider +public class AdminMenu(IStringLocalizer stringLocalizer, IOptions azureAISearchSettings) : INavigationProvider { protected readonly IStringLocalizer S = stringLocalizer; private readonly AzureAISearchDefaultOptions _azureAISearchSettings = azureAISearchSettings.Value; @@ -22,33 +20,50 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Search"], NavigationConstants.AdminMenuSearchPosition, search => search - .AddClass("azure-ai-service") - .Id("azureaiservice") - .Add(S["Indexing"], S["Indexing"].PrefixPosition(), indexing => indexing - .Add(S["Azure AI Indices"], S["Azure AI Indices"].PrefixPosition(), indexes => indexes - .Action("Index", "Admin", "OrchardCore.Search.AzureAI") - .Permission(AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes) - .LocalNav() + builder.Add( + S["Search"], + NavigationConstants.AdminMenuSearchPosition, + search => + search + .AddClass("azure-ai-service") + .Id("azureaiservice") + .Add( + S["Indexing"], + S["Indexing"].PrefixPosition(), + indexing => + indexing.Add( + S["Azure AI Indices"], + S["Azure AI Indices"].PrefixPosition(), + indexes => + indexes + .Action("Index", "Admin", "OrchardCore.Search.AzureAI") + .Permission(AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes) + .LocalNav() + ) ) - ) - ); + ); if (!_azureAISearchSettings.DisableUIConfiguration) { - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Azure AI Search"], S["Azure AI Search"].PrefixPosition(), azureAISearch => azureAISearch - .AddClass("azure-ai-search") - .Id("azureaisearch") - .Action("Index", "Admin", new { area = "OrchardCore.Settings", groupId = AzureAISearchDefaultSettingsDisplayDriver.GroupId }) - .Permission(AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Azure AI Search"], + S["Azure AI Search"].PrefixPosition(), + azureAISearch => + azureAISearch + .AddClass("azure-ai-search") + .Id("azureaisearch") + .Action("Index", "Admin", new { area = "OrchardCore.Settings", groupId = AzureAISearchDefaultSettingsDisplayDriver.GroupId }) + .Permission(AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes) + .LocalNav() + ) ) - ); + ); } return Task.CompletedTask; diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Controllers/AdminController.cs index f32a1c1db43..dc7f905211e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Controllers/AdminController.cs @@ -61,7 +61,7 @@ public AdminController( ILogger logger, IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer - ) + ) { _siteService = siteService; _authorizationService = authorizationService; @@ -90,9 +90,7 @@ public async Task Index(AzureAIIndexOptions options, PagerParamet return NotConfigured(); } - var indexes = (await _indexSettingsService.GetSettingsAsync()) - .Select(i => new IndexViewModel { Name = i.IndexName }) - .ToList(); + var indexes = (await _indexSettingsService.GetSettingsAsync()).Select(i => new IndexViewModel { Name = i.IndexName }).ToList(); var totalIndexes = indexes.Count; @@ -104,9 +102,7 @@ public async Task Index(AzureAIIndexOptions options, PagerParamet var siteSettings = await _siteService.GetSiteSettingsAsync(); var pager = new Pager(pagerParameters, siteSettings.PageSize); - indexes = indexes - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize).ToList(); + indexes = indexes.Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -123,23 +119,14 @@ public async Task Index(AzureAIIndexOptions options, PagerParamet Pager = await _shapeFactory.PagerAsync(pager, totalIndexes, routeData) }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(AzureAISearchIndexBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(AzureAISearchIndexBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(AdminIndexViewModel model) - => RedirectToAction(nameof(Index), - new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); - + public ActionResult IndexFilterPOST(AdminIndexViewModel model) => RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.BulkAction")] @@ -193,10 +180,7 @@ public async Task Create() return NotConfigured(); } - var model = new AzureAISettingsViewModel - { - AnalyzerName = AzureAISearchDefaultOptions.DefaultAnalyzer - }; + var model = new AzureAISettingsViewModel { AnalyzerName = AzureAISearchDefaultOptions.DefaultAnalyzer }; PopulateMenuOptions(model); @@ -495,22 +479,22 @@ public async Task Reset(string indexName) return RedirectToAction(nameof(Index)); } - private ViewResult NotConfigured() - => View("NotConfigured"); + private ViewResult NotConfigured() => View("NotConfigured"); - private static Task AsyncContentItemsAsync(string indexName) - => HttpBackgroundJob.ExecuteAfterEndOfRequestAsync("sync-content-items-azure-ai-" + indexName, async (scope) => - { - var indexingService = scope.ServiceProvider.GetRequiredService(); - await indexingService.ProcessContentItemsAsync(indexName); - }); + private static Task AsyncContentItemsAsync(string indexName) => + HttpBackgroundJob.ExecuteAfterEndOfRequestAsync( + "sync-content-items-azure-ai-" + indexName, + async (scope) => + { + var indexingService = scope.ServiceProvider.GetRequiredService(); + await indexingService.ProcessContentItemsAsync(indexName); + } + ); private void PopulateMenuOptions(AzureAISettingsViewModel model) { - model.Cultures = CultureInfo.GetCultures(CultureTypes.AllCultures) - .Select(x => new SelectListItem { Text = $"{x.Name} ({x.DisplayName})", Value = x.Name }); + model.Cultures = CultureInfo.GetCultures(CultureTypes.AllCultures).Select(x => new SelectListItem { Text = $"{x.Name} ({x.DisplayName})", Value = x.Name }); - model.Analyzers = _azureAIOptions.Analyzers - .Select(x => new SelectListItem { Text = x, Value = x }); + model.Analyzers = _azureAIOptions.Analyzers.Select(x => new SelectListItem { Text = x, Value = x }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchDefaultSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchDefaultSettingsDisplayDriver.cs index 3f669eb0339..e23e27022db 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchDefaultSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchDefaultSettingsDisplayDriver.cs @@ -44,7 +44,7 @@ public AzureAISearchDefaultSettingsDisplayDriver( IShellHost shellHost, IDataProtectionProvider dataProtectionProvider, IStringLocalizer stringLocalizer - ) + ) { _indexSettingsService = indexSettingsService; _httpContextAccessor = httpContextAccessor; @@ -63,24 +63,28 @@ public override IDisplayResult Edit(AzureAISearchDefaultSettings settings) return null; } - return Initialize("AzureAISearchDefaultSettings_Edit", model => - { - model.AuthenticationTypes = new[] - { - new SelectListItem(S["Default"], nameof(AzureAIAuthenticationType.Default)), - new SelectListItem(S["Managed Identity"], nameof(AzureAIAuthenticationType.ManagedIdentity)), - new SelectListItem(S["API Key"], nameof(AzureAIAuthenticationType.ApiKey)), - }; - - model.ConfigurationsAreOptional = _searchOptions.FileConfigurationExists(); - model.AuthenticationType = settings.AuthenticationType; - model.UseCustomConfiguration = settings.UseCustomConfiguration; - model.Endpoint = settings.Endpoint; - model.IdentityClientId = settings.IdentityClientId; - model.ApiKeyExists = !string.IsNullOrEmpty(settings.ApiKey); - }).Location("Content") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes)) - .OnGroup(GroupId); + return Initialize( + "AzureAISearchDefaultSettings_Edit", + model => + { + model.AuthenticationTypes = new[] + { + new SelectListItem(S["Default"], nameof(AzureAIAuthenticationType.Default)), + new SelectListItem(S["Managed Identity"], nameof(AzureAIAuthenticationType.ManagedIdentity)), + new SelectListItem(S["API Key"], nameof(AzureAIAuthenticationType.ApiKey)), + }; + + model.ConfigurationsAreOptional = _searchOptions.FileConfigurationExists(); + model.AuthenticationType = settings.AuthenticationType; + model.UseCustomConfiguration = settings.UseCustomConfiguration; + model.Endpoint = settings.Endpoint; + model.IdentityClientId = settings.IdentityClientId; + model.ApiKeyExists = !string.IsNullOrEmpty(settings.ApiKey); + } + ) + .Location("Content") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes)) + .OnGroup(GroupId); } public override async Task UpdateAsync(AzureAISearchDefaultSettings settings, BuildEditorContext context) @@ -140,12 +144,16 @@ public override async Task UpdateAsync(AzureAISearchDefaultSetti settings.UseCustomConfiguration = model.UseCustomConfiguration; - if (context.Updater.ModelState.IsValid && - (_searchOptions.Credential?.Key != model.ApiKey - || _searchOptions.Endpoint != settings.Endpoint - || _searchOptions.AuthenticationType != settings.AuthenticationType - || _searchOptions.IdentityClientId != settings.IdentityClientId - || useCustomConfigurationChanged)) + if ( + context.Updater.ModelState.IsValid + && ( + _searchOptions.Credential?.Key != model.ApiKey + || _searchOptions.Endpoint != settings.Endpoint + || _searchOptions.AuthenticationType != settings.AuthenticationType + || _searchOptions.IdentityClientId != settings.IdentityClientId + || useCustomConfigurationChanged + ) + ) { await _shellHost.ReleaseShellContextAsync(_shellSettings); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexDeploymentStepDriver.cs index 66657d250f1..01ebf81b955 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexDeploymentStepDriver.cs @@ -19,21 +19,23 @@ public AzureAISearchIndexDeploymentStepDriver(AzureAISearchIndexSettingsService _indexSettingsService = indexSettingsService; } - public override IDisplayResult Display(AzureAISearchIndexDeploymentStep step) - => Combine( + public override IDisplayResult Display(AzureAISearchIndexDeploymentStep step) => + Combine( View("AzureAISearchIndexDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), View("AzureAISearchIndexDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") ); - - public override IDisplayResult Edit(AzureAISearchIndexDeploymentStep step) - => Initialize("AzureAISearchIndexDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.IndexNames = step.IndexNames; - model.AllIndexNames = (await _indexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }).Location("Content"); - + public override IDisplayResult Edit(AzureAISearchIndexDeploymentStep step) => + Initialize( + "AzureAISearchIndexDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.IndexNames = step.IndexNames; + model.AllIndexNames = (await _indexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) + .Location("Content"); public override async Task UpdateAsync(AzureAISearchIndexDeploymentStep step, IUpdateModel updater) { diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexRebuildDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexRebuildDeploymentStepDriver.cs index 055bef504d6..9bf020e04e8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexRebuildDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexRebuildDeploymentStepDriver.cs @@ -15,19 +15,23 @@ public class AzureAISearchIndexRebuildDeploymentStepDriver(AzureAISearchIndexSet { private readonly AzureAISearchIndexSettingsService _indexSettingsService = indexSettingsService; - public override IDisplayResult Display(AzureAISearchIndexRebuildDeploymentStep step) - => Combine( + public override IDisplayResult Display(AzureAISearchIndexRebuildDeploymentStep step) => + Combine( View("AzureAISearchIndexRebuildDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), View("AzureAISearchIndexRebuildDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") ); - public override IDisplayResult Edit(AzureAISearchIndexRebuildDeploymentStep step) - => Initialize("AzureAISearchIndexRebuildDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.IndexNames = step.Indices; - model.AllIndexNames = (await _indexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }).Location("Content"); + public override IDisplayResult Edit(AzureAISearchIndexRebuildDeploymentStep step) => + Initialize( + "AzureAISearchIndexRebuildDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.IndexNames = step.Indices; + model.AllIndexNames = (await _indexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) + .Location("Content"); public override async Task UpdateAsync(AzureAISearchIndexRebuildDeploymentStep step, IUpdateModel updater) { diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexResetDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexResetDeploymentStepDriver.cs index c7163acb0d9..4278a73ba1e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexResetDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchIndexResetDeploymentStepDriver.cs @@ -15,19 +15,23 @@ public class AzureAISearchIndexResetDeploymentStepDriver(AzureAISearchIndexSetti { private readonly AzureAISearchIndexSettingsService _indexSettingsService = indexSettingsService; - public override IDisplayResult Display(AzureAISearchIndexResetDeploymentStep step) - => Combine( + public override IDisplayResult Display(AzureAISearchIndexResetDeploymentStep step) => + Combine( View("AzureAISearchIndexResetDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), View("AzureAISearchIndexResetDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") ); - public override IDisplayResult Edit(AzureAISearchIndexResetDeploymentStep step) - => Initialize("AzureAISearchIndexResetDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.IndexNames = step.Indices; - model.AllIndexNames = (await _indexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }).Location("Content"); + public override IDisplayResult Edit(AzureAISearchIndexResetDeploymentStep step) => + Initialize( + "AzureAISearchIndexResetDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.IndexNames = step.Indices; + model.AllIndexNames = (await _indexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) + .Location("Content"); public override async Task UpdateAsync(AzureAISearchIndexResetDeploymentStep step, IUpdateModel updater) { diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchSettingsDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchSettingsDeploymentStepDriver.cs index 9b7f62369bc..d0ff014363b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchSettingsDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchSettingsDeploymentStepDriver.cs @@ -7,12 +7,11 @@ namespace OrchardCore.Search.AzureAI.Drivers; public class AzureAISearchSettingsDeploymentStepDriver : DisplayDriver { - public override IDisplayResult Display(AzureAISearchSettingsDeploymentStep step) - => Combine( + public override IDisplayResult Display(AzureAISearchSettingsDeploymentStep step) => + Combine( View("AzureAISearchSettingsDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), View("AzureAISearchSettingsDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") ); - public override IDisplayResult Edit(AzureAISearchSettingsDeploymentStep step) - => View("AzureAISearchSettingsDeploymentStep_Fields_Edit", step).Location("Content"); + public override IDisplayResult Edit(AzureAISearchSettingsDeploymentStep step) => View("AzureAISearchSettingsDeploymentStep_Fields_Edit", step).Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchSettingsDisplayDriver.cs index db223d97686..dcbe3451782 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/AzureAISearchSettingsDisplayDriver.cs @@ -36,7 +36,7 @@ public AzureAISearchSettingsDisplayDriver( IShellHost shellHost, ShellSettings shellSettings, IStringLocalizer stringLocalizer - ) + ) { _indexSettingsService = indexSettingsService; _httpContextAccessor = httpContextAccessor; @@ -46,17 +46,19 @@ IStringLocalizer stringLocalizer S = stringLocalizer; } - public override IDisplayResult Edit(AzureAISearchSettings settings) - => Initialize("AzureAISearchSettings_Edit", async model => - { - model.SearchIndex = settings.SearchIndex; - model.SearchFields = string.Join(", ", settings.DefaultSearchFields ?? []); - model.SearchIndexes = (await _indexSettingsService.GetSettingsAsync()) - .Select(x => new SelectListItem(x.IndexName, x.IndexName)) - .ToList(); - }).Location("Content:2#Azure AI Search;5") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes)) - .OnGroup(SearchConstants.SearchSettingsGroupId); + public override IDisplayResult Edit(AzureAISearchSettings settings) => + Initialize( + "AzureAISearchSettings_Edit", + async model => + { + model.SearchIndex = settings.SearchIndex; + model.SearchFields = string.Join(", ", settings.DefaultSearchFields ?? []); + model.SearchIndexes = (await _indexSettingsService.GetSettingsAsync()).Select(x => new SelectListItem(x.IndexName, x.IndexName)).ToList(); + } + ) + .Location("Content:2#Azure AI Search;5") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes)) + .OnGroup(SearchConstants.SearchSettingsGroupId); public override async Task UpdateAsync(AzureAISearchSettings section, BuildEditorContext context) { diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/ContentPartFieldIndexSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/ContentPartFieldIndexSettingsDisplayDriver.cs index 789c2773c1f..33896a403e8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/ContentPartFieldIndexSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/ContentPartFieldIndexSettingsDisplayDriver.cs @@ -22,7 +22,10 @@ public override async Task EditAsync(ContentPartFieldDefinition return null; } - return Initialize("AzureAISearchContentIndexSettings_Edit", model => contentPartFieldDefinition.GetSettings()) + return Initialize( + "AzureAISearchContentIndexSettings_Edit", + model => contentPartFieldDefinition.GetSettings() + ) .Location("Content:10"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/ContentTypePartIndexSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/ContentTypePartIndexSettingsDisplayDriver.cs index 774a97df642..72697427b46 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/ContentTypePartIndexSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Drivers/ContentTypePartIndexSettingsDisplayDriver.cs @@ -22,7 +22,10 @@ public override async Task EditAsync(ContentTypePartDefinition c return null; } - return Initialize("AzureAISearchContentIndexSettings_Edit", model => contentTypePartDefinition.GetSettings()) + return Initialize( + "AzureAISearchContentIndexSettings_Edit", + model => contentTypePartDefinition.GetSettings() + ) .Location("Content:10"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Manifest.cs index d3b68441882..455ed976c14 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Manifest.cs @@ -11,9 +11,6 @@ Id = "OrchardCore.Search.AzureAI", Name = "Azure AI Search", Description = "Provides Azure AI Search services for managing indexes and facilitating search scenarios within indexes.", - Dependencies = - [ - "OrchardCore.Indexing", - ], + Dependencies = ["OrchardCore.Indexing",], Category = "Search" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Startup.cs index e0ae4e6b0fa..fcbb16816d4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Startup.cs @@ -16,8 +16,7 @@ namespace OrchardCore.Search.AzureAI; -public class Startup(ILogger logger, IShellConfiguration shellConfiguration) - : StartupBase +public class Startup(ILogger logger, IShellConfiguration shellConfiguration) : StartupBase { private readonly ILogger _logger = logger; private readonly IShellConfiguration _shellConfiguration = shellConfiguration; diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/AdminMenu.cs index c626b4f60f5..1078a7c913d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/AdminMenu.cs @@ -15,24 +15,34 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Search"], NavigationConstants.AdminMenuSearchPosition, search => search - .AddClass("elasticsearch").Id("Elasticsearch") - .Add(S["Indexing"], S["Indexing"].PrefixPosition(), import => import - .Add(S["Elasticsearch Indices"], S["Elasticsearch Indices"].PrefixPosition(), indexes => indexes - .Action("Index", "Admin", "OrchardCore.Search.Elasticsearch") - .Permission(Permissions.ManageElasticIndexes) - .LocalNav() + builder.Add( + S["Search"], + NavigationConstants.AdminMenuSearchPosition, + search => + search + .AddClass("elasticsearch") + .Id("Elasticsearch") + .Add( + S["Indexing"], + S["Indexing"].PrefixPosition(), + import => + import.Add( + S["Elasticsearch Indices"], + S["Elasticsearch Indices"].PrefixPosition(), + indexes => indexes.Action("Index", "Admin", "OrchardCore.Search.Elasticsearch").Permission(Permissions.ManageElasticIndexes).LocalNav() + ) ) - ) - .Add(S["Queries"], S["Queries"].PrefixPosition(), import => import - .Add(S["Run Elasticsearch Query"], S["Run Elasticsearch Query"].PrefixPosition(), queries => queries - .Action("Query", "Admin", "OrchardCore.Search.Elasticsearch") - .Permission(Permissions.ManageElasticIndexes) - .LocalNav() + .Add( + S["Queries"], + S["Queries"].PrefixPosition(), + import => + import.Add( + S["Run Elasticsearch Query"], + S["Run Elasticsearch Query"].PrefixPosition(), + queries => queries.Action("Query", "Admin", "OrchardCore.Search.Elasticsearch").Permission(Permissions.ManageElasticIndexes).LocalNav() + ) ) - ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs index 3f0022a270d..15729e8ca28 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs @@ -80,7 +80,8 @@ public AdminController( IShapeFactory shapeFactory, ILocalizationService localizationService, IStringLocalizer stringLocalizer, - IHtmlLocalizer htmlLocalizer) + IHtmlLocalizer htmlLocalizer + ) { _session = session; _siteService = siteService; @@ -115,9 +116,7 @@ public async Task Index(ContentOptions options, PagerParameters p return NotConfigured(); } - var indexes = (await _elasticIndexSettingsService.GetSettingsAsync()) - .Select(i => new IndexViewModel { Name = i.IndexName }) - .ToList(); + var indexes = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(i => new IndexViewModel { Name = i.IndexName }).ToList(); var totalIndexes = indexes.Count; var siteSettings = await _siteService.GetSiteSettingsAsync(); @@ -128,10 +127,7 @@ public async Task Index(ContentOptions options, PagerParameters p indexes = indexes.Where(q => q.Name.Contains(options.Search, StringComparison.OrdinalIgnoreCase)).ToList(); } - indexes = indexes - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize) - .ToList(); + indexes = indexes.Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -157,17 +153,12 @@ public async Task Index(ContentOptions options, PagerParameters p new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), ]; - return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public IActionResult IndexFilterPOST(AdminIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public IActionResult IndexFilterPOST(AdminIndexViewModel model) => RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Edit(string indexName = null) { @@ -440,11 +431,7 @@ public async Task Mappings(string indexName) { var mappings = await _elasticIndexManager.GetIndexMappings(indexName); var formattedJson = JNode.Parse(mappings).ToJsonString(System.Text.Json.JOptions.Indented); - return View(new MappingsViewModel - { - IndexName = _elasticIndexManager.GetFullIndexName(indexName), - Mappings = formattedJson - }); + return View(new MappingsViewModel { IndexName = _elasticIndexManager.GetFullIndexName(indexName), Mappings = formattedJson }); } public async Task SyncSettings() @@ -466,11 +453,13 @@ public async Task Query(string indexName, string query) return NotConfigured(); } - return await Query(new AdminQueryViewModel - { - IndexName = indexName, - DecodedQuery = string.IsNullOrWhiteSpace(query) ? string.Empty : System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(query)) - }); + return await Query( + new AdminQueryViewModel + { + IndexName = indexName, + DecodedQuery = string.IsNullOrWhiteSpace(query) ? string.Empty : System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(query)) + } + ); } [HttpPost] @@ -518,7 +507,11 @@ public async Task Query(AdminQueryViewModel model) stopwatch.Start(); var parameters = JConvert.DeserializeObject>(model.Parameters); - var tokenizedContent = await _liquidTemplateManager.RenderStringAsync(model.DecodedQuery, _javaScriptEncoder, parameters.Select(x => new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions.Value)))); + var tokenizedContent = await _liquidTemplateManager.RenderStringAsync( + model.DecodedQuery, + _javaScriptEncoder, + parameters.Select(x => new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions.Value))) + ); try { @@ -629,24 +622,21 @@ private async Task PopulateMenuOptionsAsync(ElasticIndexSettingsViewModel model) { var supportedCultures = await _localizationService.GetSupportedCulturesAsync(); - model.Cultures = supportedCultures.Select(c => new SelectListItem - { - Text = $"{c} ({CultureInfo.GetCultureInfo(c).DisplayName})", - Value = c - }); + model.Cultures = supportedCultures.Select(c => new SelectListItem { Text = $"{c} ({CultureInfo.GetCultureInfo(c).DisplayName})", Value = c }); - model.Analyzers = _elasticSearchOptions.Analyzers - .Select(x => new SelectListItem { Text = x.Key, Value = x.Key }); + model.Analyzers = _elasticSearchOptions.Analyzers.Select(x => new SelectListItem { Text = x.Key, Value = x.Key }); } - private ViewResult NotConfigured() - => View("NotConfigured"); + private ViewResult NotConfigured() => View("NotConfigured"); - private static Task ProcessContentItemsAsync(string indexName) - => HttpBackgroundJob.ExecuteAfterEndOfRequestAsync("sync-content-items-elasticsearch-" + indexName, async (scope) => - { - var indexingService = scope.ServiceProvider.GetRequiredService(); - await indexingService.ProcessContentItemsAsync(indexName); - }); + private static Task ProcessContentItemsAsync(string indexName) => + HttpBackgroundJob.ExecuteAfterEndOfRequestAsync( + "sync-content-items-elasticsearch-" + indexName, + async (scope) => + { + var indexingService = scope.ServiceProvider.GetRequiredService(); + await indexingService.ProcessContentItemsAsync(indexName); + } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/ApiController.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/ApiController.cs index 23f0d3d0982..66917a76783 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/ApiController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/ApiController.cs @@ -17,9 +17,7 @@ public class ApiController : Controller private readonly IAuthorizationService _authorizationService; private readonly ElasticQuerySource _elasticQuerySource; - public ApiController( - IAuthorizationService authorizationService, - ElasticQuerySource elasticQuerySource) + public ApiController(IAuthorizationService authorizationService, ElasticQuerySource elasticQuerySource) { _authorizationService = authorizationService; _elasticQuerySource = elasticQuerySource; @@ -90,9 +88,7 @@ public async Task DocumentsPost(ElasticApiQueryViewModel queryMod ReturnContentItems = returnContentItems }; - var queryParameters = queryModel.Parameters != null ? - JConvert.DeserializeObject>(queryModel.Parameters) - : []; + var queryParameters = queryModel.Parameters != null ? JConvert.DeserializeObject>(queryModel.Parameters) : []; var result = _elasticQuerySource.ExecuteQueryAsync(elasticQuery, queryParameters); return result; diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentPartFieldIndexSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentPartFieldIndexSettingsDisplayDriver.cs index 367bfd16664..cfc3ac813df 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentPartFieldIndexSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentPartFieldIndexSettingsDisplayDriver.cs @@ -28,10 +28,14 @@ public override async Task EditAsync(ContentPartFieldDefinition return null; } - return Initialize("ElasticContentIndexSettings_Edit", model => - { - model.ElasticContentIndexSettings = contentPartFieldDefinition.GetSettings(); - }).Location("Content:10"); + return Initialize( + "ElasticContentIndexSettings_Edit", + model => + { + model.ElasticContentIndexSettings = contentPartFieldDefinition.GetSettings(); + } + ) + .Location("Content:10"); } public override async Task UpdateAsync(ContentPartFieldDefinition contentPartFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentPickerFieldElasticEditorSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentPickerFieldElasticEditorSettingsDriver.cs index f8e99254417..6b0bdb8608b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentPickerFieldElasticEditorSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentPickerFieldElasticEditorSettingsDriver.cs @@ -20,14 +20,17 @@ public ContentPickerFieldElasticEditorSettingsDriver(ElasticIndexSettingsService public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("ContentPickerFieldElasticEditorSettings_Edit", async model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "ContentPickerFieldElasticEditorSettings_Edit", + async model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Index = settings.Index; + model.Index = settings.Index; - model.Indices = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }) + model.Indices = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) .Location("Editor"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentTypePartIndexSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentTypePartIndexSettingsDisplayDriver.cs index f9b07c864ef..85946c414f8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentTypePartIndexSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ContentTypePartIndexSettingsDisplayDriver.cs @@ -28,10 +28,14 @@ public override async Task EditAsync(ContentTypePartDefinition c return null; } - return Initialize("ElasticContentIndexSettings_Edit", model => - { - model.ElasticContentIndexSettings = contentTypePartDefinition.GetSettings(); - }).Location("Content:10"); + return Initialize( + "ElasticContentIndexSettings_Edit", + model => + { + model.ElasticContentIndexSettings = contentTypePartDefinition.GetSettings(); + } + ) + .Location("Content:10"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexDeploymentStepDriver.cs index 49d5d80737f..7994199d452 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexDeploymentStepDriver.cs @@ -20,31 +20,31 @@ public ElasticIndexDeploymentStepDriver(ElasticIndexSettingsService elasticIndex public override IDisplayResult Display(ElasticIndexDeploymentStep step) { - return - Combine( - View("ElasticIndexDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("ElasticIndexDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("ElasticIndexDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("ElasticIndexDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(ElasticIndexDeploymentStep step) { - return Initialize("ElasticIndexDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.IndexNames = step.IndexNames; - model.AllIndexNames = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }).Location("Content"); + return Initialize( + "ElasticIndexDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.IndexNames = step.IndexNames; + model.AllIndexNames = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(ElasticIndexDeploymentStep step, IUpdateModel updater) { step.IndexNames = []; - await updater.TryUpdateModelAsync(step, - Prefix, - x => x.IndexNames, - x => x.IncludeAll); + await updater.TryUpdateModelAsync(step, Prefix, x => x.IndexNames, x => x.IncludeAll); // don't have the selected option if include all if (step.IncludeAll) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexRebuildDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexRebuildDeploymentStepDriver.cs index 165ad9f7765..c373a940844 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexRebuildDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexRebuildDeploymentStepDriver.cs @@ -20,21 +20,24 @@ public ElasticIndexRebuildDeploymentStepDriver(ElasticIndexSettingsService elast public override IDisplayResult Display(ElasticIndexRebuildDeploymentStep step) { - return - Combine( - View("ElasticIndexRebuildDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("ElasticIndexRebuildDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("ElasticIndexRebuildDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("ElasticIndexRebuildDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(ElasticIndexRebuildDeploymentStep step) { - return Initialize("ElasticIndexRebuildDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.IndexNames = step.Indices; - model.AllIndexNames = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }).Location("Content"); + return Initialize( + "ElasticIndexRebuildDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.IndexNames = step.Indices; + model.AllIndexNames = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(ElasticIndexRebuildDeploymentStep rebuildIndexStep, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexResetDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexResetDeploymentStepDriver.cs index efd4b6f58f5..086dc964e39 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexResetDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticIndexResetDeploymentStepDriver.cs @@ -20,21 +20,24 @@ public ElasticIndexResetDeploymentStepDriver(ElasticIndexSettingsService elastic public override IDisplayResult Display(ElasticIndexResetDeploymentStep step) { - return - Combine( - View("ElasticIndexResetDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("ElasticIndexResetDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("ElasticIndexResetDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("ElasticIndexResetDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(ElasticIndexResetDeploymentStep step) { - return Initialize("ElasticIndexResetDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.IndexNames = step.Indices; - model.AllIndexNames = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }).Location("Content"); + return Initialize( + "ElasticIndexResetDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.IndexNames = step.Indices; + model.AllIndexNames = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(ElasticIndexResetDeploymentStep resetIndexStep, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticQueryDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticQueryDisplayDriver.cs index fed0a23e0d8..25d5693da80 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticQueryDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticQueryDisplayDriver.cs @@ -16,9 +16,7 @@ public class ElasticQueryDisplayDriver : DisplayDriver private readonly ElasticIndexSettingsService _elasticIndexSettingsService; protected readonly IStringLocalizer S; - public ElasticQueryDisplayDriver( - IStringLocalizer stringLocalizer, - ElasticIndexSettingsService elasticIndexSettingsService) + public ElasticQueryDisplayDriver(IStringLocalizer stringLocalizer, ElasticIndexSettingsService elasticIndexSettingsService) { _elasticIndexSettingsService = elasticIndexSettingsService; S = stringLocalizer; @@ -27,26 +25,44 @@ public ElasticQueryDisplayDriver( public override IDisplayResult Display(ElasticQuery query, IUpdateModel updater) { return Combine( - Dynamic("ElasticQuery_SummaryAdmin", model => { model.Query = query; }).Location("Content:5"), - Dynamic("ElasticQuery_Buttons_SummaryAdmin", model => { model.Query = query; }).Location("Actions:2") + Dynamic( + "ElasticQuery_SummaryAdmin", + model => + { + model.Query = query; + } + ) + .Location("Content:5"), + Dynamic( + "ElasticQuery_Buttons_SummaryAdmin", + model => + { + model.Query = query; + } + ) + .Location("Actions:2") ); } public override IDisplayResult Edit(ElasticQuery query, IUpdateModel updater) { - return Initialize("ElasticQuery_Edit", async model => - { - model.Query = query.Template; - model.Index = query.Index; - model.ReturnContentItems = query.ReturnContentItems; - model.Indices = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + return Initialize( + "ElasticQuery_Edit", + async model => + { + model.Query = query.Template; + model.Index = query.Index; + model.ReturnContentItems = query.ReturnContentItems; + model.Indices = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - // Extract query from the query string if we come from the main query editor - if (string.IsNullOrEmpty(query.Template)) - { - await updater.TryUpdateModelAsync(model, "", m => m.Query); - } - }).Location("Content:5"); + // Extract query from the query string if we come from the main query editor + if (string.IsNullOrEmpty(query.Template)) + { + await updater.TryUpdateModelAsync(model, "", m => m.Query); + } + } + ) + .Location("Content:5"); } public override async Task UpdateAsync(ElasticQuery model, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticSettingsDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticSettingsDeploymentStepDriver.cs index 53efead30c1..33c2993a908 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticSettingsDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Drivers/ElasticSettingsDeploymentStepDriver.cs @@ -9,11 +9,10 @@ public class ElasticSettingsDeploymentStepDriver : DisplayDriver elasticConnectionOptions, IElasticClient elasticClient, IStringLocalizer stringLocalizer - ) + ) { _elasticIndexSettingsService = elasticIndexSettingsService; _httpContextAccessor = httpContextAccessor; @@ -56,22 +53,27 @@ IStringLocalizer stringLocalizer S = stringLocalizer; } - public override IDisplayResult Edit(ElasticSettings settings) - => Initialize("ElasticSettings_Edit", async model => - { - model.SearchIndex = settings.SearchIndex; - model.SearchFields = string.Join(", ", settings.DefaultSearchFields ?? []); - model.SearchIndexes = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName); - model.DefaultQuery = settings.DefaultQuery; - model.SearchType = settings.GetSearchType(); - model.SearchTypes = [ - new(S["Multi-Match Query (Default)"], string.Empty), - new(S["Query String Query"], ElasticSettings.QueryStringSearchType), - new(S["Custom Query"], ElasticSettings.CustomSearchType), - ]; - }).Location("Content:2#Elasticsearch;10") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, Permissions.ManageElasticIndexes)) - .OnGroup(SearchConstants.SearchSettingsGroupId); + public override IDisplayResult Edit(ElasticSettings settings) => + Initialize( + "ElasticSettings_Edit", + async model => + { + model.SearchIndex = settings.SearchIndex; + model.SearchFields = string.Join(", ", settings.DefaultSearchFields ?? []); + model.SearchIndexes = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName); + model.DefaultQuery = settings.DefaultQuery; + model.SearchType = settings.GetSearchType(); + model.SearchTypes = + [ + new(S["Multi-Match Query (Default)"], string.Empty), + new(S["Query String Query"], ElasticSettings.QueryStringSearchType), + new(S["Custom Query"], ElasticSettings.CustomSearchType), + ]; + } + ) + .Location("Content:2#Elasticsearch;10") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, Permissions.ManageElasticIndexes)) + .OnGroup(SearchConstants.SearchSettingsGroupId); public override async Task UpdateAsync(ElasticSettings section, BuildEditorContext context) { diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/GraphQL/ElasticQueryFieldTypeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/GraphQL/ElasticQueryFieldTypeProvider.cs index b69614ba147..f518ba8a54d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/GraphQL/ElasticQueryFieldTypeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/GraphQL/ElasticQueryFieldTypeProvider.cs @@ -61,8 +61,7 @@ public async Task BuildAsync(ISchema schema) var fieldTypeName = querySchema["fieldTypeName"]?.ToString() ?? query.Name; - if (query.ReturnContentItems && - type.StartsWith("ContentItem/", StringComparison.OrdinalIgnoreCase)) + if (query.ReturnContentItems && type.StartsWith("ContentItem/", StringComparison.OrdinalIgnoreCase)) { var contentType = type.Remove(0, 12); fieldType = BuildContentTypeFieldType(schema, contentType, query, fieldTypeName); @@ -93,10 +92,7 @@ private static FieldType BuildSchemaBasedFieldType(ElasticQuery query, JsonNode return null; } - var typetype = new ObjectGraphType - { - Name = fieldTypeName - }; + var typetype = new ObjectGraphType { Name = fieldTypeName }; foreach (var child in properties) { @@ -142,9 +138,7 @@ private static FieldType BuildSchemaBasedFieldType(ElasticQuery query, JsonNode var fieldType = new FieldType { - Arguments = new QueryArguments( - new QueryArgument { Name = "parameters" } - ), + Arguments = new QueryArguments(new QueryArgument { Name = "parameters" }), Name = fieldTypeName, Description = "Represents the " + query.Source + " Query : " + query.Name, @@ -160,9 +154,7 @@ async ValueTask ResolveAsync(IResolveFieldContext context) var parameters = context.GetArgument("parameters"); - var queryParameters = parameters != null ? - JConvert.DeserializeObject>(parameters) - : []; + var queryParameters = parameters != null ? JConvert.DeserializeObject>(parameters) : []; var result = await queryManager.ExecuteQueryAsync(iquery, queryParameters); @@ -183,9 +175,7 @@ private static FieldType BuildContentTypeFieldType(ISchema schema, string conten var fieldType = new FieldType { - Arguments = new QueryArguments( - new QueryArgument { Name = "parameters" } - ), + Arguments = new QueryArguments(new QueryArgument { Name = "parameters" }), Name = fieldTypeName, Description = "Represents the " + query.Source + " Query : " + query.Name, @@ -201,9 +191,7 @@ async ValueTask ResolveAsync(IResolveFieldContext context) var parameters = context.GetArgument("parameters"); - var queryParameters = parameters != null ? - JConvert.DeserializeObject>(parameters) - : []; + var queryParameters = parameters != null ? JConvert.DeserializeObject>(parameters) : []; var result = await queryManager.ExecuteQueryAsync(iquery, queryParameters); diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Manifest.cs index 1b617e1c6fc..cc8d76ba82d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Manifest.cs @@ -11,11 +11,7 @@ Id = "OrchardCore.Search.Elasticsearch", Name = "Elasticsearch", Description = "Creates Elasticsearch indexes to support search scenarios, introduces a preconfigured container-enabled content type.", - Dependencies = - [ - "OrchardCore.Indexing", - "OrchardCore.ContentTypes" - ], + Dependencies = ["OrchardCore.Indexing", "OrchardCore.ContentTypes"], Category = "Search" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Permissions.cs index e7f52fa8094..f5edbaccfe2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Permissions.cs @@ -19,11 +19,7 @@ public Permissions(ElasticIndexSettingsService elasticIndexSettingsService) public async Task> GetPermissionsAsync() { - var permissions = new List() - { - ManageElasticIndexes, - QueryElasticApi, - }; + var permissions = new List() { ManageElasticIndexes, QueryElasticApi, }; var elasticIndexSettings = await _elasticIndexSettingsService.GetSettingsAsync(); @@ -36,22 +32,8 @@ public async Task> GetPermissionsAsync() } public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = - [ - ManageElasticIndexes, - ], - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = - [ - QueryElasticApi, - ], - }, - ]; + [ + new PermissionStereotype { Name = "Administrator", Permissions = [ManageElasticIndexes,], }, + new PermissionStereotype { Name = "Editor", Permissions = [QueryElasticApi,], }, + ]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Services/ElasticSearchService.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Services/ElasticSearchService.cs index 15f8e097b5d..3921d31b227 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Services/ElasticSearchService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Services/ElasticSearchService.cs @@ -40,7 +40,7 @@ public ElasticsearchService( IOptions elasticConnectionOptions, ILiquidTemplateManager liquidTemplateManager, ILogger logger - ) + ) { _siteService = siteService; _elasticIndexManager = elasticIndexManager; @@ -95,11 +95,11 @@ public async Task SearchAsync(string indexName, string term, int s if (searchType == ElasticSettings.CustomSearchType && !string.IsNullOrWhiteSpace(searchSettings.DefaultQuery)) { - var tokenizedContent = await _liquidTemplateManager.RenderStringAsync(searchSettings.DefaultQuery, _javaScriptEncoder, - new Dictionary() - { - ["term"] = new StringValue(term) - }); + var tokenizedContent = await _liquidTemplateManager.RenderStringAsync( + searchSettings.DefaultQuery, + _javaScriptEncoder, + new Dictionary() { ["term"] = new StringValue(term) } + ); try { diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Startup.cs index bcdb989d4ff..e966bf227b8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Startup.cs @@ -1,3 +1,5 @@ +using System.Text.Json; +using System.Text.Json.Nodes; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -23,8 +25,6 @@ using OrchardCore.Search.Lucene.Handler; using OrchardCore.Security.Permissions; using OrchardCore.Settings; -using System.Text.Json; -using System.Text.Json.Nodes; namespace OrchardCore.Search.Elasticsearch { @@ -41,12 +41,14 @@ public override void ConfigureServices(IServiceCollection services) { services.AddTransient, ElasticConnectionOptionsConfigurations>(); - services.AddSingleton((sp) => - { - var options = sp.GetRequiredService>().Value; + services.AddSingleton( + (sp) => + { + var options = sp.GetRequiredService>().Value; - return new ElasticClient(options.GetConnectionSettings() ?? new ConnectionSettings()); - }); + return new ElasticClient(options.GetConnectionSettings() ?? new ConnectionSettings()); + } + ); services.Configure(o => { @@ -57,10 +59,7 @@ public override void ConfigureServices(IServiceCollection services) var jsonNode = configuration.GetSection(nameof(o.Analyzers)).AsJsonNode(); var jsonElement = JsonSerializer.Deserialize(jsonNode); - var analyzersObject = JsonObject.Create(jsonElement, new JsonNodeOptions() - { - PropertyNameCaseInsensitive = true, - }); + var analyzersObject = JsonObject.Create(jsonElement, new JsonNodeOptions() { PropertyNameCaseInsensitive = true, }); if (analyzersObject != null) { @@ -83,10 +82,7 @@ public override void ConfigureServices(IServiceCollection services) if (o.Analyzers.Count == 0) { // When no analyzers are configured, we'll define a default analyzer. - o.Analyzers.Add(ElasticsearchConstants.DefaultAnalyzer, new JsonObject - { - ["type"] = "standard", - }); + o.Analyzers.Add(ElasticsearchConstants.DefaultAnalyzer, new JsonObject { ["type"] = "standard", }); } }); diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/AdminMenu.cs index b76a984dcfc..d2c5b286836 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/AdminMenu.cs @@ -15,24 +15,34 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Search"], NavigationConstants.AdminMenuSearchPosition, search => search - .AddClass("search").Id("search") - .Add(S["Indexing"], S["Indexing"].PrefixPosition(), import => import - .Add(S["Lucene Indices"], S["Lucene Indices"].PrefixPosition(), indexes => indexes - .Action("Index", "Admin", "OrchardCore.Search.Lucene") - .Permission(Permissions.ManageLuceneIndexes) - .LocalNav() - ) - ) - .Add(S["Queries"], S["Queries"].PrefixPosition(), import => import - .Add(S["Run Lucene Query"], S["Run Lucene Query"].PrefixPosition(), queries => queries - .Action("Query", "Admin", "OrchardCore.Search.Lucene") - .Permission(Permissions.ManageLuceneIndexes) - .LocalNav() + builder.Add( + S["Search"], + NavigationConstants.AdminMenuSearchPosition, + search => + search + .AddClass("search") + .Id("search") + .Add( + S["Indexing"], + S["Indexing"].PrefixPosition(), + import => + import.Add( + S["Lucene Indices"], + S["Lucene Indices"].PrefixPosition(), + indexes => indexes.Action("Index", "Admin", "OrchardCore.Search.Lucene").Permission(Permissions.ManageLuceneIndexes).LocalNav() + ) ) - ) - ); + .Add( + S["Queries"], + S["Queries"].PrefixPosition(), + import => + import.Add( + S["Run Lucene Query"], + S["Run Lucene Query"].PrefixPosition(), + queries => queries.Action("Query", "Admin", "OrchardCore.Search.Lucene").Permission(Permissions.ManageLuceneIndexes).LocalNav() + ) + ) + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Controllers/AdminController.cs index 03fdec5f624..8113a7c2012 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Controllers/AdminController.cs @@ -76,7 +76,8 @@ public AdminController( IHtmlLocalizer htmlLocalizer, ILogger logger, IOptions templateOptions, - ILocalizationService localizationService) + ILocalizationService localizationService + ) { _session = session; _luceneIndexManager = luceneIndexManager; @@ -116,10 +117,7 @@ public async Task Index(ContentOptions options, PagerParameters p results = results.Where(q => q.Name.Contains(options.Search, StringComparison.OrdinalIgnoreCase)); } - results = results - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize) - .ToList(); + results = results.Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -148,11 +146,7 @@ public async Task Index(ContentOptions options, PagerParameters p [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(AdminIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(AdminIndexViewModel model) => RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Edit(string indexName = null) { @@ -181,12 +175,12 @@ public async Task Edit(string indexName = null) AnalyzerName = IsCreate ? "standardanalyzer" : settings.AnalyzerName, IndexLatest = settings.IndexLatest, Culture = settings.Culture, - Cultures = ILocalizationService.GetAllCulturesAndAliases() - .Select(x => new SelectListItem { Text = x.Name + " (" + x.DisplayName + ")", Value = x.Name }).Prepend(new SelectListItem { Text = S["Any culture"], Value = "any" }), - Analyzers = _luceneAnalyzerManager.GetAnalyzers() - .Select(x => new SelectListItem { Text = x.Name, Value = x.Name }), - IndexedContentTypes = IsCreate ? (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Select(x => x.Name).ToArray() : settings.IndexedContentTypes, + Cultures = ILocalizationService + .GetAllCulturesAndAliases() + .Select(x => new SelectListItem { Text = x.Name + " (" + x.DisplayName + ")", Value = x.Name }) + .Prepend(new SelectListItem { Text = S["Any culture"], Value = "any" }), + Analyzers = _luceneAnalyzerManager.GetAnalyzers().Select(x => new SelectListItem { Text = x.Name, Value = x.Name }), + IndexedContentTypes = IsCreate ? (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Select(x => x.Name).ToArray() : settings.IndexedContentTypes, StoreSourceData = !IsCreate && settings.StoreSourceData }; @@ -223,13 +217,9 @@ public async Task EditPost(LuceneIndexSettingsViewModel model, str var supportedCultures = await _localizationService.GetSupportedCulturesAsync(); model.Cultures = supportedCultures - .Select(c => new SelectListItem - { - Text = $"{c} ({CultureInfo.GetCultureInfo(c).DisplayName})", - Value = c - }).Prepend(new SelectListItem { Text = S["Any culture"], Value = "any" }); - model.Analyzers = _luceneAnalyzerManager.GetAnalyzers() - .Select(x => new SelectListItem { Text = x.Name, Value = x.Name }); + .Select(c => new SelectListItem { Text = $"{c} ({CultureInfo.GetCultureInfo(c).DisplayName})", Value = c }) + .Prepend(new SelectListItem { Text = S["Any culture"], Value = "any" }); + model.Analyzers = _luceneAnalyzerManager.GetAnalyzers().Select(x => new SelectListItem { Text = x.Name, Value = x.Name }); return View(model); } @@ -237,7 +227,15 @@ public async Task EditPost(LuceneIndexSettingsViewModel model, str { try { - var settings = new LuceneIndexSettings { IndexName = model.IndexName, AnalyzerName = model.AnalyzerName, IndexLatest = model.IndexLatest, IndexedContentTypes = indexedContentTypes, Culture = model.Culture ?? "", StoreSourceData = model.StoreSourceData }; + var settings = new LuceneIndexSettings + { + IndexName = model.IndexName, + AnalyzerName = model.AnalyzerName, + IndexLatest = model.IndexLatest, + IndexedContentTypes = indexedContentTypes, + Culture = model.Culture ?? "", + StoreSourceData = model.StoreSourceData + }; // We call Rebuild in order to reset the index state cursor too in case the same index // name was also used previously. @@ -256,7 +254,15 @@ public async Task EditPost(LuceneIndexSettingsViewModel model, str { try { - var settings = new LuceneIndexSettings { IndexName = model.IndexName, AnalyzerName = model.AnalyzerName, IndexLatest = model.IndexLatest, IndexedContentTypes = indexedContentTypes, Culture = model.Culture ?? "", StoreSourceData = model.StoreSourceData }; + var settings = new LuceneIndexSettings + { + IndexName = model.IndexName, + AnalyzerName = model.AnalyzerName, + IndexLatest = model.IndexLatest, + IndexedContentTypes = indexedContentTypes, + Culture = model.Culture ?? "", + StoreSourceData = model.StoreSourceData + }; await _luceneIndexingService.UpdateIndexAsync(settings); } @@ -402,35 +408,42 @@ public async Task Query(AdminQueryViewModel model) var stopwatch = new Stopwatch(); stopwatch.Start(); - await _luceneIndexManager.SearchAsync(model.IndexName, async searcher => - { - var analyzer = _luceneAnalyzerManager.CreateAnalyzer(await _luceneIndexSettingsService.GetIndexAnalyzerAsync(model.IndexName)); - var context = new LuceneQueryContext(searcher, LuceneSettings.DefaultVersion, analyzer); + await _luceneIndexManager.SearchAsync( + model.IndexName, + async searcher => + { + var analyzer = _luceneAnalyzerManager.CreateAnalyzer(await _luceneIndexSettingsService.GetIndexAnalyzerAsync(model.IndexName)); + var context = new LuceneQueryContext(searcher, LuceneSettings.DefaultVersion, analyzer); - var parameters = JConvert.DeserializeObject>(model.Parameters); + var parameters = JConvert.DeserializeObject>(model.Parameters); - var tokenizedContent = await _liquidTemplateManager.RenderStringAsync(model.DecodedQuery, _javaScriptEncoder, parameters.Select(x => new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions.Value)))); + var tokenizedContent = await _liquidTemplateManager.RenderStringAsync( + model.DecodedQuery, + _javaScriptEncoder, + parameters.Select(x => new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions.Value))) + ); - try - { - var parameterizedQuery = JsonNode.Parse(tokenizedContent).AsObject(); - var luceneTopDocs = await _queryService.SearchAsync(context, parameterizedQuery); + try + { + var parameterizedQuery = JsonNode.Parse(tokenizedContent).AsObject(); + var luceneTopDocs = await _queryService.SearchAsync(context, parameterizedQuery); - if (luceneTopDocs != null) + if (luceneTopDocs != null) + { + model.Documents = luceneTopDocs.TopDocs.ScoreDocs.Select(hit => searcher.Doc(hit.Doc)).ToList(); + model.Count = luceneTopDocs.Count; + } + } + catch (Exception e) { - model.Documents = luceneTopDocs.TopDocs.ScoreDocs.Select(hit => searcher.Doc(hit.Doc)).ToList(); - model.Count = luceneTopDocs.Count; + _logger.LogError(e, "Error while executing query"); + ModelState.AddModelError(nameof(model.DecodedQuery), S["Invalid query : {0}", e.Message]); } - } - catch (Exception e) - { - _logger.LogError(e, "Error while executing query"); - ModelState.AddModelError(nameof(model.DecodedQuery), S["Invalid query : {0}", e.Message]); - } - stopwatch.Stop(); - model.Elapsed = stopwatch.Elapsed; - }); + stopwatch.Stop(); + model.Elapsed = stopwatch.Elapsed; + } + ); return View(model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Controllers/ApiController.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Controllers/ApiController.cs index 05f350af233..a1ca94c6f98 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Controllers/ApiController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Controllers/ApiController.cs @@ -15,9 +15,7 @@ public class ApiController : Controller private readonly IAuthorizationService _authorizationService; private readonly LuceneQuerySource _luceneQuerySource; - public ApiController( - IAuthorizationService authorizationService, - LuceneQuerySource luceneQuerySource) + public ApiController(IAuthorizationService authorizationService, LuceneQuerySource luceneQuerySource) { _authorizationService = authorizationService; _luceneQuerySource = luceneQuerySource; @@ -88,9 +86,7 @@ public async Task DocumentsPost(LuceneQueryModel queryModel) ReturnContentItems = returnContentItems }; - var queryParameters = queryModel.Parameters != null ? - JConvert.DeserializeObject>(queryModel.Parameters) - : []; + var queryParameters = queryModel.Parameters != null ? JConvert.DeserializeObject>(queryModel.Parameters) : []; return _luceneQuerySource.ExecuteQueryAsync(luceneQuery, queryParameters); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexDeploymentSource.cs index 6d0b56f9339..01051c71265 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexDeploymentSource.cs @@ -34,21 +34,14 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan { if (indicesToAdd.Contains(index.IndexName)) { - var indexSettingsDict = new Dictionary - { - { index.IndexName, index }, - }; + var indexSettingsDict = new Dictionary { { index.IndexName, index }, }; data.Add(JObject.FromObject(indexSettingsDict)); } } // Adding Lucene settings - result.Steps.Add(new JsonObject - { - ["name"] = "lucene-index", - ["Indices"] = data, - }); + result.Steps.Add(new JsonObject { ["name"] = "lucene-index", ["Indices"] = data, }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexDeploymentStepDriver.cs index 9b2ccce39e3..87a34840acb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexDeploymentStepDriver.cs @@ -19,31 +19,31 @@ public LuceneIndexDeploymentStepDriver(LuceneIndexSettingsService luceneIndexSet public override IDisplayResult Display(LuceneIndexDeploymentStep step) { - return - Combine( - View("LuceneIndexDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("LuceneIndexDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("LuceneIndexDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("LuceneIndexDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(LuceneIndexDeploymentStep step) { - return Initialize("LuceneIndexDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.IndexNames = step.IndexNames; - model.AllIndexNames = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }).Location("Content"); + return Initialize( + "LuceneIndexDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.IndexNames = step.IndexNames; + model.AllIndexNames = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(LuceneIndexDeploymentStep step, IUpdateModel updater) { step.IndexNames = []; - await updater.TryUpdateModelAsync(step, - Prefix, - x => x.IndexNames, - x => x.IncludeAll); + await updater.TryUpdateModelAsync(step, Prefix, x => x.IndexNames, x => x.IncludeAll); // don't have the selected option if include all if (step.IncludeAll) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexRebuildDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexRebuildDeploymentSource.cs index c2952037285..027c6cad8fb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexRebuildDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexRebuildDeploymentSource.cs @@ -17,12 +17,14 @@ public Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult var indicesToRebuild = luceneIndexRebuildStep.IncludeAll ? [] : luceneIndexRebuildStep.IndexNames; - result.Steps.Add(new JsonObject - { - ["name"] = "lucene-index-rebuild", - ["includeAll"] = luceneIndexRebuildStep.IncludeAll, - ["Indices"] = JArray.FromObject(indicesToRebuild), - }); + result.Steps.Add( + new JsonObject + { + ["name"] = "lucene-index-rebuild", + ["includeAll"] = luceneIndexRebuildStep.IncludeAll, + ["Indices"] = JArray.FromObject(indicesToRebuild), + } + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexRebuildDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexRebuildDeploymentStepDriver.cs index 66a0cc26bbd..bc68c32d86d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexRebuildDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexRebuildDeploymentStepDriver.cs @@ -19,21 +19,24 @@ public LuceneIndexRebuildDeploymentStepDriver(LuceneIndexSettingsService luceneI public override IDisplayResult Display(LuceneIndexRebuildDeploymentStep step) { - return - Combine( - View("LuceneIndexRebuildDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("LuceneIndexRebuildDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("LuceneIndexRebuildDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("LuceneIndexRebuildDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(LuceneIndexRebuildDeploymentStep step) { - return Initialize("LuceneIndexRebuildDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.IndexNames = step.IndexNames; - model.AllIndexNames = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }).Location("Content"); + return Initialize( + "LuceneIndexRebuildDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.IndexNames = step.IndexNames; + model.AllIndexNames = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(LuceneIndexRebuildDeploymentStep rebuildIndexStep, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexResetDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexResetDeploymentSource.cs index 91500be0020..be47e28abd2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexResetDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexResetDeploymentSource.cs @@ -17,12 +17,14 @@ public Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult var indicesToReset = luceneIndexResetStep.IncludeAll ? [] : luceneIndexResetStep.IndexNames; - result.Steps.Add(new JsonObject - { - ["name"] = "lucene-index-reset", - ["includeAll"] = luceneIndexResetStep.IncludeAll, - ["Indices"] = JArray.FromObject(indicesToReset), - }); + result.Steps.Add( + new JsonObject + { + ["name"] = "lucene-index-reset", + ["includeAll"] = luceneIndexResetStep.IncludeAll, + ["Indices"] = JArray.FromObject(indicesToReset), + } + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexResetDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexResetDeploymentStepDriver.cs index 40b24724a07..19699b127b8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexResetDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneIndexResetDeploymentStepDriver.cs @@ -19,21 +19,24 @@ public LuceneIndexResetDeploymentStepDriver(LuceneIndexSettingsService luceneInd public override IDisplayResult Display(LuceneIndexResetDeploymentStep step) { - return - Combine( - View("LuceneIndexResetDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), - View("LuceneIndexResetDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") - ); + return Combine( + View("LuceneIndexResetDeploymentStep_Fields_Summary", step).Location("Summary", "Content"), + View("LuceneIndexResetDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(LuceneIndexResetDeploymentStep step) { - return Initialize("LuceneIndexResetDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.IndexNames = step.IndexNames; - model.AllIndexNames = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }).Location("Content"); + return Initialize( + "LuceneIndexResetDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.IndexNames = step.IndexNames; + model.AllIndexNames = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(LuceneIndexResetDeploymentStep resetIndexStep, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneSettingsDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneSettingsDeploymentSource.cs index 1dd1a929c3e..f0b90b0efb1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneSettingsDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneSettingsDeploymentSource.cs @@ -25,11 +25,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan var luceneSettings = await _luceneIndexingService.GetLuceneSettingsAsync(); // Adding Lucene settings - result.Steps.Add(new JsonObject - { - ["name"] = "Settings", - ["LuceneSettings"] = JObject.FromObject(luceneSettings), - }); + result.Steps.Add(new JsonObject { ["name"] = "Settings", ["LuceneSettings"] = JObject.FromObject(luceneSettings), }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneSettingsDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneSettingsDeploymentStepDriver.cs index 29b5accea18..01b3a614a8e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneSettingsDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Deployment/LuceneSettingsDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class LuceneSettingsDeploymentStepDriver : DisplayDriver private readonly LuceneIndexSettingsService _luceneIndexSettingsService; protected readonly IStringLocalizer S; - public LuceneQueryDisplayDriver( - IStringLocalizer stringLocalizer, - LuceneIndexSettingsService luceneIndexSettingsService) + public LuceneQueryDisplayDriver(IStringLocalizer stringLocalizer, LuceneIndexSettingsService luceneIndexSettingsService) { _luceneIndexSettingsService = luceneIndexSettingsService; S = stringLocalizer; @@ -25,26 +23,44 @@ public LuceneQueryDisplayDriver( public override IDisplayResult Display(LuceneQuery query, IUpdateModel updater) { return Combine( - Dynamic("LuceneQuery_SummaryAdmin", model => { model.Query = query; }).Location("Content:5"), - Dynamic("LuceneQuery_Buttons_SummaryAdmin", model => { model.Query = query; }).Location("Actions:2") + Dynamic( + "LuceneQuery_SummaryAdmin", + model => + { + model.Query = query; + } + ) + .Location("Content:5"), + Dynamic( + "LuceneQuery_Buttons_SummaryAdmin", + model => + { + model.Query = query; + } + ) + .Location("Actions:2") ); } public override IDisplayResult Edit(LuceneQuery query, IUpdateModel updater) { - return Initialize("LuceneQuery_Edit", async model => - { - model.Query = query.Template; - model.Index = query.Index; - model.ReturnContentItems = query.ReturnContentItems; - model.Indices = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + return Initialize( + "LuceneQuery_Edit", + async model => + { + model.Query = query.Template; + model.Index = query.Index; + model.ReturnContentItems = query.ReturnContentItems; + model.Indices = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - // Extract query from the query string if we come from the main query editor - if (string.IsNullOrEmpty(query.Template)) - { - await updater.TryUpdateModelAsync(model, "", m => m.Query); - } - }).Location("Content:5"); + // Extract query from the query string if we come from the main query editor + if (string.IsNullOrEmpty(query.Template)) + { + await updater.TryUpdateModelAsync(model, "", m => m.Query); + } + } + ) + .Location("Content:5"); } public override async Task UpdateAsync(LuceneQuery model, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Drivers/LuceneSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Drivers/LuceneSettingsDisplayDriver.cs index 49dda406d54..32a815386ac 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Drivers/LuceneSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Drivers/LuceneSettingsDisplayDriver.cs @@ -17,7 +17,7 @@ public class LuceneSettingsDisplayDriver( LuceneIndexSettingsService luceneIndexSettingsService, IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService - ) : SectionDisplayDriver + ) : SectionDisplayDriver { private readonly LuceneIndexSettingsService _luceneIndexSettingsService = luceneIndexSettingsService; private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; @@ -33,13 +33,17 @@ public override async Task EditAsync(LuceneSettings settings, Bu return null; } - return Initialize("LuceneSettings_Edit", async model => - { - model.SearchIndex = settings.SearchIndex; - model.SearchFields = string.Join(", ", settings.DefaultSearchFields ?? []); - model.SearchIndexes = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName); - model.AllowLuceneQueriesInSearch = settings.AllowLuceneQueriesInSearch; - }).Location("Content:2#Lucene;15") + return Initialize( + "LuceneSettings_Edit", + async model => + { + model.SearchIndex = settings.SearchIndex; + model.SearchFields = string.Join(", ", settings.DefaultSearchFields ?? []); + model.SearchIndexes = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName); + model.AllowLuceneQueriesInSearch = settings.AllowLuceneQueriesInSearch; + } + ) + .Location("Content:2#Lucene;15") .OnGroup(SearchConstants.SearchSettingsGroupId); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/GraphQL/LuceneQueryFieldTypeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/GraphQL/LuceneQueryFieldTypeProvider.cs index bd1e655553f..05a6f082f6c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/GraphQL/LuceneQueryFieldTypeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/GraphQL/LuceneQueryFieldTypeProvider.cs @@ -60,8 +60,7 @@ public async Task BuildAsync(ISchema schema) var fieldTypeName = querySchema["fieldTypeName"]?.ToString() ?? query.Name; - if (query.ReturnContentItems && - type.StartsWith("ContentItem/", StringComparison.OrdinalIgnoreCase)) + if (query.ReturnContentItems && type.StartsWith("ContentItem/", StringComparison.OrdinalIgnoreCase)) { var contentType = type.Remove(0, 12); fieldType = BuildContentTypeFieldType(schema, contentType, query, fieldTypeName); @@ -85,16 +84,14 @@ public async Task BuildAsync(ISchema schema) private static FieldType BuildSchemaBasedFieldType(LuceneQuery query, JsonNode querySchema, string fieldTypeName) { - var properties = querySchema["properties"].AsObject(); ; + var properties = querySchema["properties"].AsObject(); + ; if (properties == null) { return null; } - var typetype = new ObjectGraphType - { - Name = fieldTypeName - }; + var typetype = new ObjectGraphType { Name = fieldTypeName }; foreach (var child in properties) { @@ -140,9 +137,7 @@ private static FieldType BuildSchemaBasedFieldType(LuceneQuery query, JsonNode q var fieldType = new FieldType { - Arguments = new QueryArguments( - new QueryArgument { Name = "parameters" } - ), + Arguments = new QueryArguments(new QueryArgument { Name = "parameters" }), Name = fieldTypeName, Description = "Represents the " + query.Source + " Query : " + query.Name, @@ -158,9 +153,7 @@ async ValueTask ResolveAsync(IResolveFieldContext context) var parameters = context.GetArgument("parameters"); - var queryParameters = parameters != null ? - JConvert.DeserializeObject>(parameters) - : []; + var queryParameters = parameters != null ? JConvert.DeserializeObject>(parameters) : []; var result = await queryManager.ExecuteQueryAsync(iquery, queryParameters); @@ -181,9 +174,7 @@ private static FieldType BuildContentTypeFieldType(ISchema schema, string conten var fieldType = new FieldType { - Arguments = new QueryArguments( - new QueryArgument { Name = "parameters" } - ), + Arguments = new QueryArguments(new QueryArgument { Name = "parameters" }), Name = fieldTypeName, Description = "Represents the " + query.Source + " Query : " + query.Name, @@ -199,9 +190,7 @@ async ValueTask ResolveAsync(IResolveFieldContext context) var parameters = context.GetArgument("parameters"); - var queryParameters = parameters != null ? - JConvert.DeserializeObject>(parameters) - : []; + var queryParameters = parameters != null ? JConvert.DeserializeObject>(parameters) : []; var result = await queryManager.ExecuteQueryAsync(iquery, queryParameters); diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Handler/LuceneIndexingContentHandler.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Handler/LuceneIndexingContentHandler.cs index e81a8e09112..32d3026a9fa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Handler/LuceneIndexingContentHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Handler/LuceneIndexingContentHandler.cs @@ -27,9 +27,13 @@ public LuceneIndexingContentHandler(IHttpContextAccessor httpContextAccessor) } public override Task PublishedAsync(PublishContentContext context) => AddContextAsync(context); + public override Task CreatedAsync(CreateContentContext context) => AddContextAsync(context); + public override Task UpdatedAsync(UpdateContentContext context) => AddContextAsync(context); + public override Task RemovedAsync(RemoveContentContext context) => AddContextAsync(context); + public override Task UnpublishedAsync(PublishContentContext context) => AddContextAsync(context); private Task AddContextAsync(ContentContextBase context) @@ -77,8 +81,10 @@ private static async Task IndexingAsync(ShellScope scope, IEnumerable x.BuildIndexAsync(buildIndexContext), logger); await luceneIndexManager.DeleteDocumentsAsync(indexSettings.IndexName, new string[] { contentItem.ContentItemId }); diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Manifest.cs index 33838a291ed..2dcb7d71b67 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Manifest.cs @@ -1,21 +1,12 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Lucene", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Lucene", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Search.Lucene", Name = "Lucene", Description = "Creates Lucene indexes to support search scenarios, introduces a preconfigured container-enabled content type.", - Dependencies = - [ - "OrchardCore.Indexing", - "OrchardCore.ContentTypes" - ], + Dependencies = ["OrchardCore.Indexing", "OrchardCore.ContentTypes"], Category = "Search" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Migrations.cs index 9ba4139ff17..50623fd38c9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Migrations.cs @@ -48,17 +48,71 @@ private async Task UpgradeAsync() { foreach (var partDefinition in contentTypeDefinition.Parts) { - await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, partBuilder => + await _contentDefinitionManager.AlterPartDefinitionAsync( + partDefinition.Name, + partBuilder => + { + if ( + partDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingPartSettings) + && !partDefinition.Settings.ContainsKey(nameof(LuceneContentIndexSettings)) + ) + { + var included = existingPartSettings["Included"]; + var analyzed = existingPartSettings["Analyzed"]; + + if (included is not null) + { + if (analyzed is not null) + { + if ((bool)included && !(bool)analyzed) + { + existingPartSettings["Keyword"] = true; + } + } + else + { + if ((bool)included) + { + existingPartSettings["Keyword"] = true; + } + } + } + + var jExistingPartSettings = existingPartSettings.AsObject(); + + // We remove unnecessary properties from old releases. + jExistingPartSettings.Remove("Analyzed"); + jExistingPartSettings.Remove("Tokenized"); + jExistingPartSettings.Remove("Template"); + + partDefinition.Settings.Add(nameof(LuceneContentIndexSettings), jExistingPartSettings.Clone()); + } + + partDefinition.Settings.Remove("ContentIndexSettings"); + } + ); + } + } + + var partDefinitions = await _contentDefinitionManager.LoadPartDefinitionsAsync(); + + foreach (var partDefinition in partDefinitions) + { + await _contentDefinitionManager.AlterPartDefinitionAsync( + partDefinition.Name, + partBuilder => { - if (partDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingPartSettings) && - !partDefinition.Settings.ContainsKey(nameof(LuceneContentIndexSettings))) + if ( + partDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingPartSettings) + && !partDefinition.Settings.ContainsKey(nameof(LuceneContentIndexSettings)) + ) { var included = existingPartSettings["Included"]; var analyzed = existingPartSettings["Analyzed"]; - if (included is not null) + if (included != null) { - if (analyzed is not null) + if (analyzed != null) { if ((bool)included && !(bool)analyzed) { @@ -85,91 +139,49 @@ await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, pa } partDefinition.Settings.Remove("ContentIndexSettings"); - }); - } - } - - var partDefinitions = await _contentDefinitionManager.LoadPartDefinitionsAsync(); - - foreach (var partDefinition in partDefinitions) - { - await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, partBuilder => - { - if (partDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingPartSettings) && - !partDefinition.Settings.ContainsKey(nameof(LuceneContentIndexSettings))) - { - var included = existingPartSettings["Included"]; - var analyzed = existingPartSettings["Analyzed"]; - if (included != null) + foreach (var fieldDefinition in partDefinition.Fields) { - if (analyzed != null) - { - if ((bool)included && !(bool)analyzed) - { - existingPartSettings["Keyword"] = true; - } - } - else + if ( + fieldDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingFieldSettings) + && !fieldDefinition.Settings.TryGetPropertyValue(nameof(LuceneContentIndexSettings), out _) + ) { - if ((bool)included) - { - existingPartSettings["Keyword"] = true; - } - } - } - - var jExistingPartSettings = existingPartSettings.AsObject(); - - // We remove unnecessary properties from old releases. - jExistingPartSettings.Remove("Analyzed"); - jExistingPartSettings.Remove("Tokenized"); - jExistingPartSettings.Remove("Template"); + var included = existingFieldSettings["Included"]; + var analyzed = existingFieldSettings["Analyzed"]; - partDefinition.Settings.Add(nameof(LuceneContentIndexSettings), jExistingPartSettings.Clone()); - } - - partDefinition.Settings.Remove("ContentIndexSettings"); - - foreach (var fieldDefinition in partDefinition.Fields) - { - if (fieldDefinition.Settings.TryGetPropertyValue("ContentIndexSettings", out var existingFieldSettings) && - !fieldDefinition.Settings.TryGetPropertyValue(nameof(LuceneContentIndexSettings), out _)) - { - var included = existingFieldSettings["Included"]; - var analyzed = existingFieldSettings["Analyzed"]; - - if (included != null) - { - if (analyzed != null) + if (included != null) { - if ((bool)included && !(bool)analyzed) + if (analyzed != null) { - existingFieldSettings["Keyword"] = true; + if ((bool)included && !(bool)analyzed) + { + existingFieldSettings["Keyword"] = true; + } } - } - else - { - if ((bool)included) + else { - existingFieldSettings["Keyword"] = true; + if ((bool)included) + { + existingFieldSettings["Keyword"] = true; + } } } - } - var jExistingFieldSettings = existingFieldSettings.AsObject(); + var jExistingFieldSettings = existingFieldSettings.AsObject(); - // We remove unnecessary properties from old releases. - jExistingFieldSettings.Remove("Analyzed"); - jExistingFieldSettings.Remove("Tokenized"); - jExistingFieldSettings.Remove("Template"); + // We remove unnecessary properties from old releases. + jExistingFieldSettings.Remove("Analyzed"); + jExistingFieldSettings.Remove("Tokenized"); + jExistingFieldSettings.Remove("Template"); - fieldDefinition.Settings.Add(nameof(LuceneContentIndexSettings), jExistingFieldSettings.Clone()); - } + fieldDefinition.Settings.Add(nameof(LuceneContentIndexSettings), jExistingFieldSettings.Clone()); + } - fieldDefinition.Settings.Remove("ContentIndexSettings"); + fieldDefinition.Settings.Remove("ContentIndexSettings"); + } } - }); + ); } // Defer this until after the subsequent migrations have succeeded as the schema has changed. @@ -198,27 +210,33 @@ await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, pa var quotedContentColumnName = dialect.QuoteForColumnName("Content"); var quotedTypeColumnName = dialect.QuoteForColumnName("Type"); - var updateCmd = $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, '\"$type\":\"OrchardCore.Lucene.LuceneQuery, OrchardCore.Lucene\"', '\"$type\":\"OrchardCore.Search.Lucene.LuceneQuery, OrchardCore.Search.Lucene\"') WHERE {quotedTypeColumnName} = 'OrchardCore.Queries.Services.QueriesDocument, OrchardCore.Queries'"; + var updateCmd = + $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, '\"$type\":\"OrchardCore.Lucene.LuceneQuery, OrchardCore.Lucene\"', '\"$type\":\"OrchardCore.Search.Lucene.LuceneQuery, OrchardCore.Search.Lucene\"') WHERE {quotedTypeColumnName} = 'OrchardCore.Queries.Services.QueriesDocument, OrchardCore.Queries'"; await transaction.Connection.ExecuteAsync(updateCmd, null, transaction); - updateCmd = $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, '\"$type\":\"OrchardCore.Lucene.Deployment.LuceneIndexDeploymentStep, OrchardCore.Lucene\"', '\"$type\":\"OrchardCore.Search.Lucene.Deployment.LuceneIndexDeploymentStep, OrchardCore.Search.Lucene\"') WHERE {quotedTypeColumnName} = 'OrchardCore.Deployment.DeploymentPlan, OrchardCore.Deployment.Abstractions'"; + updateCmd = + $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, '\"$type\":\"OrchardCore.Lucene.Deployment.LuceneIndexDeploymentStep, OrchardCore.Lucene\"', '\"$type\":\"OrchardCore.Search.Lucene.Deployment.LuceneIndexDeploymentStep, OrchardCore.Search.Lucene\"') WHERE {quotedTypeColumnName} = 'OrchardCore.Deployment.DeploymentPlan, OrchardCore.Deployment.Abstractions'"; await transaction.Connection.ExecuteAsync(updateCmd, null, transaction); - updateCmd = $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, '\"$type\":\"OrchardCore.Lucene.Deployment.LuceneSettingsDeploymentStep, OrchardCore.Lucene\"', '\"$type\":\"OrchardCore.Search.Lucene.Deployment.LuceneSettingsDeploymentStep, OrchardCore.Search.Lucene\"') WHERE {quotedTypeColumnName} = 'OrchardCore.Deployment.DeploymentPlan, OrchardCore.Deployment.Abstractions'"; + updateCmd = + $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, '\"$type\":\"OrchardCore.Lucene.Deployment.LuceneSettingsDeploymentStep, OrchardCore.Lucene\"', '\"$type\":\"OrchardCore.Search.Lucene.Deployment.LuceneSettingsDeploymentStep, OrchardCore.Search.Lucene\"') WHERE {quotedTypeColumnName} = 'OrchardCore.Deployment.DeploymentPlan, OrchardCore.Deployment.Abstractions'"; await transaction.Connection.ExecuteAsync(updateCmd, null, transaction); - updateCmd = $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, '\"$type\":\"OrchardCore.Lucene.Deployment.LuceneIndexResetDeploymentStep, OrchardCore.Lucene\"', '\"$type\":\"OrchardCore.Search.Lucene.Deployment.LuceneIndexResetDeploymentStep, OrchardCore.Search.Lucene\"') WHERE {quotedTypeColumnName} = 'OrchardCore.Deployment.DeploymentPlan, OrchardCore.Deployment.Abstractions'"; + updateCmd = + $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, '\"$type\":\"OrchardCore.Lucene.Deployment.LuceneIndexResetDeploymentStep, OrchardCore.Lucene\"', '\"$type\":\"OrchardCore.Search.Lucene.Deployment.LuceneIndexResetDeploymentStep, OrchardCore.Search.Lucene\"') WHERE {quotedTypeColumnName} = 'OrchardCore.Deployment.DeploymentPlan, OrchardCore.Deployment.Abstractions'"; await transaction.Connection.ExecuteAsync(updateCmd, null, transaction); - updateCmd = $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, '\"$type\":\"OrchardCore.Lucene.Deployment.LuceneIndexRebuildDeploymentStep, OrchardCore.Lucene\"', '\"$type\":\"OrchardCore.Search.Lucene.Deployment.LuceneIndexRebuildDeploymentStep, OrchardCore.Search.Lucene\"') WHERE {quotedTypeColumnName} = 'OrchardCore.Deployment.DeploymentPlan, OrchardCore.Deployment.Abstractions'"; + updateCmd = + $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, '\"$type\":\"OrchardCore.Lucene.Deployment.LuceneIndexRebuildDeploymentStep, OrchardCore.Lucene\"', '\"$type\":\"OrchardCore.Search.Lucene.Deployment.LuceneIndexRebuildDeploymentStep, OrchardCore.Search.Lucene\"') WHERE {quotedTypeColumnName} = 'OrchardCore.Deployment.DeploymentPlan, OrchardCore.Deployment.Abstractions'"; await transaction.Connection.ExecuteAsync(updateCmd, null, transaction); - updateCmd = $"UPDATE {quotedTableName} SET {quotedTypeColumnName} = 'OrchardCore.Search.Lucene.Model.LuceneIndexSettingsDocument, OrchardCore.Search.Lucene' WHERE {quotedTypeColumnName} = 'OrchardCore.Lucene.Model.LuceneIndexSettingsDocument, OrchardCore.Lucene'"; + updateCmd = + $"UPDATE {quotedTableName} SET {quotedTypeColumnName} = 'OrchardCore.Search.Lucene.Model.LuceneIndexSettingsDocument, OrchardCore.Search.Lucene' WHERE {quotedTypeColumnName} = 'OrchardCore.Lucene.Model.LuceneIndexSettingsDocument, OrchardCore.Lucene'"; await transaction.Connection.ExecuteAsync(updateCmd, null, transaction); diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Permissions.cs index 1ff55c627d3..1b9032d5fab 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Permissions.cs @@ -19,11 +19,7 @@ public Permissions(LuceneIndexSettingsService luceneIndexSettingsService) public async Task> GetPermissionsAsync() { - var permissions = new List() - { - ManageLuceneIndexes, - QueryLuceneApi, - }; + var permissions = new List() { ManageLuceneIndexes, QueryLuceneApi, }; var luceneIndexSettings = await _luceneIndexSettingsService.GetSettingsAsync(); @@ -36,22 +32,8 @@ public async Task> GetPermissionsAsync() } public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = - [ - ManageLuceneIndexes, - ], - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = - [ - QueryLuceneApi, - ], - }, - ]; + [ + new PermissionStereotype { Name = "Administrator", Permissions = [ManageLuceneIndexes,], }, + new PermissionStereotype { Name = "Editor", Permissions = [QueryLuceneApi,], }, + ]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexRebuildStep.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexRebuildStep.cs index 3131c9a8638..05209589a07 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexRebuildStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexRebuildStep.cs @@ -25,23 +25,26 @@ public async Task ExecuteAsync(RecipeExecutionContext context) if (model.IncludeAll || model.Indices.Length > 0) { - await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync("lucene-index-rebuild", async (scope) => - { - var luceneIndexSettingsService = scope.ServiceProvider.GetRequiredService(); - var luceneIndexingService = scope.ServiceProvider.GetRequiredService(); + await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync( + "lucene-index-rebuild", + async (scope) => + { + var luceneIndexSettingsService = scope.ServiceProvider.GetRequiredService(); + var luceneIndexingService = scope.ServiceProvider.GetRequiredService(); - var indices = model.IncludeAll ? (await luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray() : model.Indices; + var indices = model.IncludeAll ? (await luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray() : model.Indices; - foreach (var indexName in indices) - { - var luceneIndexSettings = await luceneIndexSettingsService.GetSettingsAsync(indexName); - if (luceneIndexSettings != null) + foreach (var indexName in indices) { - await luceneIndexingService.RebuildIndexAsync(indexName); - await luceneIndexingService.ProcessContentItemsAsync(indexName); + var luceneIndexSettings = await luceneIndexSettingsService.GetSettingsAsync(indexName); + if (luceneIndexSettings != null) + { + await luceneIndexingService.RebuildIndexAsync(indexName); + await luceneIndexingService.ProcessContentItemsAsync(indexName); + } } } - }); + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexResetStep.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexResetStep.cs index 62b17fd72d3..1bb6b0d8701 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexResetStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexResetStep.cs @@ -25,31 +25,34 @@ public async Task ExecuteAsync(RecipeExecutionContext context) if (model.IncludeAll || model.Indices.Length > 0) { - await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync("lucene-index-reset", async (scope) => - { - var luceneIndexSettingsService = scope.ServiceProvider.GetRequiredService(); - var luceneIndexingService = scope.ServiceProvider.GetRequiredService(); - var luceneIndexManager = scope.ServiceProvider.GetRequiredService(); + await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync( + "lucene-index-reset", + async (scope) => + { + var luceneIndexSettingsService = scope.ServiceProvider.GetRequiredService(); + var luceneIndexingService = scope.ServiceProvider.GetRequiredService(); + var luceneIndexManager = scope.ServiceProvider.GetRequiredService(); - var indices = model.IncludeAll ? (await luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray() : model.Indices; + var indices = model.IncludeAll ? (await luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray() : model.Indices; - foreach (var indexName in indices) - { - var luceneIndexSettings = await luceneIndexSettingsService.GetSettingsAsync(indexName); - if (luceneIndexSettings != null) + foreach (var indexName in indices) { - if (!luceneIndexManager.Exists(indexName)) - { - await luceneIndexingService.CreateIndexAsync(luceneIndexSettings); - } - else + var luceneIndexSettings = await luceneIndexSettingsService.GetSettingsAsync(indexName); + if (luceneIndexSettings != null) { - luceneIndexingService.ResetIndexAsync(indexName); + if (!luceneIndexManager.Exists(indexName)) + { + await luceneIndexingService.CreateIndexAsync(luceneIndexSettings); + } + else + { + luceneIndexingService.ResetIndexAsync(indexName); + } + await luceneIndexingService.ProcessContentItemsAsync(indexName); } - await luceneIndexingService.ProcessContentItemsAsync(indexName); } } - }); + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexStep.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexStep.cs index 0dd0611145c..bd826866016 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Recipes/LuceneIndexStep.cs @@ -17,10 +17,7 @@ public class LuceneIndexStep : IRecipeStepHandler private readonly LuceneIndexingService _luceneIndexingService; private readonly LuceneIndexManager _luceneIndexManager; - public LuceneIndexStep( - LuceneIndexingService luceneIndexingService, - LuceneIndexManager luceneIndexManager - ) + public LuceneIndexStep(LuceneIndexingService luceneIndexingService, LuceneIndexManager luceneIndexManager) { _luceneIndexManager = luceneIndexManager; _luceneIndexingService = luceneIndexingService; diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/IndexingBackgroundTask.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/IndexingBackgroundTask.cs index a0c0616adc0..3512e997929 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/IndexingBackgroundTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/IndexingBackgroundTask.cs @@ -12,10 +12,7 @@ namespace OrchardCore.Search.Lucene /// /// This services is only registered from OrchardCore.Search.Lucene.Worker feature. /// - [BackgroundTask( - Title = "Lucene Indexes Updater", - Schedule = "* * * * *", - Description = "Updates lucene indexes.")] + [BackgroundTask(Title = "Lucene Indexes Updater", Schedule = "* * * * *", Description = "Updates lucene indexes.")] public class IndexingBackgroundTask : IBackgroundTask { public Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneAnalyzer.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneAnalyzer.cs index 1ab4662d7d3..516d2fa96e2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneAnalyzer.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneAnalyzer.cs @@ -13,11 +13,11 @@ public LuceneAnalyzer(string name, Func factory) Name = name; } - public LuceneAnalyzer(string name, Analyzer instance) : this(name, () => instance) - { - } + public LuceneAnalyzer(string name, Analyzer instance) + : this(name, () => instance) { } public string Name { get; } + public Analyzer CreateAnalyzer() { return _factory(); diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneContentPickerResultProvider.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneContentPickerResultProvider.cs index 18592a9f90c..61c6add20ca 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneContentPickerResultProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneContentPickerResultProvider.cs @@ -38,37 +38,42 @@ public async Task> Search(ContentPickerSearchCo var results = new List(); - await _luceneIndexManager.SearchAsync(indexName, searcher => - { - Query query = null; - - if (string.IsNullOrWhiteSpace(searchContext.Query)) + await _luceneIndexManager.SearchAsync( + indexName, + searcher => { - query = new MatchAllDocsQuery(); - } - else - { - query = new WildcardQuery(new Term("Content.ContentItem.DisplayText.Normalized", searchContext.Query.ToLowerInvariant() + "*")); - } + Query query = null; - var filter = new FieldCacheTermsFilter("Content.ContentItem.ContentType", searchContext.ContentTypes.ToArray()); + if (string.IsNullOrWhiteSpace(searchContext.Query)) + { + query = new MatchAllDocsQuery(); + } + else + { + query = new WildcardQuery(new Term("Content.ContentItem.DisplayText.Normalized", searchContext.Query.ToLowerInvariant() + "*")); + } - var docs = searcher.Search(query, filter, 50, Sort.RELEVANCE); + var filter = new FieldCacheTermsFilter("Content.ContentItem.ContentType", searchContext.ContentTypes.ToArray()); - foreach (var hit in docs.ScoreDocs) - { - var doc = searcher.Doc(hit.Doc); + var docs = searcher.Search(query, filter, 50, Sort.RELEVANCE); - results.Add(new ContentPickerResult + foreach (var hit in docs.ScoreDocs) { - ContentItemId = doc.GetField("ContentItemId").GetStringValue(), - DisplayText = doc.GetField("Content.ContentItem.DisplayText.keyword").GetStringValue(), - HasPublished = doc.GetField("Content.ContentItem.Published").GetStringValue().Equals("true", StringComparison.OrdinalIgnoreCase), - }); + var doc = searcher.Doc(hit.Doc); + + results.Add( + new ContentPickerResult + { + ContentItemId = doc.GetField("ContentItemId").GetStringValue(), + DisplayText = doc.GetField("Content.ContentItem.DisplayText.keyword").GetStringValue(), + HasPublished = doc.GetField("Content.ContentItem.Published").GetStringValue().Equals("true", StringComparison.OrdinalIgnoreCase), + } + ); + } + + return Task.CompletedTask; } - - return Task.CompletedTask; - }); + ); return results.OrderBy(x => x.DisplayText); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexManager.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexManager.cs index af41d25e452..31b672b4cb8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexManager.cs @@ -43,7 +43,7 @@ public class LuceneIndexManager : IDisposable private readonly LuceneIndexSettingsService _luceneIndexSettingsService; private readonly SpatialContext _ctx; private readonly GeohashPrefixTree _grid; - private readonly static object _synLock = new(); + private static readonly object _synLock = new(); public LuceneIndexManager( IClock clock, @@ -52,14 +52,11 @@ public LuceneIndexManager( ILogger logger, LuceneAnalyzerManager luceneAnalyzerManager, LuceneIndexSettingsService luceneIndexSettingsService - ) + ) { _clock = clock; _logger = logger; - _rootPath = PathExtensions.Combine( - shellOptions.Value.ShellsApplicationDataPath, - shellOptions.Value.ShellsContainerName, - shellSettings.Name, "Lucene"); + _rootPath = PathExtensions.Combine(shellOptions.Value.ShellsApplicationDataPath, shellOptions.Value.ShellsContainerName, shellSettings.Name, "Lucene"); Directory.CreateDirectory(_rootPath); _luceneAnalyzerManager = luceneAnalyzerManager; _luceneIndexSettingsService = luceneIndexSettingsService; @@ -82,18 +79,21 @@ public async Task CreateIndexAsync(string indexName) public async Task DeleteDocumentsAsync(string indexName, IEnumerable contentItemIds) { - await WriteAsync(indexName, writer => - { - writer.DeleteDocuments(contentItemIds.Select(x => new Term("ContentItemId", x)).ToArray()); + await WriteAsync( + indexName, + writer => + { + writer.DeleteDocuments(contentItemIds.Select(x => new Term("ContentItemId", x)).ToArray()); - writer.Commit(); + writer.Commit(); - if (_indexPools.TryRemove(indexName, out var pool)) - { - pool.MakeDirty(); - pool.Release(); + if (_indexPools.TryRemove(indexName, out var pool)) + { + pool.MakeDirty(); + pool.Release(); + } } - }); + ); } public void DeleteIndex(string indexName) @@ -142,21 +142,24 @@ public async Task StoreDocumentsAsync(string indexName, IEnumerable - { - foreach (var indexDocument in indexDocuments) + await WriteAsync( + indexName, + writer => { - writer.AddDocument(CreateLuceneDocument(indexDocument, luceneIndexSettings)); - } + foreach (var indexDocument in indexDocuments) + { + writer.AddDocument(CreateLuceneDocument(indexDocument, luceneIndexSettings)); + } - writer.Commit(); + writer.Commit(); - if (_indexPools.TryRemove(indexName, out var pool)) - { - pool.MakeDirty(); - pool.Release(); + if (_indexPools.TryRemove(indexName, out var pool)) + { + pool.MakeDirty(); + pool.Release(); + } } - }); + ); } public async Task SearchAsync(string indexName, Func searcher) @@ -206,9 +209,7 @@ private Document CreateLuceneDocument(DocumentIndex documentIndex, LuceneIndexSe foreach (var entry in documentIndex.Entries) { - var store = entry.Options.HasFlag(DocumentIndexOptions.Store) - ? Field.Store.YES - : Field.Store.NO; + var store = entry.Options.HasFlag(DocumentIndexOptions.Store) ? Field.Store.YES : Field.Store.NO; switch (entry.Type) { @@ -238,11 +239,21 @@ private Document CreateLuceneDocument(DocumentIndex documentIndex, LuceneIndexSe { if (entry.Value is DateTimeOffset) { - doc.Add(new StoredField(IndexingConstants.SourceKey + entry.Name, DateTools.DateToString(((DateTimeOffset)entry.Value).UtcDateTime, DateResolution.SECOND))); + doc.Add( + new StoredField( + IndexingConstants.SourceKey + entry.Name, + DateTools.DateToString(((DateTimeOffset)entry.Value).UtcDateTime, DateResolution.SECOND) + ) + ); } else { - doc.Add(new StoredField(IndexingConstants.SourceKey + entry.Name, DateTools.DateToString(((DateTime)entry.Value).ToUniversalTime(), DateResolution.SECOND))); + doc.Add( + new StoredField( + IndexingConstants.SourceKey + entry.Name, + DateTools.DateToString(((DateTime)entry.Value).ToUniversalTime(), DateResolution.SECOND) + ) + ); } } } @@ -417,12 +428,15 @@ private async Task WriteAsync(string indexName, Action action, bool private IndexReaderPool.IndexReaderLease GetReader(string indexName) { - var pool = _indexPools.GetOrAdd(indexName, n => - { - var path = new DirectoryInfo(PathExtensions.Combine(_rootPath, indexName)); - var reader = DirectoryReader.Open(FSDirectory.Open(path)); - return new IndexReaderPool(reader); - }); + var pool = _indexPools.GetOrAdd( + indexName, + n => + { + var path = new DirectoryInfo(PathExtensions.Combine(_rootPath, indexName)); + var reader = DirectoryReader.Open(FSDirectory.Open(path)); + return new IndexReaderPool(reader); + } + ); return pool.Acquire(); } @@ -522,7 +536,8 @@ public void Dispose() internal class IndexWriterWrapper : IndexWriter { - public IndexWriterWrapper(LDirectory directory, IndexWriterConfig config) : base(directory, config) + public IndexWriterWrapper(LDirectory directory, IndexWriterConfig config) + : base(directory, config) { IsClosing = false; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexingService.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexingService.cs index 75bfd7e39aa..b68ba97708e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexingService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexingService.cs @@ -40,7 +40,8 @@ public LuceneIndexingService( LuceneIndexManager indexManager, IIndexingTaskManager indexingTaskManager, ISiteService siteService, - ILogger logger) + ILogger logger + ) { _shellHost = shellHost; _shellSettings = shellSettings; @@ -104,138 +105,149 @@ public async Task ProcessContentItemsAsync(string indexName = default) // Create a scope for the content manager. var shellScope = await _shellHost.GetScopeAsync(_shellSettings); - await shellScope.UsingAsync(async scope => - { - // Load the next batch of tasks. - batch = (await _indexingTaskManager.GetIndexingTasksAsync(lastTaskId, BatchSize)).ToArray(); - - if (batch.Length == 0) + await shellScope.UsingAsync( + async scope => { - return; - } - - var contentManager = scope.ServiceProvider.GetRequiredService(); - var indexHandlers = scope.ServiceProvider.GetServices(); + // Load the next batch of tasks. + batch = (await _indexingTaskManager.GetIndexingTasksAsync(lastTaskId, BatchSize)).ToArray(); - // Pre-load all content items to prevent SELECT N+1. - var updatedContentItemIds = batch - .Where(x => x.Type == IndexingTaskTypes.Update) - .Select(x => x.ContentItemId) - .ToArray(); - - var allPublished = new Dictionary(); - var allLatest = new Dictionary(); + if (batch.Length == 0) + { + return; + } - var allPublishedContentItems = await contentManager.GetAsync(updatedContentItemIds); - allPublished = allPublishedContentItems.DistinctBy(x => x.ContentItemId).ToDictionary(k => k.ContentItemId, v => v); - var allLatestContentItems = await contentManager.GetAsync(updatedContentItemIds, latest: true); - allLatest = allLatestContentItems.DistinctBy(x => x.ContentItemId).ToDictionary(k => k.ContentItemId, v => v); + var contentManager = scope.ServiceProvider.GetRequiredService(); + var indexHandlers = scope.ServiceProvider.GetServices(); - // Group all DocumentIndex by index to batch update them. - var updatedDocumentsByIndex = new Dictionary>(); + // Pre-load all content items to prevent SELECT N+1. + var updatedContentItemIds = batch.Where(x => x.Type == IndexingTaskTypes.Update).Select(x => x.ContentItemId).ToArray(); - foreach (var index in allIndices) - { - updatedDocumentsByIndex[index.Key] = []; - } + var allPublished = new Dictionary(); + var allLatest = new Dictionary(); - if (indexName != null) - { - indexSettingsList = indexSettingsList.Where(x => x.IndexName == indexName); - } + var allPublishedContentItems = await contentManager.GetAsync(updatedContentItemIds); + allPublished = allPublishedContentItems.DistinctBy(x => x.ContentItemId).ToDictionary(k => k.ContentItemId, v => v); + var allLatestContentItems = await contentManager.GetAsync(updatedContentItemIds, latest: true); + allLatest = allLatestContentItems.DistinctBy(x => x.ContentItemId).ToDictionary(k => k.ContentItemId, v => v); - var needLatest = indexSettingsList.FirstOrDefault(x => x.IndexLatest) != null; - var needPublished = indexSettingsList.FirstOrDefault(x => !x.IndexLatest) != null; + // Group all DocumentIndex by index to batch update them. + var updatedDocumentsByIndex = new Dictionary>(); - var settingsByIndex = indexSettingsList.ToDictionary(x => x.IndexName, x => x); + foreach (var index in allIndices) + { + updatedDocumentsByIndex[index.Key] = []; + } - foreach (var task in batch) - { - if (task.Type == IndexingTaskTypes.Update) + if (indexName != null) { - BuildIndexContext publishedIndexContext = null, latestIndexContext = null; + indexSettingsList = indexSettingsList.Where(x => x.IndexName == indexName); + } - if (needPublished) - { - allPublished.TryGetValue(task.ContentItemId, out var contentItem); + var needLatest = indexSettingsList.FirstOrDefault(x => x.IndexLatest) != null; + var needPublished = indexSettingsList.FirstOrDefault(x => !x.IndexLatest) != null; - if (contentItem != null) - { - publishedIndexContext = new BuildIndexContext(new DocumentIndex(task.ContentItemId, contentItem.ContentItemVersionId), contentItem, new string[] { contentItem.ContentType }, new LuceneContentIndexSettings()); - await indexHandlers.InvokeAsync(x => x.BuildIndexAsync(publishedIndexContext), _logger); - } - } + var settingsByIndex = indexSettingsList.ToDictionary(x => x.IndexName, x => x); - if (needLatest) + foreach (var task in batch) + { + if (task.Type == IndexingTaskTypes.Update) { - allLatest.TryGetValue(task.ContentItemId, out var contentItem); + BuildIndexContext publishedIndexContext = null, + latestIndexContext = null; - if (contentItem != null) + if (needPublished) { - latestIndexContext = new BuildIndexContext(new DocumentIndex(task.ContentItemId, contentItem.ContentItemVersionId), contentItem, new string[] { contentItem.ContentType }, new LuceneContentIndexSettings()); - await indexHandlers.InvokeAsync(x => x.BuildIndexAsync(latestIndexContext), _logger); + allPublished.TryGetValue(task.ContentItemId, out var contentItem); + + if (contentItem != null) + { + publishedIndexContext = new BuildIndexContext( + new DocumentIndex(task.ContentItemId, contentItem.ContentItemVersionId), + contentItem, + new string[] { contentItem.ContentType }, + new LuceneContentIndexSettings() + ); + await indexHandlers.InvokeAsync(x => x.BuildIndexAsync(publishedIndexContext), _logger); + } } - } - // Update the document from the index if its lastIndexId is smaller than the current task id. - foreach (var index in allIndices) - { - if (index.Value >= task.Id || !settingsByIndex.TryGetValue(index.Key, out var settings)) + if (needLatest) { - continue; + allLatest.TryGetValue(task.ContentItemId, out var contentItem); + + if (contentItem != null) + { + latestIndexContext = new BuildIndexContext( + new DocumentIndex(task.ContentItemId, contentItem.ContentItemVersionId), + contentItem, + new string[] { contentItem.ContentType }, + new LuceneContentIndexSettings() + ); + await indexHandlers.InvokeAsync(x => x.BuildIndexAsync(latestIndexContext), _logger); + } } - var context = !settings.IndexLatest ? publishedIndexContext : latestIndexContext; - - // We index only if we actually found a content item in the database. - if (context == null) + // Update the document from the index if its lastIndexId is smaller than the current task id. + foreach (var index in allIndices) { - // TODO purge these content items from IndexingTask table. - continue; + if (index.Value >= task.Id || !settingsByIndex.TryGetValue(index.Key, out var settings)) + { + continue; + } + + var context = !settings.IndexLatest ? publishedIndexContext : latestIndexContext; + + // We index only if we actually found a content item in the database. + if (context == null) + { + // TODO purge these content items from IndexingTask table. + continue; + } + + var cultureAspect = await contentManager.PopulateAspectAsync(context.ContentItem); + var culture = cultureAspect.HasCulture ? cultureAspect.Culture.Name : null; + var ignoreIndexedCulture = settings.Culture != "any" && culture != settings.Culture; + + // Ignore if the content item content type or culture is not indexed in this index. + if (!settings.IndexedContentTypes.Contains(context.ContentItem.ContentType) || ignoreIndexedCulture) + { + continue; + } + + updatedDocumentsByIndex[index.Key].Add(context.DocumentIndex); } - - var cultureAspect = await contentManager.PopulateAspectAsync(context.ContentItem); - var culture = cultureAspect.HasCulture ? cultureAspect.Culture.Name : null; - var ignoreIndexedCulture = settings.Culture != "any" && culture != settings.Culture; - - // Ignore if the content item content type or culture is not indexed in this index. - if (!settings.IndexedContentTypes.Contains(context.ContentItem.ContentType) || ignoreIndexedCulture) - { - continue; - } - - updatedDocumentsByIndex[index.Key].Add(context.DocumentIndex); } } - } - // Delete all the existing documents. - foreach (var index in updatedDocumentsByIndex) - { - var deletedDocuments = updatedDocumentsByIndex[index.Key].Select(x => x.ContentItemId); + // Delete all the existing documents. + foreach (var index in updatedDocumentsByIndex) + { + var deletedDocuments = updatedDocumentsByIndex[index.Key].Select(x => x.ContentItemId); - await _indexManager.DeleteDocumentsAsync(index.Key, deletedDocuments); - } + await _indexManager.DeleteDocumentsAsync(index.Key, deletedDocuments); + } - // Submits all the new documents to the index. - foreach (var index in updatedDocumentsByIndex) - { - await _indexManager.StoreDocumentsAsync(index.Key, updatedDocumentsByIndex[index.Key]); - } + // Submits all the new documents to the index. + foreach (var index in updatedDocumentsByIndex) + { + await _indexManager.StoreDocumentsAsync(index.Key, updatedDocumentsByIndex[index.Key]); + } - // Update task ids. - lastTaskId = batch.Last().Id; + // Update task ids. + lastTaskId = batch.Last().Id; - foreach (var indexStatus in allIndices) - { - if (indexStatus.Value < lastTaskId) + foreach (var indexStatus in allIndices) { - _indexingState.SetLastTaskId(indexStatus.Key, lastTaskId); + if (indexStatus.Value < lastTaskId) + { + _indexingState.SetLastTaskId(indexStatus.Key, lastTaskId); + } } - } - _indexingState.Update(); - }, activateShell: false); + _indexingState.Update(); + }, + activateShell: false + ); } while (batch.Length == BatchSize); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexingState.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexingState.cs index 6a1bdc67cb2..58879069b79 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexingState.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexingState.cs @@ -15,16 +15,14 @@ public class LuceneIndexingState private readonly string _indexSettingsFilename; private readonly JsonObject _content; - public LuceneIndexingState( - IOptions shellOptions, - ShellSettings shellSettings - ) + public LuceneIndexingState(IOptions shellOptions, ShellSettings shellSettings) { _indexSettingsFilename = PathExtensions.Combine( shellOptions.Value.ShellsApplicationDataPath, shellOptions.Value.ShellsContainerName, shellSettings.Name, - "lucene.status.json"); + "lucene.status.json" + ); if (!File.Exists(_indexSettingsFilename)) { diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneQuery.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneQuery.cs index 7813444c46a..31c35bce704 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneQuery.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneQuery.cs @@ -5,13 +5,13 @@ namespace OrchardCore.Search.Lucene { public class LuceneQuery : Query { - public LuceneQuery() : base("Lucene") - { - } + public LuceneQuery() + : base("Lucene") { } public string Index { get; set; } public string Template { get; set; } public bool ReturnContentItems { get; set; } + public override bool ResultsOfType() => ReturnContentItems ? typeof(T) == typeof(ContentItem) : base.ResultsOfType(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneQuerySource.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneQuerySource.cs index 20baddad7db..6b356aaafcb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneQuerySource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneQuerySource.cs @@ -36,7 +36,8 @@ public LuceneQuerySource( ILiquidTemplateManager liquidTemplateManager, ISession session, JavaScriptEncoder javaScriptEncoder, - IOptions templateOptions) + IOptions templateOptions + ) { _luceneIndexManager = luceneIndexManager; _luceneIndexSettingsService = luceneIndexSettingsService; @@ -60,46 +61,52 @@ public async Task ExecuteQueryAsync(Query query, IDictionary - { - var tokenizedContent = await _liquidTemplateManager.RenderStringAsync(luceneQuery.Template, _javaScriptEncoder, parameters.Select(x => new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions)))); + await _luceneIndexManager.SearchAsync( + luceneQuery.Index, + async searcher => + { + var tokenizedContent = await _liquidTemplateManager.RenderStringAsync( + luceneQuery.Template, + _javaScriptEncoder, + parameters.Select(x => new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions))) + ); - var parameterizedQuery = JsonNode.Parse(tokenizedContent).AsObject(); + var parameterizedQuery = JsonNode.Parse(tokenizedContent).AsObject(); - var analyzer = _luceneAnalyzerManager.CreateAnalyzer(await _luceneIndexSettingsService.GetIndexAnalyzerAsync(luceneQuery.Index)); - var context = new LuceneQueryContext(searcher, LuceneSettings.DefaultVersion, analyzer); - var docs = await _queryService.SearchAsync(context, parameterizedQuery); - luceneQueryResults.Count = docs.Count; + var analyzer = _luceneAnalyzerManager.CreateAnalyzer(await _luceneIndexSettingsService.GetIndexAnalyzerAsync(luceneQuery.Index)); + var context = new LuceneQueryContext(searcher, LuceneSettings.DefaultVersion, analyzer); + var docs = await _queryService.SearchAsync(context, parameterizedQuery); + luceneQueryResults.Count = docs.Count; - if (luceneQuery.ReturnContentItems) - { - // We always return an empty collection if the bottom lines queries have no results. - luceneQueryResults.Items = []; + if (luceneQuery.ReturnContentItems) + { + // We always return an empty collection if the bottom lines queries have no results. + luceneQueryResults.Items = []; - // Load corresponding content item versions - var indexedContentItemVersionIds = docs.TopDocs.ScoreDocs.Select(x => searcher.Doc(x.Doc).Get("ContentItemVersionId")).ToArray(); - var dbContentItems = await _session.Query(x => x.ContentItemVersionId.IsIn(indexedContentItemVersionIds)).ListAsync(); + // Load corresponding content item versions + var indexedContentItemVersionIds = docs.TopDocs.ScoreDocs.Select(x => searcher.Doc(x.Doc).Get("ContentItemVersionId")).ToArray(); + var dbContentItems = await _session.Query(x => x.ContentItemVersionId.IsIn(indexedContentItemVersionIds)).ListAsync(); - // Reorder the result to preserve the one from the lucene query - if (dbContentItems.Any()) - { - var dbContentItemVersionIds = dbContentItems.ToDictionary(x => x.ContentItemVersionId, x => x); - var indexedAndInDB = indexedContentItemVersionIds.Where(dbContentItemVersionIds.ContainsKey); - luceneQueryResults.Items = indexedAndInDB.Select(x => dbContentItemVersionIds[x]).ToArray(); + // Reorder the result to preserve the one from the lucene query + if (dbContentItems.Any()) + { + var dbContentItemVersionIds = dbContentItems.ToDictionary(x => x.ContentItemVersionId, x => x); + var indexedAndInDB = indexedContentItemVersionIds.Where(dbContentItemVersionIds.ContainsKey); + luceneQueryResults.Items = indexedAndInDB.Select(x => dbContentItemVersionIds[x]).ToArray(); + } } - } - else - { - var results = new List(); - foreach (var document in docs.TopDocs.ScoreDocs.Select(hit => searcher.Doc(hit.Doc))) + else { - results.Add(new JsonObject(document.Select(x => - KeyValuePair.Create(x.Name, (JsonNode)JsonValue.Create(x.GetStringValue()))))); - } + var results = new List(); + foreach (var document in docs.TopDocs.ScoreDocs.Select(hit => searcher.Doc(hit.Doc))) + { + results.Add(new JsonObject(document.Select(x => KeyValuePair.Create(x.Name, (JsonNode)JsonValue.Create(x.GetStringValue()))))); + } - luceneQueryResults.Items = results; + luceneQueryResults.Items = results; + } } - }); + ); return luceneQueryResults; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneSearchQueryService.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneSearchQueryService.cs index a3958366b06..90388fd4dfa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneSearchQueryService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneSearchQueryService.cs @@ -19,24 +19,27 @@ public async Task> ExecuteQueryAsync(Query query, string indexName { var contentItemIds = new List(); - await _luceneIndexManager.SearchAsync(indexName, searcher => - { - if (end > 0) + await _luceneIndexManager.SearchAsync( + indexName, + searcher => { - var collector = TopScoreDocCollector.Create(end, true); + if (end > 0) + { + var collector = TopScoreDocCollector.Create(end, true); - searcher.Search(query, collector); - var hits = collector.GetTopDocs(start, end); + searcher.Search(query, collector); + var hits = collector.GetTopDocs(start, end); - foreach (var hit in hits.ScoreDocs) - { - var d = searcher.Doc(hit.Doc, _idSet); - contentItemIds.Add(d.GetField("ContentItemId").GetStringValue()); + foreach (var hit in hits.ScoreDocs) + { + var d = searcher.Doc(hit.Doc, _idSet); + contentItemIds.Add(d.GetField("ContentItemId").GetStringValue()); + } } - } - return Task.CompletedTask; - }); + return Task.CompletedTask; + } + ); return contentItemIds; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneSearchService.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneSearchService.cs index c22c388e469..f16b73ca7f2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneSearchService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneSearchService.cs @@ -26,7 +26,8 @@ public LuceneSearchService( LuceneAnalyzerManager luceneAnalyzerManager, LuceneIndexSettingsService luceneIndexSettingsService, ILuceneSearchQueryService luceneSearchQueryService, - ILogger logger) + ILogger logger + ) { _siteService = siteService; _luceneIndexManager = luceneIndexManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentPartFieldIndexSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentPartFieldIndexSettingsDisplayDriver.cs index 5aa0d3d26b9..195d283776a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentPartFieldIndexSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentPartFieldIndexSettingsDisplayDriver.cs @@ -28,10 +28,14 @@ public override async Task EditAsync(ContentPartFieldDefinition return null; } - return Initialize("LuceneContentIndexSettings_Edit", model => - { - model.LuceneContentIndexSettings = contentPartFieldDefinition.GetSettings(); - }).Location("Content:10"); + return Initialize( + "LuceneContentIndexSettings_Edit", + model => + { + model.LuceneContentIndexSettings = contentPartFieldDefinition.GetSettings(); + } + ) + .Location("Content:10"); } public override async Task UpdateAsync(ContentPartFieldDefinition contentPartFieldDefinition, UpdatePartFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentPickerFieldLuceneEditorSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentPickerFieldLuceneEditorSettingsDriver.cs index 9447a0be542..a86fa727f24 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentPickerFieldLuceneEditorSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentPickerFieldLuceneEditorSettingsDriver.cs @@ -18,13 +18,16 @@ public ContentPickerFieldLuceneEditorSettingsDriver(LuceneIndexSettingsService l public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("ContentPickerFieldLuceneEditorSettings_Edit", async model => - { - var settings = partFieldDefinition.Settings.ToObject(); - - model.Index = settings.Index; - model.Indices = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - }) + return Initialize( + "ContentPickerFieldLuceneEditorSettings_Edit", + async model => + { + var settings = partFieldDefinition.Settings.ToObject(); + + model.Index = settings.Index; + model.Indices = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); + } + ) .Location("Editor"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentTypePartIndexSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentTypePartIndexSettingsDisplayDriver.cs index 1498a7a582c..228ae6ca4f5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentTypePartIndexSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Settings/ContentTypePartIndexSettingsDisplayDriver.cs @@ -28,10 +28,14 @@ public override async Task EditAsync(ContentTypePartDefinition c return null; } - return Initialize("LuceneContentIndexSettings_Edit", model => - { - model.LuceneContentIndexSettings = contentTypePartDefinition.GetSettings(); - }).Location("Content:10"); + return Initialize( + "LuceneContentIndexSettings_Edit", + model => + { + model.LuceneContentIndexSettings = contentTypePartDefinition.GetSettings(); + } + ) + .Location("Content:10"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Startup.cs index c1131e3a7b4..f21ca63be2d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Startup.cs @@ -1,3 +1,4 @@ +using System.Text.Json.Serialization; using Lucene.Net.Analysis.Standard; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.DependencyInjection; @@ -24,7 +25,6 @@ using OrchardCore.Search.Lucene.Settings; using OrchardCore.Security.Permissions; using OrchardCore.Settings; -using System.Text.Json.Serialization; namespace OrchardCore.Search.Lucene { @@ -43,9 +43,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); - services.Configure(o => - o.Analyzers.Add(new LuceneAnalyzer(LuceneSettings.StandardAnalyzer, - new StandardAnalyzer(LuceneSettings.DefaultVersion)))); + services.Configure(o => o.Analyzers.Add(new LuceneAnalyzer(LuceneSettings.StandardAnalyzer, new StandardAnalyzer(LuceneSettings.DefaultVersion)))); services.AddScoped, LuceneQueryDisplayDriver>(); diff --git a/src/OrchardCore.Modules/OrchardCore.Search/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Search/AdminMenu.cs index a6228821f19..e1f35f09c4b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search/AdminMenu.cs @@ -7,11 +7,7 @@ namespace OrchardCore.Search { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", SearchConstants.SearchSettingsGroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", SearchConstants.SearchSettingsGroupId }, }; protected readonly IStringLocalizer S; @@ -27,16 +23,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Search"], NavigationConstants.AdminMenuSearchPosition, search => search - .AddClass("search") - .Id("search") - .Add(S["Settings"], S["Settings"].PrefixPosition(), settings => settings - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageSearchSettings) - .LocalNav() - ) - ); + builder.Add( + S["Search"], + NavigationConstants.AdminMenuSearchPosition, + search => + search + .AddClass("search") + .Id("search") + .Add( + S["Settings"], + S["Settings"].PrefixPosition(), + settings => settings.Action("Index", "Admin", _routeValues).Permission(Permissions.ManageSearchSettings).LocalNav() + ) + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search/Controllers/SearchController.cs b/src/OrchardCore.Modules/OrchardCore.Search/Controllers/SearchController.cs index b6b1d00ade2..d050746bf8a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search/Controllers/SearchController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search/Controllers/SearchController.cs @@ -45,7 +45,7 @@ public SearchController( IEnumerable searchHandlers, IShapeFactory shapeFactory, ILogger logger - ) + ) { _authorizationService = authorizationService; _siteService = siteService; @@ -88,17 +88,19 @@ public async Task Search(SearchViewModel viewModel, PagerSlimPara if (string.IsNullOrWhiteSpace(viewModel.Terms)) { - return View(new SearchIndexViewModel() - { - Index = viewModel.Index, - PageTitle = searchSettings.PageTitle, - SearchForm = new SearchFormViewModel() + return View( + new SearchIndexViewModel() { - Terms = viewModel.Terms, - Placeholder = searchSettings.Placeholder, Index = viewModel.Index, + PageTitle = searchSettings.PageTitle, + SearchForm = new SearchFormViewModel() + { + Terms = viewModel.Terms, + Placeholder = searchSettings.Placeholder, + Index = viewModel.Index, + } } - }); + ); } var pager = new PagerSlim(pagerParameters, siteSettings.PageSize); @@ -133,22 +135,20 @@ public async Task Search(SearchViewModel viewModel, PagerSlimPara { await _searchHandlers.InvokeAsync((handler, context) => handler.SearchedAsync(context), searchContext, _logger); - return View(new SearchIndexViewModel() - { - Index = viewModel.Index, - PageTitle = searchSettings.PageTitle, - SearchForm = new SearchFormViewModel() + return View( + new SearchIndexViewModel() { - Terms = viewModel.Terms, - Placeholder = searchSettings.Placeholder, Index = viewModel.Index, - }, - SearchResults = new SearchResultsViewModel() - { - Index = viewModel.Index, - ContentItems = [], - }, - }); + PageTitle = searchSettings.PageTitle, + SearchForm = new SearchFormViewModel() + { + Terms = viewModel.Terms, + Placeholder = searchSettings.Placeholder, + Index = viewModel.Index, + }, + SearchResults = new SearchResultsViewModel() { Index = viewModel.Index, ContentItems = [], }, + } + ); } // Query the database to retrieve content items. @@ -156,13 +156,11 @@ public async Task Search(SearchViewModel viewModel, PagerSlimPara if (searchResult.Latest) { - query = _session.Query() - .Where(x => x.ContentItemId.IsIn(searchResult.ContentItemIds) && x.Latest); + query = _session.Query().Where(x => x.ContentItemId.IsIn(searchResult.ContentItemIds) && x.Latest); } else { - query = _session.Query() - .Where(x => x.ContentItemId.IsIn(searchResult.ContentItemIds) && x.Published); + query = _session.Query().Where(x => x.ContentItemId.IsIn(searchResult.ContentItemIds) && x.Published); } await _searchHandlers.InvokeAsync((handler, context) => handler.SearchedAsync(context), searchContext, _logger); @@ -202,15 +200,12 @@ public async Task Search(SearchViewModel viewModel, PagerSlimPara SearchResults = new SearchResultsViewModel() { Index = viewModel.Index, - ContentItems = containedItems.OrderBy(x => searchResult.ContentItemIds.IndexOf(x.ContentItemId)) - .Take(pager.PageSize) - .ToList(), + ContentItems = containedItems.OrderBy(x => searchResult.ContentItemIds.IndexOf(x.ContentItemId)).Take(pager.PageSize).ToList(), }, - Pager = await _shapeFactory.PagerSlimAsync(pager, new Dictionary() - { - { nameof(viewModel.Terms), viewModel.Terms }, - { nameof(viewModel.Index), viewModel.Index }, - }), + Pager = await _shapeFactory.PagerSlimAsync( + pager, + new Dictionary() { { nameof(viewModel.Terms), viewModel.Terms }, { nameof(viewModel.Index), viewModel.Index }, } + ), }; return View(shape); diff --git a/src/OrchardCore.Modules/OrchardCore.Search/Deployment/SearchSettingsDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Search/Deployment/SearchSettingsDeploymentSource.cs index 392dc578ab3..c01232d4d6e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search/Deployment/SearchSettingsDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search/Deployment/SearchSettingsDeploymentSource.cs @@ -27,11 +27,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan var settings = await _site.GetSiteSettingsAsync(); var searchSettings = settings.As(); - result.Steps.Add(new JsonObject - { - ["name"] = "Settings", - ["SearchSettings"] = JObject.FromObject(searchSettings), - }); + result.Steps.Add(new JsonObject { ["name"] = "Settings", ["SearchSettings"] = JObject.FromObject(searchSettings), }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search/Deployment/SearchSettingsDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search/Deployment/SearchSettingsDeploymentStepDriver.cs index 96b6e59a4f2..656308e2e2d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search/Deployment/SearchSettingsDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search/Deployment/SearchSettingsDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class SearchSettingsDeploymentStepDriver : DisplayDriver(GetEditorShapeType(context), viewModel => - { - viewModel.Placeholder = part.Placeholder; - viewModel.IndexName = part.IndexName; - }).Location("Content"); + return Initialize( + GetEditorShapeType(context), + viewModel => + { + viewModel.Placeholder = part.Placeholder; + viewModel.IndexName = part.IndexName; + } + ) + .Location("Content"); } public override async Task UpdateAsync(SearchFormPart part, IUpdateModel updater, UpdatePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Search/Drivers/SearchSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Search/Drivers/SearchSettingsDisplayDriver.cs index 392c46f310f..11d5ffc2cdd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search/Drivers/SearchSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search/Drivers/SearchSettingsDisplayDriver.cs @@ -25,11 +25,7 @@ public class SearchSettingsDisplayDriver : SectionDisplayDriver EditAsync(SearchSettings settings, Bu return null; } - return Initialize("SearchSettings_Edit", model => - { - var searchServices = _serviceProvider.GetServices(); + return Initialize( + "SearchSettings_Edit", + model => + { + var searchServices = _serviceProvider.GetServices(); - model.SearchServices = searchServices.Select(service => new SelectListItem(service.Name, service.Name)).ToList(); - model.Placeholder = settings.Placeholder; - model.PageTitle = settings.PageTitle; - model.ProviderName = settings.ProviderName; - }).Location("Content:2") - .OnGroup(SearchConstants.SearchSettingsGroupId); + model.SearchServices = searchServices.Select(service => new SelectListItem(service.Name, service.Name)).ToList(); + model.Placeholder = settings.Placeholder; + model.PageTitle = settings.PageTitle; + model.ProviderName = settings.ProviderName; + } + ) + .Location("Content:2") + .OnGroup(SearchConstants.SearchSettingsGroupId); } public override async Task UpdateAsync(SearchSettings section, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Search/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Search/Manifest.cs index 6484064da07..3411dea2f50 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search/Manifest.cs @@ -1,15 +1,5 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Search", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Search", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] -[assembly: Feature( - Id = "OrchardCore.Search", - Name = "Search", - Description = "The Search module adds frontend search capabilities.", - Category = "Search" -)] +[assembly: Feature(Id = "OrchardCore.Search", Name = "Search", Description = "The Search module adds frontend search capabilities.", Category = "Search")] diff --git a/src/OrchardCore.Modules/OrchardCore.Search/Migrations/SearchMigrations.cs b/src/OrchardCore.Modules/OrchardCore.Search/Migrations/SearchMigrations.cs index b7b19588e2d..727e03bb47f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search/Migrations/SearchMigrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search/Migrations/SearchMigrations.cs @@ -9,21 +9,15 @@ public class SearchMigrations : DataMigration { private readonly IContentDefinitionManager _contentDefinitionManager; - public SearchMigrations(IContentDefinitionManager contentDefinitionManager) - => _contentDefinitionManager = contentDefinitionManager; + public SearchMigrations(IContentDefinitionManager contentDefinitionManager) => _contentDefinitionManager = contentDefinitionManager; public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("SearchFormPart", part => part - .WithDisplayName("Search Form Part") - .Attachable() - ); + await _contentDefinitionManager.AlterPartDefinitionAsync("SearchFormPart", part => part.WithDisplayName("Search Form Part").Attachable()); - await _contentDefinitionManager.AlterTypeDefinitionAsync("SearchForm", type => type - .Stereotype("Widget") - .DisplayedAs("Search Form") - .WithDescription("Provides a search form") - .WithPart("SearchFormPart") + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "SearchForm", + type => type.Stereotype("Widget").DisplayedAs("Search Form").WithDescription("Provides a search form").WithPart("SearchFormPart") ); return 1; diff --git a/src/OrchardCore.Modules/OrchardCore.Search/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Search/Permissions.cs index d4227db57a3..66fe35101a5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search/Permissions.cs @@ -10,21 +10,9 @@ public class Permissions : IPermissionProvider public static readonly Permission ManageSearchSettings = new("ManageSearchSettings", "Manage Search Settings"); - private readonly IEnumerable _allPermissions = - [ - QuerySearchIndex, - ManageSearchSettings, - ]; + private readonly IEnumerable _allPermissions = [QuerySearchIndex, ManageSearchSettings,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search/Services/SearchSettingsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Search/Services/SearchSettingsConfiguration.cs index cb8ea451d30..7199f1a0517 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search/Services/SearchSettingsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search/Services/SearchSettingsConfiguration.cs @@ -15,9 +15,7 @@ public SearchSettingsConfiguration(ISiteService site) public void Configure(SearchSettings options) { - var settings = _site.GetSiteSettingsAsync() - .GetAwaiter().GetResult() - .As(); + var settings = _site.GetSiteSettingsAsync().GetAwaiter().GetResult().As(); options.ProviderName = settings.ProviderName; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Search/Startup.cs index 89151ad533f..044917ea74f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search/Startup.cs @@ -35,8 +35,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped, SearchSettingsDisplayDriver>(); - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddDataMigration(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Security/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Security/AdminMenu.cs index 86b14eccc1a..d63d233a749 100644 --- a/src/OrchardCore.Modules/OrchardCore.Security/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Security/AdminMenu.cs @@ -8,12 +8,7 @@ namespace OrchardCore.Security { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", SecuritySettingsDisplayDriver.SettingsGroupId }, - - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", SecuritySettingsDisplayDriver.SettingsGroupId }, }; protected readonly IStringLocalizer S; @@ -29,18 +24,23 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], NavigationConstants.AdminMenuSecurityPosition, security => security - .AddClass("security") - .Id("security") - .Add(S["Settings"], settings => settings - .Add(S["Security Headers"], S["Security Headers"].PrefixPosition(), headers => headers - .Permission(SecurityPermissions.ManageSecurityHeadersSettings) - .Action("Index", "Admin", _routeValues) - .LocalNav() + builder.Add( + S["Security"], + NavigationConstants.AdminMenuSecurityPosition, + security => + security + .AddClass("security") + .Id("security") + .Add( + S["Settings"], + settings => + settings.Add( + S["Security Headers"], + S["Security Headers"].PrefixPosition(), + headers => headers.Permission(SecurityPermissions.ManageSecurityHeadersSettings).Action("Index", "Admin", _routeValues).LocalNav() + ) ) - ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Security/Drivers/SecuritySettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Security/Drivers/SecuritySettingsDisplayDriver.cs index 1f6d6031c91..a84e528cad2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Security/Drivers/SecuritySettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Security/Drivers/SecuritySettingsDisplayDriver.cs @@ -28,7 +28,8 @@ public SecuritySettingsDisplayDriver( ShellSettings shellSettings, IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService, - IOptionsSnapshot securitySettings) + IOptionsSnapshot securitySettings + ) { _shellHost = shellHost; _shellSettings = shellSettings; @@ -46,26 +47,31 @@ public override async Task EditAsync(SecuritySettings settings, return null; } - return Initialize("SecurityHeadersSettings_Edit", model => - { - // Set the settings from configuration when AdminSettings are overriden via ConfigureSecuritySettings() - var currentSettings = settings; - if (_securitySettings.FromConfiguration) - { - currentSettings = _securitySettings; - } - - model.FromConfiguration = currentSettings.FromConfiguration; - model.ContentSecurityPolicy = currentSettings.ContentSecurityPolicy; - model.PermissionsPolicy = currentSettings.PermissionsPolicy; - model.ReferrerPolicy = currentSettings.ReferrerPolicy; - - model.EnableSandbox = currentSettings.ContentSecurityPolicy != null && - currentSettings.ContentSecurityPolicy.ContainsKey(ContentSecurityPolicyValue.Sandbox); - - model.UpgradeInsecureRequests = currentSettings.ContentSecurityPolicy != null && - currentSettings.ContentSecurityPolicy.ContainsKey(ContentSecurityPolicyValue.UpgradeInsecureRequests); - }).Location("Content:2").OnGroup(SettingsGroupId); + return Initialize( + "SecurityHeadersSettings_Edit", + model => + { + // Set the settings from configuration when AdminSettings are overriden via ConfigureSecuritySettings() + var currentSettings = settings; + if (_securitySettings.FromConfiguration) + { + currentSettings = _securitySettings; + } + + model.FromConfiguration = currentSettings.FromConfiguration; + model.ContentSecurityPolicy = currentSettings.ContentSecurityPolicy; + model.PermissionsPolicy = currentSettings.PermissionsPolicy; + model.ReferrerPolicy = currentSettings.ReferrerPolicy; + + model.EnableSandbox = + currentSettings.ContentSecurityPolicy != null && currentSettings.ContentSecurityPolicy.ContainsKey(ContentSecurityPolicyValue.Sandbox); + + model.UpgradeInsecureRequests = + currentSettings.ContentSecurityPolicy != null && currentSettings.ContentSecurityPolicy.ContainsKey(ContentSecurityPolicyValue.UpgradeInsecureRequests); + } + ) + .Location("Content:2") + .OnGroup(SettingsGroupId); } public override async Task UpdateAsync(SecuritySettings section, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Security/Extensions/OrchardCoreBuilderExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Security/Extensions/OrchardCoreBuilderExtensions.cs index 445ffc4fbb3..90d293c9f5d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Security/Extensions/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Security/Extensions/OrchardCoreBuilderExtensions.cs @@ -8,20 +8,22 @@ public static class OrchardCoreBuilderExtensions { public static OrchardCoreBuilder ConfigureSecuritySettings(this OrchardCoreBuilder builder) { - builder.ConfigureServices((tenantServices, serviceProvider) => - { - var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Security"); - - tenantServices.PostConfigure(settings => + builder.ConfigureServices( + (tenantServices, serviceProvider) => { - settings.ContentSecurityPolicy.Clear(); - settings.PermissionsPolicy.Clear(); + var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Security"); + + tenantServices.PostConfigure(settings => + { + settings.ContentSecurityPolicy.Clear(); + settings.PermissionsPolicy.Clear(); - configurationSection.Bind(settings); + configurationSection.Bind(settings); - settings.FromConfiguration = true; - }); - }); + settings.FromConfiguration = true; + }); + } + ); return builder; } diff --git a/src/OrchardCore.Modules/OrchardCore.Security/Options/SecurityHeadersOptions.cs b/src/OrchardCore.Modules/OrchardCore.Security/Options/SecurityHeadersOptions.cs index f09415cc030..fbfbf864cf2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Security/Options/SecurityHeadersOptions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Security/Options/SecurityHeadersOptions.cs @@ -30,9 +30,7 @@ public SecurityHeadersOptions() public SecurityHeadersOptions AddContentSecurityPolicy(Dictionary policies) { ContentSecurityPolicy = policies - .Where(kvp => kvp.Value != null || - kvp.Key == ContentSecurityPolicyValue.Sandbox || - kvp.Key == ContentSecurityPolicyValue.UpgradeInsecureRequests) + .Where(kvp => kvp.Value != null || kvp.Key == ContentSecurityPolicyValue.Sandbox || kvp.Key == ContentSecurityPolicyValue.UpgradeInsecureRequests) .Select(kvp => kvp.Key + (kvp.Value != null ? " " + kvp.Value : string.Empty)) .ToArray(); @@ -55,10 +53,7 @@ public SecurityHeadersOptions AddContentTypeOptions() public SecurityHeadersOptions AddPermissionsPolicy(IDictionary policies) { - PermissionsPolicy = policies - .Where(kvp => kvp.Value != PermissionsPolicyOriginValue.None) - .Select(kvp => kvp.Key + "=" + kvp.Value) - .ToArray(); + PermissionsPolicy = policies.Where(kvp => kvp.Value != PermissionsPolicyOriginValue.None).Select(kvp => kvp.Key + "=" + kvp.Value).ToArray(); return this; } diff --git a/src/OrchardCore.Modules/OrchardCore.Security/SecurityPermissions.cs b/src/OrchardCore.Modules/OrchardCore.Security/SecurityPermissions.cs index 7d6a5be17c7..d466b55fa6f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Security/SecurityPermissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Security/SecurityPermissions.cs @@ -8,20 +8,9 @@ public class SecurityPermissions : IPermissionProvider { public static readonly Permission ManageSecurityHeadersSettings = new("ManageSecurityHeadersSettings", "Manage Security Headers Settings"); - private readonly IEnumerable _allPermissions = - [ - ManageSecurityHeadersSettings, - ]; + private readonly IEnumerable _allPermissions = [ManageSecurityHeadersSettings,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Security/Services/SecuritySettingsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Security/Services/SecuritySettingsConfiguration.cs index 7d155643fa7..169e65e6719 100644 --- a/src/OrchardCore.Modules/OrchardCore.Security/Services/SecuritySettingsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Security/Services/SecuritySettingsConfiguration.cs @@ -7,13 +7,11 @@ public class SecuritySettingsConfiguration : IConfigureOptions { private readonly ISecurityService _securityService; - public SecuritySettingsConfiguration(ISecurityService securityService) - => _securityService = securityService; + public SecuritySettingsConfiguration(ISecurityService securityService) => _securityService = securityService; public void Configure(SecuritySettings options) { - var securitySettings = _securityService.GetSettingsAsync() - .GetAwaiter().GetResult(); + var securitySettings = _securityService.GetSettingsAsync().GetAwaiter().GetResult(); options.ContentSecurityPolicy = securitySettings.ContentSecurityPolicy; options.ContentTypeOptions = securitySettings.ContentTypeOptions; diff --git a/src/OrchardCore.Modules/OrchardCore.Security/Settings/SecuritySettings.cs b/src/OrchardCore.Modules/OrchardCore.Security/Settings/SecuritySettings.cs index 17318ead6ef..ca77bea6783 100644 --- a/src/OrchardCore.Modules/OrchardCore.Security/Settings/SecuritySettings.cs +++ b/src/OrchardCore.Modules/OrchardCore.Security/Settings/SecuritySettings.cs @@ -21,9 +21,7 @@ public Dictionary ContentSecurityPolicy // Exclude null values and clone the dictionary to not be shared by site settings and options instances. _contentSecurityPolicy = value - .Where(kvp => kvp.Value != null || - kvp.Key == ContentSecurityPolicyValue.Sandbox || - kvp.Key == ContentSecurityPolicyValue.UpgradeInsecureRequests) + .Where(kvp => kvp.Value != null || kvp.Key == ContentSecurityPolicyValue.Sandbox || kvp.Key == ContentSecurityPolicyValue.UpgradeInsecureRequests) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (_contentSecurityPolicy.TryGetValue(ContentSecurityPolicyValue.UpgradeInsecureRequests, out _)) @@ -46,9 +44,7 @@ public Dictionary PermissionsPolicy } // Exlude 'None' values and clone the dictionary to not be shared by site settings and options instances. - _permissionsPolicy = value - .Where(kvp => kvp.Value != PermissionsPolicyOriginValue.None) - .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + _permissionsPolicy = value.Where(kvp => kvp.Value != PermissionsPolicyOriginValue.None).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Security/ViewModels/SecuritySettingsViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Security/ViewModels/SecuritySettingsViewModel.cs index ea1a469addb..843885bbc2c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Security/ViewModels/SecuritySettingsViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Security/ViewModels/SecuritySettingsViewModel.cs @@ -16,11 +16,10 @@ public Dictionary ContentSecurityPolicy set { // Populate all policy values for the editor (null if not provided). - _contentSecurityPolicy = SecurityHeaderDefaults.ContentSecurityPolicyNames - .ToDictionary(name => name, name => - value?.ContainsKey(name) ?? false - ? value[name] - : null); + _contentSecurityPolicy = SecurityHeaderDefaults.ContentSecurityPolicyNames.ToDictionary( + name => name, + name => value?.ContainsKey(name) ?? false ? value[name] : null + ); } } @@ -34,11 +33,10 @@ public Dictionary PermissionsPolicy set { // Populate all policy values for the editor ('None' if not provided). - _permissionsPolicy = SecurityHeaderDefaults.PermissionsPolicyNames - .ToDictionary(name => name, name => - value?.ContainsKey(name) ?? false - ? value[name] - : PermissionsPolicyOriginValue.None); + _permissionsPolicy = SecurityHeaderDefaults.PermissionsPolicyNames.ToDictionary( + name => name, + name => value?.ContainsKey(name) ?? false ? value[name] : PermissionsPolicyOriginValue.None + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Seo/AdminMenu.cs index 451f62e55f8..df959483a39 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/AdminMenu.cs @@ -7,11 +7,7 @@ namespace OrchardCore.Seo; public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", SeoConstants.RobotsSettingsGroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", SeoConstants.RobotsSettingsGroupId }, }; protected readonly IStringLocalizer S; @@ -27,18 +23,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["SEO"], S["SEO"].PrefixPosition(), seo => seo - .AddClass("seo") - .Id("seo") - .Action("Index", "Admin", _routeValues) - .Permission(SeoConstants.ManageSeoSettings) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["SEO"], + S["SEO"].PrefixPosition(), + seo => seo.AddClass("seo").Id("seo").Action("Index", "Admin", _routeValues).Permission(SeoConstants.ManageSeoSettings).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/RobotsSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/RobotsSettingsDisplayDriver.cs index 4c3b7967737..7cb2118b000 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/RobotsSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/RobotsSettingsDisplayDriver.cs @@ -25,7 +25,8 @@ public RobotsSettingsDisplayDriver( IAuthorizationService authorizationService, IStaticFileProvider staticFileProvider, INotifier notifier, - IHtmlLocalizer htmlLocalizer) + IHtmlLocalizer htmlLocalizer + ) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -44,28 +45,36 @@ public override async Task EditAsync(RobotsSettings settings, Bu return null; } - return Initialize("RobotsSettings_Edit", async model => - { - var fileInfo = _staticFileProvider.GetFileInfo(SeoConstants.RobotsFileName); + return Initialize( + "RobotsSettings_Edit", + async model => + { + var fileInfo = _staticFileProvider.GetFileInfo(SeoConstants.RobotsFileName); - if (fileInfo.Exists) - { - await _notifier.WarningAsync(H["A physical {0} file is found for the current site. Until removed, the settings below will have no effect.", SeoConstants.RobotsFileName]); - } + if (fileInfo.Exists) + { + await _notifier.WarningAsync( + H["A physical {0} file is found for the current site. Until removed, the settings below will have no effect.", SeoConstants.RobotsFileName] + ); + } - model.AllowAllAgents = settings.AllowAllAgents; - model.DisallowAdmin = settings.DisallowAdmin; - model.AdditionalRules = settings.AdditionalRules; - }).Location("Content:5") - .OnGroup(SeoConstants.RobotsSettingsGroupId); + model.AllowAllAgents = settings.AllowAllAgents; + model.DisallowAdmin = settings.DisallowAdmin; + model.AdditionalRules = settings.AdditionalRules; + } + ) + .Location("Content:5") + .OnGroup(SeoConstants.RobotsSettingsGroupId); } public override async Task UpdateAsync(RobotsSettings settings, BuildEditorContext context) { var user = _httpContextAccessor.HttpContext?.User; - if (!context.GroupId.Equals(SeoConstants.RobotsSettingsGroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(user, SeoConstants.ManageSeoSettings)) + if ( + !context.GroupId.Equals(SeoConstants.RobotsSettingsGroupId, StringComparison.OrdinalIgnoreCase) + || !await _authorizationService.AuthorizeAsync(user, SeoConstants.ManageSeoSettings) + ) { return null; } diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/SeoContentDriver.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/SeoContentDriver.cs index 63a705709c0..54c1b78a336 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/SeoContentDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/SeoContentDriver.cs @@ -32,7 +32,7 @@ public SeoContentDriver( IResourceManager resourceManager, IShortcodeService shortcodeService, HtmlEncoder htmlEncoder - ) + ) { _contentManager = contentManager; _pageTitleBuilder = pageTitleBuilder; @@ -64,10 +64,7 @@ public override async Task DisplayAsync(ContentItem contentItem, return null; } - var shortCodeContext = new Context - { - ["ContentItem"] = contentItem - }; + var shortCodeContext = new Context { ["ContentItem"] = contentItem }; if (!string.IsNullOrEmpty(aspect.PageTitle)) { @@ -76,204 +73,167 @@ public override async Task DisplayAsync(ContentItem contentItem, if (!string.IsNullOrEmpty(aspect.MetaDescription)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Name = "description", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.MetaDescription, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Name = "description", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.MetaDescription, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.MetaKeywords)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Name = "keywords", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.MetaKeywords, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Name = "keywords", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.MetaKeywords, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.Canonical)) { - _resourceManager.RegisterLink(new LinkEntry - { - Href = aspect.Canonical, - Rel = "canonical" - }); + _resourceManager.RegisterLink(new LinkEntry { Href = aspect.Canonical, Rel = "canonical" }); } if (!string.IsNullOrEmpty(aspect.MetaRobots)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Name = "robots", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.MetaRobots, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Name = "robots", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.MetaRobots, shortCodeContext)) } + ); } foreach (var customMetaTag in aspect.CustomMetaTags) { // Generate a new meta entry as the builder is preopulated. - _resourceManager.RegisterMeta(new MetaEntry( - _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(customMetaTag.Name, shortCodeContext)), - _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(customMetaTag.Property, shortCodeContext)), - _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(customMetaTag.Content, shortCodeContext)), - _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(customMetaTag.HttpEquiv, shortCodeContext)), - _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(customMetaTag.Charset, shortCodeContext)))); + _resourceManager.RegisterMeta( + new MetaEntry( + _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(customMetaTag.Name, shortCodeContext)), + _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(customMetaTag.Property, shortCodeContext)), + _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(customMetaTag.Content, shortCodeContext)), + _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(customMetaTag.HttpEquiv, shortCodeContext)), + _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(customMetaTag.Charset, shortCodeContext)) + ) + ); } // OpenGraph. if (!string.IsNullOrEmpty(aspect.OpenGraphType)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "og:type", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphType, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Property = "og:type", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphType, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.OpenGraphTitle)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "og:title", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphTitle, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Property = "og:title", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphTitle, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.OpenGraphDescription)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "og:description", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphDescription, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry + { + Property = "og:description", + Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphDescription, shortCodeContext)) + } + ); } if (!string.IsNullOrEmpty(aspect.OpenGraphImage)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "og:image", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphImage, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Property = "og:image", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphImage, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.OpenGraphImageAlt)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "og:image:alt", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphImageAlt, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Property = "og:image:alt", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphImageAlt, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.OpenGraphUrl)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "og:url", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphUrl, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Property = "og:url", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphUrl, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.OpenGraphSiteName)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "og:site_name", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphSiteName, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Property = "og:site_name", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphSiteName, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.OpenGraphAppId)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "fb:app_id", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphAppId, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Property = "fb:app_id", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphAppId, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.OpenGraphLocale)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "og:locale", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphLocale, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Property = "og:locale", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.OpenGraphLocale, shortCodeContext)) } + ); } // Twitter. if (!string.IsNullOrEmpty(aspect.TwitterCard)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "twitter:card", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterCard, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Property = "twitter:card", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterCard, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.TwitterSite)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Property = "twitter:site", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterSite, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Property = "twitter:site", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterSite, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.TwitterTitle)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Name = "twitter:title", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterTitle, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Name = "twitter:title", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterTitle, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.TwitterDescription)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Name = "twitter:description", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterDescription, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Name = "twitter:description", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterDescription, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.TwitterImage)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Name = "twitter:image", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterImage, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Name = "twitter:image", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterImage, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.TwitterImageAlt)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Name = "twitter:image:alt", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterImageAlt, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Name = "twitter:image:alt", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterImageAlt, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.TwitterCreator)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Name = "twitter:creator", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterCreator, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Name = "twitter:creator", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterCreator, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.TwitterUrl)) { - _resourceManager.RegisterMeta(new MetaEntry - { - Name = "twitter:url", - Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterUrl, shortCodeContext)) - }); + _resourceManager.RegisterMeta( + new MetaEntry { Name = "twitter:url", Content = _htmlEncoder.Encode(await _shortcodeService.ProcessAsync(aspect.TwitterUrl, shortCodeContext)) } + ); } if (!string.IsNullOrEmpty(aspect.GoogleSchema)) @@ -291,7 +251,6 @@ public override async Task DisplayAsync(ContentItem contentItem, } _resourceManager.RegisterHeadScript(new HtmlString($"")); - } return null; diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/SeoMetaPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/SeoMetaPartDisplayDriver.cs index fe5a65157b3..bd17624591e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/SeoMetaPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Drivers/SeoMetaPartDisplayDriver.cs @@ -28,51 +28,73 @@ public override IDisplayResult Edit(SeoMetaPart part, BuildPartEditorContext con var results = new List { - Initialize("SeoMetaPart_Edit", model => - { - model.PageTitle = part.PageTitle; - model.Render = part.Render; - model.MetaDescription = part.MetaDescription; - model.MetaKeywords = part.MetaKeywords; - model.Canonical = part.Canonical; - model.MetaRobots = part.MetaRobots; - model.CustomMetaTags = JConvert.SerializeObject(part.CustomMetaTags, JOptions.CamelCaseIndented); - model.SeoMetaPart = part; - model.Settings = settings; - }).Location("Parts#SEO;50"), + Initialize( + "SeoMetaPart_Edit", + model => + { + model.PageTitle = part.PageTitle; + model.Render = part.Render; + model.MetaDescription = part.MetaDescription; + model.MetaKeywords = part.MetaKeywords; + model.Canonical = part.Canonical; + model.MetaRobots = part.MetaRobots; + model.CustomMetaTags = JConvert.SerializeObject(part.CustomMetaTags, JOptions.CamelCaseIndented); + model.SeoMetaPart = part; + model.Settings = settings; + } + ) + .Location("Parts#SEO;50"), }; if (settings.DisplayOpenGraph) { - results.Add(Initialize("SeoMetaPartOpenGraph_Edit", model => - { - model.OpenGraphType = part.OpenGraphType; - model.OpenGraphTitle = part.OpenGraphTitle; - model.OpenGraphDescription = part.OpenGraphDescription; - model.SeoMetaPart = part; - }).Location("Parts#SEO;50%Open Graph;20")); + results.Add( + Initialize( + "SeoMetaPartOpenGraph_Edit", + model => + { + model.OpenGraphType = part.OpenGraphType; + model.OpenGraphTitle = part.OpenGraphTitle; + model.OpenGraphDescription = part.OpenGraphDescription; + model.SeoMetaPart = part; + } + ) + .Location("Parts#SEO;50%Open Graph;20") + ); } if (settings.DisplayTwitter) { - results.Add(Initialize("SeoMetaPartTwitter_Edit", model => - { - model.TwitterTitle = part.TwitterTitle; - model.TwitterDescription = part.TwitterDescription; - model.TwitterCard = part.TwitterCard; - model.TwitterCreator = part.TwitterCreator; - model.TwitterSite = part.TwitterSite; - model.SeoMetaPart = part; - }).Location("Parts#SEO;50%Twitter;30")); + results.Add( + Initialize( + "SeoMetaPartTwitter_Edit", + model => + { + model.TwitterTitle = part.TwitterTitle; + model.TwitterDescription = part.TwitterDescription; + model.TwitterCard = part.TwitterCard; + model.TwitterCreator = part.TwitterCreator; + model.TwitterSite = part.TwitterSite; + model.SeoMetaPart = part; + } + ) + .Location("Parts#SEO;50%Twitter;30") + ); } if (settings.DisplayGoogleSchema) { - results.Add(Initialize("SeoMetaPartGoogleSchema_Edit", model => - { - model.GoogleSchema = part.GoogleSchema; - model.SeoMetaPart = part; - }).Location("Parts#SEO;50%Google Schema;40")); + results.Add( + Initialize( + "SeoMetaPartGoogleSchema_Edit", + model => + { + model.GoogleSchema = part.GoogleSchema; + model.SeoMetaPart = part; + } + ) + .Location("Parts#SEO;50%Google Schema;40") + ); } return Combine(results); @@ -92,9 +114,7 @@ public override async Task UpdateAsync(SeoMetaPart part, IUpdate part.Canonical = partViewModel.Canonical; part.MetaRobots = partViewModel.MetaRobots; - part.CustomMetaTags = string.IsNullOrWhiteSpace(partViewModel.CustomMetaTags) - ? [] - : JConvert.DeserializeObject(partViewModel.CustomMetaTags); + part.CustomMetaTags = string.IsNullOrWhiteSpace(partViewModel.CustomMetaTags) ? [] : JConvert.DeserializeObject(partViewModel.CustomMetaTags); if (part.Canonical?.IndexOfAny(SeoMetaPart.InvalidCharactersForCanoncial) > -1 || part.Canonical?.IndexOf(' ') > -1) { diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/GraphQL/MetaEntryQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Seo/GraphQL/MetaEntryQueryObjectType.cs index b5cbb860867..2a75e335795 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/GraphQL/MetaEntryQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/GraphQL/MetaEntryQueryObjectType.cs @@ -13,16 +13,11 @@ public MetaEntryQueryObjectType(IStringLocalizer S) Name = nameof(MetaEntry); Description = S["Meta entry"]; - Field(x => x.Name) - .Description("Name of the meta entry"); - Field(x => x.Property) - .Description("Property of the meta entry"); - Field(x => x.Content) - .Description("Content of the meta entry"); - Field(x => x.HttpEquiv) - .Description("HttpEquiv of the meta entry"); - Field(x => x.Charset) - .Description("Charset of the meta entry"); + Field(x => x.Name).Description("Name of the meta entry"); + Field(x => x.Property).Description("Property of the meta entry"); + Field(x => x.Content).Description("Content of the meta entry"); + Field(x => x.HttpEquiv).Description("HttpEquiv of the meta entry"); + Field(x => x.Charset).Description("Charset of the meta entry"); Field("Tag") .Description("The generated tag of the meta entry") .Resolve(ctx => diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/GraphQL/SeoMetaQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Seo/GraphQL/SeoMetaQueryObjectType.cs index ebac25eff70..5862ae69f09 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/GraphQL/SeoMetaQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/GraphQL/SeoMetaQueryObjectType.cs @@ -12,51 +12,31 @@ public SeoMetaQueryObjectType(IStringLocalizer S) Name = nameof(SeoMetaPart); Description = S["SEO meta fields"]; - Field(x => x.Render) - .Description("Whether to render the seo metas"); - Field(x => x.PageTitle, true) - .Description("The seo page title"); - Field(x => x.MetaDescription, true) - .Description("The meta description of the content item"); - Field(x => x.MetaKeywords, true) - .Description("The meta keywords of the content item"); - Field(x => x.Canonical, true) - .Description("The canonical link of the content item"); - Field(x => x.MetaRobots, true) - .Description("The content item specific meta robots definition"); - - Field>("customMetaTags") - .Resolve(ctx => ctx.Source.CustomMetaTags); - - Field>("defaultSocialImage") - .Resolve(ctx => ctx.Source.DefaultSocialImage); - - Field>("openGraphImage") - .Resolve(ctx => ctx.Source.OpenGraphImage); - - Field(x => x.OpenGraphType, true) - .Description("The seo meta opengraph type"); - Field(x => x.OpenGraphTitle, true) - .Description("The seo meta opengraph title"); - Field(x => x.OpenGraphDescription, true) - .Description("The seo meta opengraph description"); - - Field>("twitterImage") - .Resolve(ctx => ctx.Source.TwitterImage); - - Field(x => x.TwitterTitle, true) - .Description("The seo meta twitter title"); - Field(x => x.TwitterDescription, true) - .Description("The seo meta twitter description"); - Field(x => x.TwitterCard, true) - .Description("The seo meta twitter card"); - Field(x => x.TwitterCreator, true) - .Description("The seo meta twitter creator"); - Field(x => x.TwitterSite, true) - .Description("The seo meta twitter site"); - - Field(x => x.GoogleSchema, true) - .Description("The seo meta google schema"); + Field(x => x.Render).Description("Whether to render the seo metas"); + Field(x => x.PageTitle, true).Description("The seo page title"); + Field(x => x.MetaDescription, true).Description("The meta description of the content item"); + Field(x => x.MetaKeywords, true).Description("The meta keywords of the content item"); + Field(x => x.Canonical, true).Description("The canonical link of the content item"); + Field(x => x.MetaRobots, true).Description("The content item specific meta robots definition"); + Field>("customMetaTags").Resolve(ctx => ctx.Source.CustomMetaTags); + + Field>("defaultSocialImage").Resolve(ctx => ctx.Source.DefaultSocialImage); + + Field>("openGraphImage").Resolve(ctx => ctx.Source.OpenGraphImage); + + Field(x => x.OpenGraphType, true).Description("The seo meta opengraph type"); + Field(x => x.OpenGraphTitle, true).Description("The seo meta opengraph title"); + Field(x => x.OpenGraphDescription, true).Description("The seo meta opengraph description"); + + Field>("twitterImage").Resolve(ctx => ctx.Source.TwitterImage); + + Field(x => x.TwitterTitle, true).Description("The seo meta twitter title"); + Field(x => x.TwitterDescription, true).Description("The seo meta twitter description"); + Field(x => x.TwitterCard, true).Description("The seo meta twitter card"); + Field(x => x.TwitterCreator, true).Description("The seo meta twitter creator"); + Field(x => x.TwitterSite, true).Description("The seo meta twitter site"); + + Field(x => x.GoogleSchema, true).Description("The seo meta google schema"); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Handlers/SeoMetaPartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Handlers/SeoMetaPartHandler.cs index 2854c4aa8e9..4a80b075d45 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Handlers/SeoMetaPartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Handlers/SeoMetaPartHandler.cs @@ -32,7 +32,7 @@ public SeoMetaPartHandler( IHttpContextAccessor httpContextAccessor, IUrlHelperFactory urlHelperFactory, IContentManager contentManager - ) + ) { _mediaFileStore = mediaFileStore; _siteService = siteService; diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Handlers/SeoMetaSettingsHandler.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Handlers/SeoMetaSettingsHandler.cs index 855f96617ca..62aeda904aa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Handlers/SeoMetaSettingsHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Handlers/SeoMetaSettingsHandler.cs @@ -32,7 +32,7 @@ public SeoMetaSettingsHandler( IActionContextAccessor actionContextAccessor, IHttpContextAccessor httpContextAccessor, IUrlHelperFactory urlHelperFactory - ) + ) { _mediaFileStore = mediaFileStore; _siteService = siteService; @@ -64,13 +64,27 @@ public override Task GetContentItemAspectAsync(ContentItemAspectContext context) // Logic is this happens last after the part settings. // so if values are not set it is responsible for settings them. - string defaultImage = metaSettings.Content.SocialMetaSettings?.DefaultSocialImage?.Paths?.Count > 0 ? metaSettings.Content.SocialMetaSettings.DefaultSocialImage.Paths[0] : string.Empty; - string openGraphImage = metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.Paths?.Count > 0 ? metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.Paths[0] : string.Empty; - string twitterImage = metaSettings.Content.SocialMetaSettings?.TwitterImage?.Paths?.Count > 0 ? metaSettings.Content.SocialMetaSettings?.TwitterImage?.Paths[0] : string.Empty; - - string defaultAltText = metaSettings.Content.SocialMetaSettings?.DefaultSocialImage?.MediaTexts?.Count > 0 ? metaSettings.Content.SocialMetaSettings.DefaultSocialImage.MediaTexts[0] : string.Empty; - string openGraphAltText = metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.MediaTexts?.Count > 0 ? metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.MediaTexts[0] : string.Empty; - string twitterAltText = metaSettings.Content.SocialMetaSettings?.TwitterImage?.MediaTexts?.Count > 0 ? metaSettings.Content.SocialMetaSettings?.TwitterImage?.MediaTexts[0] : string.Empty; + string defaultImage = + metaSettings.Content.SocialMetaSettings?.DefaultSocialImage?.Paths?.Count > 0 + ? metaSettings.Content.SocialMetaSettings.DefaultSocialImage.Paths[0] + : string.Empty; + string openGraphImage = + metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.Paths?.Count > 0 ? metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.Paths[0] : string.Empty; + string twitterImage = + metaSettings.Content.SocialMetaSettings?.TwitterImage?.Paths?.Count > 0 ? metaSettings.Content.SocialMetaSettings?.TwitterImage?.Paths[0] : string.Empty; + + string defaultAltText = + metaSettings.Content.SocialMetaSettings?.DefaultSocialImage?.MediaTexts?.Count > 0 + ? metaSettings.Content.SocialMetaSettings.DefaultSocialImage.MediaTexts[0] + : string.Empty; + string openGraphAltText = + metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.MediaTexts?.Count > 0 + ? metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.MediaTexts[0] + : string.Empty; + string twitterAltText = + metaSettings.Content.SocialMetaSettings?.TwitterImage?.MediaTexts?.Count > 0 + ? metaSettings.Content.SocialMetaSettings?.TwitterImage?.MediaTexts[0] + : string.Empty; string twitterCard = metaSettings.Content.SocialMetaSettings?.TwitterCard?.Text?.ToString(); string twitterCreator = metaSettings.Content.SocialMetaSettings?.TwitterCreator?.Text?.ToString(); diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Indexes/SeoMetaPartContentIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Indexes/SeoMetaPartContentIndexHandler.cs index 4045cb57f14..d65a3f85b81 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Indexes/SeoMetaPartContentIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Indexes/SeoMetaPartContentIndexHandler.cs @@ -20,20 +20,11 @@ public Task BuildIndexAsync(BuildIndexContext context) return Task.CompletedTask; } - context.DocumentIndex.Set( - PageTitleKey, - parent.PageTitle, - DocumentIndexOptions.Store); - - context.DocumentIndex.Set( - MetaDescriptionKey, - parent.MetaDescription, - DocumentIndexOptions.Store); - - context.DocumentIndex.Set( - MetaKeywordsKey, - parent.MetaKeywords, - DocumentIndexOptions.Store); + context.DocumentIndex.Set(PageTitleKey, parent.PageTitle, DocumentIndexOptions.Store); + + context.DocumentIndex.Set(MetaDescriptionKey, parent.MetaDescription, DocumentIndexOptions.Store); + + context.DocumentIndex.Set(MetaKeywordsKey, parent.MetaKeywords, DocumentIndexOptions.Store); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Manifest.cs index d2e04caca45..4d913212b6b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Manifest.cs @@ -7,10 +7,5 @@ Version = ManifestConstants.OrchardCoreVersion, Description = "Provides SEO meta features", Category = "Content Management", - Dependencies = - [ - "OrchardCore.Contents", - "OrchardCore.Recipes.Core", - "OrchardCore.Media", - ] + Dependencies = ["OrchardCore.Contents", "OrchardCore.Recipes.Core", "OrchardCore.Media",] )] diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Migrations.cs index cc64d43382f..94179ef0afb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Migrations.cs @@ -21,21 +21,21 @@ public Migrations(IContentDefinitionManager contentDefinitionManager, IRecipeMig public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("SeoMetaPart", builder => builder - .Attachable() - .WithDescription("Provides a part that allows SEO meta descriptions to be applied to a content item.") - .WithField("DefaultSocialImage", field => field - .OfType("MediaField") - .WithDisplayName("Default social image") - .WithSettings(new MediaFieldSettings { Multiple = false })) - .WithField("OpenGraphImage", field => field - .OfType("MediaField") - .WithDisplayName("Open graph image") - .WithSettings(new MediaFieldSettings { Multiple = false })) - .WithField("TwitterImage", field => field - .OfType("MediaField") - .WithDisplayName("Twitter image") - .WithSettings(new MediaFieldSettings { Multiple = false })) + await _contentDefinitionManager.AlterPartDefinitionAsync( + "SeoMetaPart", + builder => + builder + .Attachable() + .WithDescription("Provides a part that allows SEO meta descriptions to be applied to a content item.") + .WithField( + "DefaultSocialImage", + field => field.OfType("MediaField").WithDisplayName("Default social image").WithSettings(new MediaFieldSettings { Multiple = false }) + ) + .WithField( + "OpenGraphImage", + field => field.OfType("MediaField").WithDisplayName("Open graph image").WithSettings(new MediaFieldSettings { Multiple = false }) + ) + .WithField("TwitterImage", field => field.OfType("MediaField").WithDisplayName("Twitter image").WithSettings(new MediaFieldSettings { Multiple = false })) ); await _recipeMigrator.ExecuteAsync("socialmetasettings.recipe.json", this); diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Models/SeoMetaPart.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Models/SeoMetaPart.cs index aea656f5afe..e66f5a3aaa6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Models/SeoMetaPart.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Models/SeoMetaPart.cs @@ -22,10 +22,8 @@ public class SeoMetaPart : ContentPart public string MetaRobots { get; set; } public MetaEntry[] CustomMetaTags { get; set; } = []; - public MediaField DefaultSocialImage { get; set; } - public MediaField OpenGraphImage { get; set; } public string OpenGraphType { get; set; } public string OpenGraphTitle { get; set; } diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/SeoPermissionProvider.cs b/src/OrchardCore.Modules/OrchardCore.Seo/SeoPermissionProvider.cs index 189f5cef01d..fe2cbe328b7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/SeoPermissionProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/SeoPermissionProvider.cs @@ -8,20 +8,9 @@ public class SeoPermissionProvider : IPermissionProvider { public static readonly Permission ManageSeoSettings = SeoConstants.ManageSeoSettings; - private readonly IEnumerable _allPermissions = - [ - ManageSeoSettings, - ]; + private readonly IEnumerable _allPermissions = [ManageSeoSettings,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Services/RobotsMiddleware.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Services/RobotsMiddleware.cs index 74dee85be88..6b88d3bd00d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Services/RobotsMiddleware.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Services/RobotsMiddleware.cs @@ -15,10 +15,7 @@ public class RobotsMiddleware private readonly IStaticFileProvider _staticFileProvider; private readonly IEnumerable _robotsProviders; - public RobotsMiddleware( - RequestDelegate next, - IStaticFileProvider staticFileProvider, - IEnumerable robotsProviders) + public RobotsMiddleware(RequestDelegate next, IStaticFileProvider staticFileProvider, IEnumerable robotsProviders) { _next = next; _staticFileProvider = staticFileProvider; diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Services/SiteSettingsRobotsProvider.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Services/SiteSettingsRobotsProvider.cs index 2ab7ce3eecc..0be7bdfad54 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Services/SiteSettingsRobotsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Services/SiteSettingsRobotsProvider.cs @@ -11,9 +11,7 @@ public class SiteSettingsRobotsProvider : IRobotsProvider private readonly ISiteService _siteService; private readonly AdminOptions _adminOptions; - public SiteSettingsRobotsProvider( - ISiteService siteService, - IOptions adminOptions) + public SiteSettingsRobotsProvider(ISiteService siteService, IOptions adminOptions) { _siteService = siteService; _adminOptions = adminOptions.Value; diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Settings/SeoMetaPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Settings/SeoMetaPartSettingsDisplayDriver.cs index e325adb8988..ef0b87ecb8c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Settings/SeoMetaPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Settings/SeoMetaPartSettingsDisplayDriver.cs @@ -12,37 +12,46 @@ public class SeoMetaPartSettingsDisplayDriver : ContentTypePartDefinitionDisplay { public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("SeoMetaPartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + "SeoMetaPartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); - model.DisplayKeywords = settings.DisplayKeywords; - model.DisplayCustomMetaTags = settings.DisplayCustomMetaTags; - model.DisplayOpenGraph = settings.DisplayOpenGraph; - model.DisplayTwitter = settings.DisplayTwitter; - model.DisplayGoogleSchema = settings.DisplayGoogleSchema; - }).Location("Content"); + model.DisplayKeywords = settings.DisplayKeywords; + model.DisplayCustomMetaTags = settings.DisplayCustomMetaTags; + model.DisplayOpenGraph = settings.DisplayOpenGraph; + model.DisplayTwitter = settings.DisplayTwitter; + model.DisplayGoogleSchema = settings.DisplayGoogleSchema; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) { var model = new SeoMetaPartSettingsViewModel(); - await context.Updater.TryUpdateModelAsync(model, Prefix, + await context.Updater.TryUpdateModelAsync( + model, + Prefix, m => m.DisplayKeywords, m => m.DisplayCustomMetaTags, m => m.DisplayOpenGraph, m => m.DisplayTwitter, - m => m.DisplayGoogleSchema); + m => m.DisplayGoogleSchema + ); - context.Builder.WithSettings(new SeoMetaPartSettings - { - DisplayKeywords = model.DisplayKeywords, - DisplayCustomMetaTags = model.DisplayCustomMetaTags, - DisplayOpenGraph = model.DisplayOpenGraph, - DisplayTwitter = model.DisplayTwitter, - DisplayGoogleSchema = model.DisplayGoogleSchema - }); + context.Builder.WithSettings( + new SeoMetaPartSettings + { + DisplayKeywords = model.DisplayKeywords, + DisplayCustomMetaTags = model.DisplayCustomMetaTags, + DisplayOpenGraph = model.DisplayOpenGraph, + DisplayTwitter = model.DisplayTwitter, + DisplayGoogleSchema = model.DisplayGoogleSchema + } + ); return Edit(contentTypePartDefinition, context.Updater); } diff --git a/src/OrchardCore.Modules/OrchardCore.Seo/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Seo/Startup.cs index e7a29994e1f..0081775a13d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Seo/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Seo/Startup.cs @@ -27,9 +27,7 @@ public override void ConfigureServices(IServiceCollection services) { services.AddDataMigration(); - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Settings/AdminMenu.cs index 7c891fc4635..e55c0336724 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/AdminMenu.cs @@ -8,11 +8,7 @@ namespace OrchardCore.Settings { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", DefaultSiteSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", DefaultSiteSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -28,20 +24,25 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], NavigationConstants.AdminMenuConfigurationPosition, configuration => configuration - .AddClass("menu-configuration") - .Id("configuration") - .Add(S["Settings"], "1", settings => settings - .Add(S["General"], "1", entry => entry - .AddClass("general") - .Id("general") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageGroupSettings) - .LocalNav() - ), - priority: 1) - ); + builder.Add( + S["Configuration"], + NavigationConstants.AdminMenuConfigurationPosition, + configuration => + configuration + .AddClass("menu-configuration") + .Id("configuration") + .Add( + S["Settings"], + "1", + settings => + settings.Add( + S["General"], + "1", + entry => entry.AddClass("general").Id("general").Action("Index", "Admin", _routeValues).Permission(Permissions.ManageGroupSettings).LocalNav() + ), + priority: 1 + ) + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Settings/Controllers/AdminController.cs index fac76003b44..a0589990f1f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/Controllers/AdminController.cs @@ -30,7 +30,8 @@ public AdminController( INotifier notifier, IHtmlLocalizer h, IOptions cultureOptions, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _siteSettingsDisplayManager = siteSettingsDisplayManager; _siteService = siteService; diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/Deployment/SiteSettingsDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Settings/Deployment/SiteSettingsDeploymentStepDriver.cs index 0081dd6c0e0..5607c5a7b7f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/Deployment/SiteSettingsDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/Deployment/SiteSettingsDeploymentStepDriver.cs @@ -11,19 +11,22 @@ public class SiteSettingsDeploymentStepDriver : DisplayDriver("SiteSettingsDeploymentStep_Fields_Edit", model => - { - model.Settings = step.Settings; - }).Location("Content"); + return Initialize( + "SiteSettingsDeploymentStep_Fields_Edit", + model => + { + model.Settings = step.Settings; + } + ) + .Location("Content"); } public override async Task UpdateAsync(SiteSettingsDeploymentStep step, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/Drivers/ButtonsSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Settings/Drivers/ButtonsSettingsDisplayDriver.cs index 22e953755ca..84deacd7d36 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/Drivers/ButtonsSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/Drivers/ButtonsSettingsDisplayDriver.cs @@ -10,10 +10,9 @@ public class ButtonsSettingsDisplayDriver : DisplayDriver public override Task EditAsync(ISite site, BuildEditorContext context) { - return Task.FromResult(Dynamic("SiteSettings_SaveButton") - .Location("Actions") - .OnGroup(context.GroupId) // Trick to render the shape for all groups - ); + return Task.FromResult( + Dynamic("SiteSettings_SaveButton").Location("Actions").OnGroup(context.GroupId) // Trick to render the shape for all groups + ); } public override Task UpdateAsync(ISite model, UpdateEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/Drivers/DefaultSiteSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Settings/Drivers/DefaultSiteSettingsDisplayDriver.cs index fb1eb1120ec..046112e42fa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/Drivers/DefaultSiteSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/Drivers/DefaultSiteSettingsDisplayDriver.cs @@ -18,10 +18,7 @@ public class DefaultSiteSettingsDisplayDriver : DisplayDriver private readonly IShellHost _shellHost; private readonly ShellSettings _shellSettings; - public DefaultSiteSettingsDisplayDriver( - IShellHost shellHost, - ShellSettings shellSettings, - IStringLocalizer stringLocalizer) + public DefaultSiteSettingsDisplayDriver(IShellHost shellHost, ShellSettings shellSettings, IStringLocalizer stringLocalizer) { _shellHost = shellHost; _shellSettings = shellSettings; @@ -38,15 +35,9 @@ public override Task EditAsync(ISite site, BuildEditorContext co context.Shape.Metadata.Wrappers.Add("Settings_Wrapper__General"); var result = Combine( - Initialize("Settings_Edit__Site", model => PopulateProperties(site, model)) - .Location("Content:1#Site;10") - .OnGroup(GroupId), - Initialize("Settings_Edit__Resources", model => PopulateProperties(site, model)) - .Location("Content:1#Resources;20") - .OnGroup(GroupId), - Initialize("Settings_Edit__Cache", model => PopulateProperties(site, model)) - .Location("Content:1#Cache;30") - .OnGroup(GroupId) + Initialize("Settings_Edit__Site", model => PopulateProperties(site, model)).Location("Content:1#Site;10").OnGroup(GroupId), + Initialize("Settings_Edit__Resources", model => PopulateProperties(site, model)).Location("Content:1#Resources;20").OnGroup(GroupId), + Initialize("Settings_Edit__Cache", model => PopulateProperties(site, model)).Location("Content:1#Cache;30").OnGroup(GroupId) ); return Task.FromResult(result); @@ -112,7 +103,6 @@ private static void PopulateProperties(ISite site, SiteSettingsViewModel model) model.CacheMode = site.CacheMode; } - private static bool IsGeneralGroup(BuildEditorContext context) - => context.GroupId.Equals(GroupId, StringComparison.OrdinalIgnoreCase); + private static bool IsGeneralGroup(BuildEditorContext context) => context.GroupId.Equals(GroupId, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/Liquid/LiquidSiteSettingsAccessor.cs b/src/OrchardCore.Modules/OrchardCore.Settings/Liquid/LiquidSiteSettingsAccessor.cs index f6b16d41f36..9c2b58c0a4b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/Liquid/LiquidSiteSettingsAccessor.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/Liquid/LiquidSiteSettingsAccessor.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Liquid /// /// This is a placeholder class that allows modules to extend the `Site` property in the current Liquid scope. /// - public class LiquidSiteSettingsAccessor - { - } + public class LiquidSiteSettingsAccessor { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Settings/Permissions.cs index 13067b4c1db..454ff87aeec 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/Permissions.cs @@ -11,20 +11,9 @@ public class Permissions : IPermissionProvider // This permission is not exposed, it's just used for the APIs to generate/check custom ones. public static readonly Permission ManageGroupSettings = new("ManageResourceSettings", "Manage settings", new[] { ManageSettings }); - private readonly IEnumerable _allPermissions = - [ - ManageSettings, - ]; + private readonly IEnumerable _allPermissions = [ManageSettings,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/Services/DefaultTimeZoneSelector.cs b/src/OrchardCore.Modules/OrchardCore.Settings/Services/DefaultTimeZoneSelector.cs index ed6fb3ba700..c62f155db25 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/Services/DefaultTimeZoneSelector.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/Services/DefaultTimeZoneSelector.cs @@ -19,11 +19,7 @@ public DefaultTimeZoneSelector(ISiteService siteService) public Task GetTimeZoneAsync() { - return Task.FromResult(new TimeZoneSelectorResult - { - Priority = 0, - TimeZoneId = async () => (await _siteService.GetSiteSettingsAsync())?.TimeZoneId - }); + return Task.FromResult(new TimeZoneSelectorResult { Priority = 0, TimeZoneId = async () => (await _siteService.GetSiteSettingsAsync())?.TimeZoneId }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/Services/SiteService.cs b/src/OrchardCore.Modules/OrchardCore.Settings/Services/SiteService.cs index 80f18c91dab..c6ef56f1ac0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/Services/SiteService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/Services/SiteService.cs @@ -38,16 +38,18 @@ public SiteService(IDocumentManager documentManager, IClock clock) private Task GetDefaultSettingsAsync() { - return Task.FromResult(new SiteSettings - { - SiteSalt = Guid.NewGuid().ToString("N"), - SiteName = "My Orchard Project Application", - PageTitleFormat = "{% page_title Site.SiteName, position: \"after\", separator: \" - \" %}", - TimeZoneId = _clock.GetSystemTimeZone().TimeZoneId, - PageSize = 10, - MaxPageSize = 100, - MaxPagedCount = 0 - }); + return Task.FromResult( + new SiteSettings + { + SiteSalt = Guid.NewGuid().ToString("N"), + SiteName = "My Orchard Project Application", + PageTitleFormat = "{% page_title Site.SiteName, position: \"after\", separator: \" - \" %}", + TimeZoneId = _clock.GetSystemTimeZone().TimeZoneId, + PageSize = 10, + MaxPageSize = 100, + MaxPagedCount = 0 + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/SiteSettings.cs b/src/OrchardCore.Modules/OrchardCore.Settings/SiteSettings.cs index 4e000f0aed1..33c0ae3c2c4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/SiteSettings.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/SiteSettings.cs @@ -27,7 +27,8 @@ public class SiteSettings : DocumentEntity, ISite public bool AppendVersion { get; set; } = true; public CacheMode CacheMode { get; set; } - public T As() where T : new() + public T As() + where T : new() { var name = typeof(T).Name; if (!IsReadOnly) diff --git a/src/OrchardCore.Modules/OrchardCore.Settings/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Settings/Startup.cs index 4454b54fb13..beb3f1b046f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Settings/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Settings/Startup.cs @@ -30,37 +30,39 @@ public override void ConfigureServices(IServiceCollection services) services.Configure(o => { o.Scope.SetValue("Site", new ObjectValue(new LiquidSiteSettingsAccessor())); - o.MemberAccessStrategy.Register(async (obj, name, context) => - { - var liquidTemplateContext = (LiquidTemplateContext)context; + o.MemberAccessStrategy.Register( + async (obj, name, context) => + { + var liquidTemplateContext = (LiquidTemplateContext)context; - var siteService = liquidTemplateContext.Services.GetRequiredService(); - var site = await siteService.GetSiteSettingsAsync(); + var siteService = liquidTemplateContext.Services.GetRequiredService(); + var site = await siteService.GetSiteSettingsAsync(); - FluidValue result = name switch - { - nameof(ISite.SiteName) => new StringValue(site.SiteName), - nameof(ISite.PageTitleFormat) => new StringValue(site.PageTitleFormat), - nameof(ISite.SiteSalt) => new StringValue(site.SiteSalt), - nameof(ISite.SuperUser) => new StringValue(site.SuperUser), - nameof(ISite.Calendar) => new StringValue(site.Calendar), - nameof(ISite.TimeZoneId) => new StringValue(site.TimeZoneId), - nameof(ISite.ResourceDebugMode) => new StringValue(site.ResourceDebugMode.ToString()), - nameof(ISite.UseCdn) => BooleanValue.Create(site.UseCdn), - nameof(ISite.CdnBaseUrl) => new StringValue(site.CdnBaseUrl), - nameof(ISite.PageSize) => NumberValue.Create(site.PageSize), - nameof(ISite.MaxPageSize) => NumberValue.Create(site.MaxPageSize), - nameof(ISite.MaxPagedCount) => NumberValue.Create(site.MaxPagedCount), - nameof(ISite.BaseUrl) => new StringValue(site.BaseUrl), - nameof(ISite.HomeRoute) => new ObjectValue(site.HomeRoute), - nameof(ISite.AppendVersion) => BooleanValue.Create(site.AppendVersion), - nameof(ISite.CacheMode) => new StringValue(site.CacheMode.ToString()), - nameof(ISite.Properties) => new ObjectValue(site.Properties), - _ => NilValue.Instance - }; + FluidValue result = name switch + { + nameof(ISite.SiteName) => new StringValue(site.SiteName), + nameof(ISite.PageTitleFormat) => new StringValue(site.PageTitleFormat), + nameof(ISite.SiteSalt) => new StringValue(site.SiteSalt), + nameof(ISite.SuperUser) => new StringValue(site.SuperUser), + nameof(ISite.Calendar) => new StringValue(site.Calendar), + nameof(ISite.TimeZoneId) => new StringValue(site.TimeZoneId), + nameof(ISite.ResourceDebugMode) => new StringValue(site.ResourceDebugMode.ToString()), + nameof(ISite.UseCdn) => BooleanValue.Create(site.UseCdn), + nameof(ISite.CdnBaseUrl) => new StringValue(site.CdnBaseUrl), + nameof(ISite.PageSize) => NumberValue.Create(site.PageSize), + nameof(ISite.MaxPageSize) => NumberValue.Create(site.MaxPageSize), + nameof(ISite.MaxPagedCount) => NumberValue.Create(site.MaxPagedCount), + nameof(ISite.BaseUrl) => new StringValue(site.BaseUrl), + nameof(ISite.HomeRoute) => new ObjectValue(site.HomeRoute), + nameof(ISite.AppendVersion) => BooleanValue.Create(site.AppendVersion), + nameof(ISite.CacheMode) => new StringValue(site.CacheMode.ToString()), + nameof(ISite.Properties) => new ObjectValue(site.Properties), + _ => NilValue.Instance + }; - return result; - }); + return result; + } + ); }); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Setup/Controllers/SetupController.cs b/src/OrchardCore.Modules/OrchardCore.Setup/Controllers/SetupController.cs index d96ec02a46a..a2140d8acdb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Setup/Controllers/SetupController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Setup/Controllers/SetupController.cs @@ -41,7 +41,8 @@ public SetupController( IEmailAddressValidator emailAddressValidator, IEnumerable databaseProviders, IStringLocalizer localizer, - ILogger logger) + ILogger logger + ) { _clock = clock; _setupService = setupService; diff --git a/src/OrchardCore.Modules/OrchardCore.Setup/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Setup/Startup.cs index e84af382297..57cd9682781 100644 --- a/src/OrchardCore.Modules/OrchardCore.Setup/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Setup/Startup.cs @@ -81,19 +81,12 @@ public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder ro if (_supportedCultures?.Length > 0) { - localizationOptions - .AddSupportedCultures(_supportedCultures) - .AddSupportedUICultures(_supportedCultures); + localizationOptions.AddSupportedCultures(_supportedCultures).AddSupportedUICultures(_supportedCultures); } app.UseRequestLocalization(localizationOptions); - routes.MapAreaControllerRoute( - name: "Setup", - areaName: "OrchardCore.Setup", - pattern: "", - defaults: new { controller = "Setup", action = "Index" } - ); + routes.MapAreaControllerRoute(name: "Setup", areaName: "OrchardCore.Setup", pattern: "", defaults: new { controller = "Setup", action = "Index" }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/AdminMenu.cs index 9ed3af46b59..cb3536e8019 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/AdminMenu.cs @@ -20,14 +20,15 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Design"], design => design - .Add(S["Shortcodes"], S["Shortcodes"].PrefixPosition(), import => import - .Action("Index", "Admin", "OrchardCore.Shortcodes") - .Permission(Permissions.ManageShortcodeTemplates) - .LocalNav() + builder.Add( + S["Design"], + design => + design.Add( + S["Shortcodes"], + S["Shortcodes"].PrefixPosition(), + import => import.Action("Index", "Admin", "OrchardCore.Shortcodes").Permission(Permissions.ManageShortcodeTemplates).LocalNav() ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Controllers/AdminController.cs index 4024dc02aa9..bab4f41f979 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Controllers/AdminController.cs @@ -51,7 +51,7 @@ public AdminController( IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer, IHtmlSanitizerService htmlSanitizerService - ) + ) { _authorizationService = authorizationService; _shortcodeTemplatesManager = shortcodeTemplatesManager; @@ -84,9 +84,7 @@ public async Task Index(ContentOptions options, PagerParameters p var count = shortcodeTemplates.Count; - shortcodeTemplates = shortcodeTemplates.OrderBy(x => x.Key) - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize).ToList(); + shortcodeTemplates = shortcodeTemplates.OrderBy(x => x.Key).Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -105,21 +103,15 @@ public async Task Index(ContentOptions options, PagerParameters p Pager = pagerShape }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(ShortcodeTemplateIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(ShortcodeTemplateIndexViewModel model) => + RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); [Admin("Shortcodes/Create", "Shortcodes.Create")] public async Task Create() @@ -166,7 +158,10 @@ public async Task CreatePost(ShortcodeTemplateViewModel model, st } else if (!_liquidTemplateManager.Validate(model.Content, out var errors)) { - ModelState.AddModelError(nameof(ShortcodeTemplateViewModel.Content), S["The template doesn't contain a valid Liquid expression. Details: {0}", string.Join(" ", errors)]); + ModelState.AddModelError( + nameof(ShortcodeTemplateViewModel.Content), + S["The template doesn't contain a valid Liquid expression. Details: {0}", string.Join(" ", errors)] + ); } } @@ -248,8 +243,7 @@ public async Task Edit(string sourceName, ShortcodeTemplateViewMo { ModelState.AddModelError(nameof(ShortcodeTemplateViewModel.Name), S["The name contains invalid characters."]); } - else if (!string.Equals(model.Name, sourceName, StringComparison.OrdinalIgnoreCase) - && shortcodeTemplatesDocument.ShortcodeTemplates.ContainsKey(model.Name)) + else if (!string.Equals(model.Name, sourceName, StringComparison.OrdinalIgnoreCase) && shortcodeTemplatesDocument.ShortcodeTemplates.ContainsKey(model.Name)) { ModelState.AddModelError(nameof(ShortcodeTemplateViewModel.Name), S["A template with the same name already exists."]); } @@ -260,7 +254,10 @@ public async Task Edit(string sourceName, ShortcodeTemplateViewMo } else if (!_liquidTemplateManager.Validate(model.Content, out var errors)) { - ModelState.AddModelError(nameof(ShortcodeTemplateViewModel.Content), S["The template doesn't contain a valid Liquid expression. Details: {0}", string.Join(" ", errors)]); + ModelState.AddModelError( + nameof(ShortcodeTemplateViewModel.Content), + S["The template doesn't contain a valid Liquid expression. Details: {0}", string.Join(" ", errors)] + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Deployment/AllShortcodeTemplatesDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Deployment/AllShortcodeTemplatesDeploymentSource.cs index 5c4eaf2d69c..aa03bfb623e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Deployment/AllShortcodeTemplatesDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Deployment/AllShortcodeTemplatesDeploymentSource.cs @@ -31,11 +31,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan templateObjects[template.Key] = JObject.FromObject(template.Value); } - result.Steps.Add(new JsonObject - { - ["name"] = "ShortcodeTemplates", - ["ShortcodeTemplates"] = templateObjects, - }); + result.Steps.Add(new JsonObject { ["name"] = "ShortcodeTemplates", ["ShortcodeTemplates"] = templateObjects, }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Deployment/AllShortcodeTemplatesDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Deployment/AllShortcodeTemplatesDeploymentStepDriver.cs index d603b1459f8..e685db684ad 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Deployment/AllShortcodeTemplatesDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Deployment/AllShortcodeTemplatesDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class AllShortcodeTemplatesDeploymentStepDriver : DisplayDriver _allPermissions = - [ - ManageShortcodeTemplates, - ]; + private readonly IEnumerable _allPermissions = [ManageShortcodeTemplates,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _allPermissions, - }, - ]; + [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, }, new PermissionStereotype { Name = "Editor", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Providers/LocaleShortcodeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Providers/LocaleShortcodeProvider.cs index 9ac31934e53..3fa29ea6c65 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Providers/LocaleShortcodeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Providers/LocaleShortcodeProvider.cs @@ -37,8 +37,7 @@ public ValueTask EvaluateAsync(string identifier, Arguments arguments, s } currentCulture = currentCulture.Parent; - } - while (currentCulture != CultureInfo.InvariantCulture); + } while (currentCulture != CultureInfo.InvariantCulture); } else { diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Razor/OrchardRazorHelperExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Razor/OrchardRazorHelperExtensions.cs index f351df3b082..fd70fa2b0d1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Razor/OrchardRazorHelperExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Razor/OrchardRazorHelperExtensions.cs @@ -40,6 +40,5 @@ public static async Task ShortcodesToHtmlAsync(this IOrchardHelper } [Obsolete("Replaced by ShortcodesToHtmlAsync")] - public static Task HtmlToShortcodesAsync(this IOrchardHelper orchardHelper, string html, object model = null) - => orchardHelper.ShortcodesToHtmlAsync(html, model); + public static Task HtmlToShortcodesAsync(this IOrchardHelper orchardHelper, string html, object model = null) => orchardHelper.ShortcodesToHtmlAsync(html, model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/OptionsShortcodeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/OptionsShortcodeProvider.cs index 473681d6c2b..0f906f9268e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/OptionsShortcodeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/OptionsShortcodeProvider.cs @@ -1,4 +1,3 @@ - using System.Threading.Tasks; using Microsoft.Extensions.Options; using Shortcodes; diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeOptionsDescriptorProvider.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeOptionsDescriptorProvider.cs index 33e99b44826..47c928558fa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeOptionsDescriptorProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeOptionsDescriptorProvider.cs @@ -15,14 +15,15 @@ public ShortcodeOptionsDescriptorProvider(IOptions options) } public Task> DiscoverAsync() => - Task.FromResult(_options.Shortcodes.Values.Select(option => - new ShortcodeDescriptor + Task.FromResult( + _options.Shortcodes.Values.Select(option => new ShortcodeDescriptor { Name = option.Name, DefaultValue = option.DefaultValue, Usage = option.Usage, Hint = option.Hint, Categories = option.Categories - })); + }) + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeService.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeService.cs index d7e021ea3bd..a112ba73a3d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeService.cs @@ -9,9 +9,7 @@ public class ShortcodeService : IShortcodeService private readonly IEnumerable _shortcodeContextProviders; private readonly ShortcodesProcessor _shortcodesProcessor; - public ShortcodeService( - IEnumerable shortcodeProviders, - IEnumerable shortcodeContextProviders) + public ShortcodeService(IEnumerable shortcodeProviders, IEnumerable shortcodeContextProviders) { _shortcodesProcessor = new ShortcodesProcessor(shortcodeProviders); _shortcodeContextProviders = shortcodeContextProviders; diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeTemplatesDescriptorProvider.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeTemplatesDescriptorProvider.cs index 782edc62a19..eaa1908b45d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeTemplatesDescriptorProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/ShortcodeTemplatesDescriptorProvider.cs @@ -17,15 +17,14 @@ public async Task> DiscoverAsync() { var document = await _shortcodeTemplatesManager.GetShortcodeTemplatesDocumentAsync(); - return document.ShortcodeTemplates.Select(kvp => - new ShortcodeDescriptor - { - Name = kvp.Key, - Hint = kvp.Value.Hint, - DefaultValue = kvp.Value.DefaultValue, - Usage = kvp.Value.Usage, - Categories = kvp.Value.Categories - }); + return document.ShortcodeTemplates.Select(kvp => new ShortcodeDescriptor + { + Name = kvp.Key, + Hint = kvp.Value.Hint, + DefaultValue = kvp.Value.DefaultValue, + Usage = kvp.Value.Usage, + Categories = kvp.Value.Categories + }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/TemplateShortcodeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/TemplateShortcodeProvider.cs index b9a0d869299..3aba3190b12 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/TemplateShortcodeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/TemplateShortcodeProvider.cs @@ -18,10 +18,7 @@ public class TemplateShortcodeProvider : IShortcodeProvider private ShortcodeTemplatesDocument _shortcodeTemplatesDocument; private readonly HashSet _identifiers = []; - public TemplateShortcodeProvider( - ShortcodeTemplatesManager shortcodeTemplatesManager, - ILiquidTemplateManager liquidTemplateManager, - HtmlEncoder htmlEncoder) + public TemplateShortcodeProvider(ShortcodeTemplatesManager shortcodeTemplatesManager, ILiquidTemplateManager liquidTemplateManager, HtmlEncoder htmlEncoder) { _shortcodeTemplatesManager = shortcodeTemplatesManager; _liquidTemplateManager = liquidTemplateManager; @@ -68,7 +65,9 @@ public async ValueTask EvaluateAsync(string identifier, Arguments argume internal class Content : LiquidContentAccessor { public readonly string _content; + public Content(string content) => _content = content; + public override string ToString() => _content; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Startup.cs index 06772ccdd7b..76bf65db03e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Startup.cs @@ -77,20 +77,23 @@ public class LocaleShortcodeProviderStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddShortcode("locale", d => - { - d.DefaultValue = "[locale {language_code}] [/locale]"; - d.Hint = "Conditionally render content in the specified language"; - d.Usage = -@"[locale en]English Text[/locale][locale fr false]French Text[/locale]
+ services.AddShortcode( + "locale", + d => + { + d.DefaultValue = "[locale {language_code}] [/locale]"; + d.Hint = "Conditionally render content in the specified language"; + d.Usage = + @"[locale en]English Text[/locale][locale fr false]French Text[/locale]
Args: lang, fallback
"; - d.Categories = ["Localization"]; - }); + d.Categories = ["Localization"]; + } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/AdminMenu.cs index d3a9d2b4890..d945b5eb777 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/AdminMenu.cs @@ -20,24 +20,23 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["SEO"], S["SEO"].PrefixPosition(), seo => seo - .Permission(Permissions.ManageSitemaps) - .Add(S["Sitemaps"], S["Sitemaps"].PrefixPosition("1"), sitemaps => sitemaps - .Action("List", "Admin", "OrchardCore.Sitemaps") - .LocalNav() - ) - .Add(S["Sitemap Indexes"], S["Sitemap Indexes"].PrefixPosition("2"), indexes => indexes - .Action("List", "SitemapIndex", "OrchardCore.Sitemaps") - .LocalNav() - ) - .Add(S["Sitemaps Cache"], S["Sitemaps Cache"].PrefixPosition("3"), cache => cache - .Action("List", "SitemapCache", "OrchardCore.Sitemaps") - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["SEO"], + S["SEO"].PrefixPosition(), + seo => + seo.Permission(Permissions.ManageSitemaps) + .Add(S["Sitemaps"], S["Sitemaps"].PrefixPosition("1"), sitemaps => sitemaps.Action("List", "Admin", "OrchardCore.Sitemaps").LocalNav()) + .Add( + S["Sitemap Indexes"], + S["Sitemap Indexes"].PrefixPosition("2"), + indexes => indexes.Action("List", "SitemapIndex", "OrchardCore.Sitemaps").LocalNav() + ) + .Add(S["Sitemaps Cache"], S["Sitemaps Cache"].PrefixPosition("3"), cache => cache.Action("List", "SitemapCache", "OrchardCore.Sitemaps").LocalNav()) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Builders/SitemapIndexTypeBuilder.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Builders/SitemapIndexTypeBuilder.cs index 62ef910321a..89e0c201e2c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Builders/SitemapIndexTypeBuilder.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Builders/SitemapIndexTypeBuilder.cs @@ -20,11 +20,7 @@ public class SitemapIndexTypeBuilder : SitemapTypeBuilderBase private readonly ISitemapModifiedDateProvider _sitemapModifiedDateProvider; private readonly SitemapsOptions _sitemapsOptions; - public SitemapIndexTypeBuilder( - ISitemapManager sitemapManager, - ISitemapModifiedDateProvider sitemapModifiedDateProvider, - IOptions options - ) + public SitemapIndexTypeBuilder(ISitemapManager sitemapManager, ISitemapModifiedDateProvider sitemapModifiedDateProvider, IOptions options) { _sitemapManager = sitemapManager; _sitemapModifiedDateProvider = sitemapModifiedDateProvider; @@ -35,9 +31,11 @@ public override async Task BuildSitemapTypeAsync(SitemapIndex sitemap, SitemapBu { context.Response = new SitemapResponse { - ResponseElement = new XElement(_namespace + "sitemapindex", + ResponseElement = new XElement( + _namespace + "sitemapindex", new XAttribute(XNamespace.Xmlns + "xsi", _schemaInstance), - new XAttribute(_schemaInstance + "schemaLocation", _schemaLocation)) + new XAttribute(_schemaInstance + "schemaLocation", _schemaLocation) + ) }; var indexSource = sitemap.SitemapSources.FirstOrDefault() as SitemapIndexSource; @@ -47,18 +45,14 @@ public override async Task BuildSitemapTypeAsync(SitemapIndex sitemap, SitemapBu return; } - var containedSitemaps = (await _sitemapManager.GetSitemapsAsync()) - .Where(s => s.Enabled && indexSource.ContainedSitemapIds.Any(id => id == s.SitemapId)); + var containedSitemaps = (await _sitemapManager.GetSitemapsAsync()).Where(s => s.Enabled && indexSource.ContainedSitemapIds.Any(id => id == s.SitemapId)); foreach (var containedSitemap in containedSitemaps) { var xmlSitemap = new XElement(_namespace + "sitemap"); var loc = new XElement(_namespace + "loc"); - var routeValues = new RouteValueDictionary(_sitemapsOptions.GlobalRouteValues) - { - [_sitemapsOptions.SitemapIdKey] = containedSitemap.SitemapId - }; + var routeValues = new RouteValueDictionary(_sitemapsOptions.GlobalRouteValues) { [_sitemapsOptions.SitemapIdKey] = containedSitemap.SitemapId }; loc.Add(context.HostPrefix + context.UrlHelper.Action(routeValues["Action"].ToString(), routeValues)); xmlSitemap.Add(loc); diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Builders/SitemapTypeBuilder.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Builders/SitemapTypeBuilder.cs index be820753337..6ffdb14d7f5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Builders/SitemapTypeBuilder.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Builders/SitemapTypeBuilder.cs @@ -18,10 +18,7 @@ public SitemapTypeBuilder(IEnumerable sitemapSourceBuilde public override async Task BuildSitemapTypeAsync(Sitemap sitemap, SitemapBuilderContext context) { - context.Response = new SitemapResponse - { - ResponseElement = new XElement(_namespace + "urlset") - }; + context.Response = new SitemapResponse { ResponseElement = new XElement(_namespace + "urlset") }; foreach (var source in sitemap.SitemapSources) { diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Cache/DefaultSitemapCacheProvider.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Cache/DefaultSitemapCacheProvider.cs index e26321dfd61..324bbddb9e8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Cache/DefaultSitemapCacheProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Cache/DefaultSitemapCacheProvider.cs @@ -21,11 +21,7 @@ public class DefaultSitemapCacheProvider : ISitemapCacheProvider private readonly PhysicalFileProvider _fileProvider; private readonly ILogger _logger; - public DefaultSitemapCacheProvider( - IWebHostEnvironment webHostEnvironment, - ShellSettings shellSettings, - ILogger logger - ) + public DefaultSitemapCacheProvider(IWebHostEnvironment webHostEnvironment, ShellSettings shellSettings, ILogger logger) { var path = GetSitemapCachePath(webHostEnvironment, shellSettings, SitemapCachePath); diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Cache/SitemapCacheBackgroundTask.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Cache/SitemapCacheBackgroundTask.cs index 2c9b8498415..7e1b2d5d1cf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Cache/SitemapCacheBackgroundTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Cache/SitemapCacheBackgroundTask.cs @@ -8,10 +8,7 @@ namespace OrchardCore.Sitemaps.Cache { - [BackgroundTask( - Title = "Sitemap Cache Cleaner", - Schedule = "*/5 * * * *", - Description = "Cleans up sitemap cache files.")] + [BackgroundTask(Title = "Sitemap Cache Cleaner", Schedule = "*/5 * * * *", Description = "Cleans up sitemap cache files.")] public class SitemapCacheBackgroundTask : IBackgroundTask { public async Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken) diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/AdminController.cs index 9cef43df1bb..7e6eb71747b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/AdminController.cs @@ -52,7 +52,8 @@ public AdminController( INotifier notifier, IShapeFactory shapeFactory, IStringLocalizer stringLocalizer, - IHtmlLocalizer htmlLocalizer) + IHtmlLocalizer htmlLocalizer + ) { _sitemapService = sitemapService; _displayManager = displayManager; @@ -77,8 +78,7 @@ public async Task List(ContentOptions options, PagerParameters pa var pager = new Pager(pagerParameters, _pagerOptions.GetPageSize()); - var sitemaps = (await _sitemapManager.GetSitemapsAsync()) - .OfType(); + var sitemaps = (await _sitemapManager.GetSitemapsAsync()).OfType(); if (!string.IsNullOrWhiteSpace(options.Search)) { @@ -87,10 +87,7 @@ public async Task List(ContentOptions options, PagerParameters pa var count = sitemaps.Count(); - var results = sitemaps - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize) - .ToList(); + var results = sitemaps.Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -102,26 +99,26 @@ public async Task List(ContentOptions options, PagerParameters pa var model = new ListSitemapViewModel { - Sitemaps = results.Select(sm => new SitemapListEntry { SitemapId = sm.SitemapId, Name = sm.Name, Enabled = sm.Enabled }).ToList(), + Sitemaps = results + .Select(sm => new SitemapListEntry + { + SitemapId = sm.SitemapId, + Name = sm.Name, + Enabled = sm.Enabled + }) + .ToList(), Options = options, Pager = await _shapeFactory.PagerAsync(pager, count, routeData) }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(List))] [FormValueRequired("submit.Filter")] - public ActionResult ListFilterPOST(ListSitemapViewModel model) - => RedirectToAction(nameof(List), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult ListFilterPOST(ListSitemapViewModel model) => RedirectToAction(nameof(List), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Display(string sitemapId) { diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapCacheController.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapCacheController.cs index 9f364545d89..3670eb3f2fb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapCacheController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapCacheController.cs @@ -23,7 +23,7 @@ public SitemapCacheController( ISitemapCacheProvider sitemapCacheProvider, INotifier notifier, IHtmlLocalizer htmlLocalizer - ) + ) { _authorizationService = authorizationService; _sitemapCacheProvider = sitemapCacheProvider; @@ -38,10 +38,7 @@ public async Task List() return Forbid(); } - var model = new ListSitemapCacheViewModel - { - CachedFileNames = (await _sitemapCacheProvider.ListAsync()).ToArray() - }; + var model = new ListSitemapCacheViewModel { CachedFileNames = (await _sitemapCacheProvider.ListAsync()).ToArray() }; return View(model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapController.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapController.cs index c0159ded7c3..1dc3a098036 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapController.cs @@ -35,7 +35,7 @@ public SitemapController( ISitemapCacheProvider sitemapCacheProvider, ShellSettings shellSettings, ILogger logger - ) + ) { _sitemapManager = sitemapManager; _siteService = siteService; @@ -56,7 +56,7 @@ public async Task Index(string sitemapId, CancellationToken cance var fileResolver = await _sitemapCacheProvider.GetCachedSitemapAsync(sitemap.CacheFileName); if (fileResolver != null) { - // When multiple requests occur for the same sitemap it + // When multiple requests occur for the same sitemap it // may still be building, so we wait for it to complete. if (_workers.TryGetValue(_tenantName + sitemap.Path, out var writeTask)) { @@ -69,48 +69,52 @@ public async Task Index(string sitemapId, CancellationToken cance } else { - var work = await _workers.GetOrAdd(_tenantName + sitemap.Path, x => new Lazy>(async () => - { - try - { - var siteSettings = await _siteService.GetSiteSettingsAsync(); - - var context = new SitemapBuilderContext() - { - HostPrefix = siteSettings.BaseUrl, - UrlHelper = Url - }; - - var document = await _sitemapBuilder.BuildAsync(sitemap, context); - - if (document == null) - { - return null; - } - - document.Declaration = new XDeclaration("1.0", "utf-8", null); - - var stream = new MemoryStream(); - await document.SaveAsync(stream, SaveOptions.None, cancellationToken); - - if (stream.Length >= ErrorLength) - { - _logger.LogError("Sitemap 50MB maximum length limit exceeded"); - } - else if (stream.Length >= WarningLength) - { - _logger.LogWarning("Sitemap nearing 50MB length limit"); - } - - await _sitemapCacheProvider.SetSitemapCacheAsync(stream, sitemap.CacheFileName, cancellationToken); - - return stream; - } - finally - { - _workers.TryRemove(_tenantName + sitemap.Path, out var writeCacheTask); - } - }, LazyThreadSafetyMode.ExecutionAndPublication)).Value; + var work = await _workers + .GetOrAdd( + _tenantName + sitemap.Path, + x => new Lazy>( + async () => + { + try + { + var siteSettings = await _siteService.GetSiteSettingsAsync(); + + var context = new SitemapBuilderContext() { HostPrefix = siteSettings.BaseUrl, UrlHelper = Url }; + + var document = await _sitemapBuilder.BuildAsync(sitemap, context); + + if (document == null) + { + return null; + } + + document.Declaration = new XDeclaration("1.0", "utf-8", null); + + var stream = new MemoryStream(); + await document.SaveAsync(stream, SaveOptions.None, cancellationToken); + + if (stream.Length >= ErrorLength) + { + _logger.LogError("Sitemap 50MB maximum length limit exceeded"); + } + else if (stream.Length >= WarningLength) + { + _logger.LogWarning("Sitemap nearing 50MB length limit"); + } + + await _sitemapCacheProvider.SetSitemapCacheAsync(stream, sitemap.CacheFileName, cancellationToken); + + return stream; + } + finally + { + _workers.TryRemove(_tenantName + sitemap.Path, out var writeCacheTask); + } + }, + LazyThreadSafetyMode.ExecutionAndPublication + ) + ) + .Value; if (work == null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapIndexController.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapIndexController.cs index d381f0532a4..d250b6f7581 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapIndexController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapIndexController.cs @@ -48,7 +48,8 @@ public SitemapIndexController( IShapeFactory shapeFactory, IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer, - INotifier notifier) + INotifier notifier + ) { _sitemapService = sitemapService; _authorizationService = authorizationService; @@ -71,8 +72,7 @@ public async Task List(ContentOptions options, PagerParameters pa var pager = new Pager(pagerParameters, _pagerOptions.GetPageSize()); - var sitemaps = (await _sitemapManager.GetSitemapsAsync()) - .OfType(); + var sitemaps = (await _sitemapManager.GetSitemapsAsync()).OfType(); if (!string.IsNullOrWhiteSpace(options.Search)) { @@ -81,10 +81,7 @@ public async Task List(ContentOptions options, PagerParameters pa var count = sitemaps.Count(); - var results = sitemaps - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize) - .ToList(); + var results = sitemaps.Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -98,27 +95,27 @@ public async Task List(ContentOptions options, PagerParameters pa var model = new ListSitemapIndexViewModel { - SitemapIndexes = results.Select(sm => new SitemapIndexListEntry { SitemapId = sm.SitemapId, Name = sm.Name, Enabled = sm.Enabled }).ToList(), + SitemapIndexes = results + .Select(sm => new SitemapIndexListEntry + { + SitemapId = sm.SitemapId, + Name = sm.Name, + Enabled = sm.Enabled + }) + .ToList(), Options = options, Pager = pagerShape }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; - + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(List))] [FormValueRequired("submit.Filter")] - public ActionResult ListFilterPOST(ListSitemapIndexViewModel model) - => RedirectToAction(nameof(List), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult ListFilterPOST(ListSitemapIndexViewModel model) => + RedirectToAction(nameof(List), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Create() { @@ -140,10 +137,7 @@ public async Task Create() .OrderBy(s => s.Name) .ToArray(); - var model = new CreateSitemapIndexViewModel - { - ContainableSitemaps = containableSitemaps - }; + var model = new CreateSitemapIndexViewModel { ContainableSitemaps = containableSitemaps }; return View(model); } @@ -156,22 +150,15 @@ public async Task Create(CreateSitemapIndexViewModel model) return Forbid(); } - var sitemap = new SitemapIndex - { - SitemapId = _sitemapIdGenerator.GenerateUniqueId() - }; + var sitemap = new SitemapIndex { SitemapId = _sitemapIdGenerator.GenerateUniqueId() }; - var indexSource = new SitemapIndexSource - { - Id = _sitemapIdGenerator.GenerateUniqueId() - }; + var indexSource = new SitemapIndexSource { Id = _sitemapIdGenerator.GenerateUniqueId() }; sitemap.SitemapSources.Add(indexSource); if (ModelState.IsValid) { await _sitemapService.ValidatePathAsync(model.Path, _updateModelAccessor.ModelUpdater); - } // Path validation may invalidate model state. @@ -181,10 +168,7 @@ public async Task Create(CreateSitemapIndexViewModel model) sitemap.Enabled = model.Enabled; sitemap.Path = model.Path; - indexSource.ContainedSitemapIds = model.ContainableSitemaps - .Where(m => m.IsChecked) - .Select(m => m.SitemapId) - .ToArray(); + indexSource.ContainedSitemapIds = model.ContainableSitemaps.Where(m => m.IsChecked).Select(m => m.SitemapId).ToArray(); await _sitemapManager.UpdateSitemapAsync(sitemap); @@ -270,10 +254,7 @@ public async Task Edit(EditSitemapIndexViewModel model) sitemap.Enabled = model.Enabled; sitemap.Path = model.Path; - indexSource.ContainedSitemapIds = model.ContainableSitemaps - .Where(m => m.IsChecked) - .Select(m => m.SitemapId) - .ToArray(); + indexSource.ContainedSitemapIds = model.ContainableSitemaps.Where(m => m.IsChecked).Select(m => m.SitemapId).ToArray(); await _sitemapManager.UpdateSitemapAsync(sitemap); diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SourceController.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SourceController.cs index de98b278fe3..57406fdf255 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SourceController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SourceController.cs @@ -37,7 +37,8 @@ public SourceController( IUpdateModelAccessor updateModelAccessor, INotifier notifier, IStringLocalizer stringLocalizer, - IHtmlLocalizer htmlLocalizer) + IHtmlLocalizer htmlLocalizer + ) { _displayManager = displayManager; _factories = factories; diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Deployment/AllSitemapsDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Deployment/AllSitemapsDeploymentSource.cs index 8abf5f30e26..b452363920c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Deployment/AllSitemapsDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Deployment/AllSitemapsDeploymentSource.cs @@ -25,11 +25,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan var jArray = JArray.FromObject(sitemaps); - result.Steps.Add(new JsonObject - { - ["name"] = "Sitemaps", - ["data"] = jArray, - }); + result.Steps.Add(new JsonObject { ["name"] = "Sitemaps", ["data"] = jArray, }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Deployment/AllSitemapsDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Deployment/AllSitemapsDeploymentStepDriver.cs index c2462583b80..dae127004c5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Deployment/AllSitemapsDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Deployment/AllSitemapsDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class AllSitemapsDeploymentStepDriver : DisplayDriver("CustomPathSitemapSource_Edit", model => - { - model.Path = sitemapSource.Path; - model.Priority = sitemapSource.Priority; - model.ChangeFrequency = sitemapSource.ChangeFrequency; - - }).Location("Content"); + return Initialize( + "CustomPathSitemapSource_Edit", + model => + { + model.Path = sitemapSource.Path; + model.Priority = sitemapSource.Priority; + model.ChangeFrequency = sitemapSource.ChangeFrequency; + } + ) + .Location("Content"); } public override async Task UpdateAsync(CustomPathSitemapSource sitemap, UpdateEditorContext context) { var model = new CustomPathSitemapSourceViewModel(); - if (await context.Updater.TryUpdateModelAsync(model, - Prefix, - m => m.Path, - m => m.Priority, - m => m.ChangeFrequency - )) + if (await context.Updater.TryUpdateModelAsync(model, Prefix, m => m.Path, m => m.Priority, m => m.ChangeFrequency)) { sitemap.Path = model.Path; sitemap.Priority = model.Priority; @@ -58,14 +56,26 @@ public override async Task UpdateAsync(CustomPathSitemapSource s if (sitemap.Path?.IndexOfAny(CustomPathSitemapSource.InvalidCharactersForPath) > -1 || sitemap.Path?.IndexOf(' ') > -1 || sitemap.Path?.IndexOf("//") > -1) { var invalidCharactersForMessage = string.Join(", ", CustomPathSitemapSource.InvalidCharactersForPath.Select(c => $"\"{c}\"")); - context.Updater.ModelState.AddModelError(Prefix, sitemap.Path, S["Please do not use any of the following characters in your permalink: {0}. No spaces, or consecutive slashes, are allowed (please use dashes or underscores instead).", invalidCharactersForMessage]); + context.Updater.ModelState.AddModelError( + Prefix, + sitemap.Path, + S[ + "Please do not use any of the following characters in your permalink: {0}. No spaces, or consecutive slashes, are allowed (please use dashes or underscores instead).", + invalidCharactersForMessage + ] + ); } if (sitemap.Path?.Length > CustomPathSitemapSource.MaxPathLength) { - context.Updater.ModelState.AddModelError(Prefix, sitemap.Path, S["Your path is too long. The path can only be up to {0} characters.", CustomPathSitemapSource.MaxPathLength]); + context.Updater.ModelState.AddModelError( + Prefix, + sitemap.Path, + S["Your path is too long. The path can only be up to {0} characters.", CustomPathSitemapSource.MaxPathLength] + ); } - }; + } + ; return Edit(sitemap, context.Updater); } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Drivers/SitemapPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Drivers/SitemapPartDisplayDriver.cs index 37718f67775..31d0f27b2ca 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Drivers/SitemapPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Drivers/SitemapPartDisplayDriver.cs @@ -11,21 +11,14 @@ public class SitemapPartDisplayDriver : ContentPartDisplayDriver { public override IDisplayResult Edit(SitemapPart part) { - return Initialize("SitemapPart_Edit", m => BuildViewModel(m, part)) - .Location("Parts#SEO:5"); + return Initialize("SitemapPart_Edit", m => BuildViewModel(m, part)).Location("Parts#SEO:5"); } public override async Task UpdateAsync(SitemapPart model, IUpdateModel updater) { var viewModel = new SitemapPartViewModel(); - if (await updater.TryUpdateModelAsync(viewModel, - Prefix, - t => t.OverrideSitemapConfig, - t => t.ChangeFrequency, - t => t.Exclude, - t => t.Priority - )) + if (await updater.TryUpdateModelAsync(viewModel, Prefix, t => t.OverrideSitemapConfig, t => t.ChangeFrequency, t => t.Exclude, t => t.Priority)) { model.OverrideSitemapConfig = viewModel.OverrideSitemapConfig; model.ChangeFrequency = viewModel.ChangeFrequency; @@ -36,7 +29,6 @@ public override async Task UpdateAsync(SitemapPart model, IUpdat return Edit(model); } - private static void BuildViewModel(SitemapPartViewModel model, SitemapPart part) { model.OverrideSitemapConfig = part.OverrideSitemapConfig; diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Drivers/SitemapsRobotsSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Drivers/SitemapsRobotsSettingsDisplayDriver.cs index cbf0954fc02..d3fb9643111 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Drivers/SitemapsRobotsSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Drivers/SitemapsRobotsSettingsDisplayDriver.cs @@ -16,9 +16,7 @@ public class SitemapsRobotsSettingsDisplayDriver : SectionDisplayDriver EditAsync(SitemapsRobotsSettings sett return null; } - return Initialize("SitemapsRobotsSettings_Edit", model => - { - model.IncludeSitemaps = settings.IncludeSitemaps; - }).Location("Content:4") - .OnGroup(SeoConstants.RobotsSettingsGroupId); + return Initialize( + "SitemapsRobotsSettings_Edit", + model => + { + model.IncludeSitemaps = settings.IncludeSitemaps; + } + ) + .Location("Content:4") + .OnGroup(SeoConstants.RobotsSettingsGroupId); } public override async Task UpdateAsync(SitemapsRobotsSettings settings, BuildEditorContext context) { var user = _httpContextAccessor.HttpContext?.User; - if (!context.GroupId.Equals(SeoConstants.RobotsSettingsGroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(user, SeoConstants.ManageSeoSettings)) + if ( + !context.GroupId.Equals(SeoConstants.RobotsSettingsGroupId, StringComparison.OrdinalIgnoreCase) + || !await _authorizationService.AuthorizeAsync(user, SeoConstants.ManageSeoSettings) + ) { return null; } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Handlers/CustomPathSitemapSourceUpdateHandler.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Handlers/CustomPathSitemapSourceUpdateHandler.cs index f3155ed4502..8ab7dcccf71 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Handlers/CustomPathSitemapSourceUpdateHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Handlers/CustomPathSitemapSourceUpdateHandler.cs @@ -26,8 +26,7 @@ public async Task UpdateSitemapAsync(SitemapUpdateContext context) foreach (var sitemap in sitemaps) { // Do not break out of this loop, as it must check each sitemap. - foreach (var source in sitemap.SitemapSources - .Select(s => s as CustomPathSitemapSource)) + foreach (var source in sitemap.SitemapSources.Select(s => s as CustomPathSitemapSource)) { if (source == null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Handlers/SitemapIndexTypeUpdateHandler.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Handlers/SitemapIndexTypeUpdateHandler.cs index 5463e1e87df..f6902cb103a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Handlers/SitemapIndexTypeUpdateHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Handlers/SitemapIndexTypeUpdateHandler.cs @@ -21,8 +21,7 @@ public async Task UpdateSitemapAsync(SitemapUpdateContext context) var allSitemaps = await _sitemapManager.LoadSitemapsAsync(); - var sitemapIndex = allSitemaps - .FirstOrDefault(s => s.GetType() == typeof(SitemapIndex)); + var sitemapIndex = allSitemaps.FirstOrDefault(s => s.GetType() == typeof(SitemapIndex)); if (contentItem == null || sitemapIndex == null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Manifest.cs index 92d614f0d5a..4316d634007 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Manifest.cs @@ -1,20 +1,12 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Sitemaps", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Sitemaps", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Sitemaps", Name = "Sitemaps", Description = "Provides dynamic sitemap generation services.", - Dependencies = - [ - "OrchardCore.Contents", - ], + Dependencies = ["OrchardCore.Contents",], Category = "Content Management" )] @@ -22,10 +14,7 @@ Id = "OrchardCore.Sitemaps.RazorPages", Name = "Sitemaps for Decoupled Razor Pages", Description = "Provides decoupled razor pages support for dynamic sitemap generation.", - Dependencies = - [ - "OrchardCore.Sitemaps" - ], + Dependencies = ["OrchardCore.Sitemaps"], Category = "Content Management" )] @@ -33,9 +22,6 @@ Id = "OrchardCore.Sitemaps.Cleanup", Name = "Sitemaps Cleanup", Description = "Cleanup sitemap cache files through a background task.", - Dependencies = - [ - "OrchardCore.Sitemaps" - ], + Dependencies = ["OrchardCore.Sitemaps"], Category = "Content Management" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Migrations.cs index 0a788deaac7..4b89fc6275a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Migrations.cs @@ -16,9 +16,10 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("SitemapPart", builder => builder - .Attachable() - .WithDescription("Provides an optional part that allows content items to be excluded, or configured, on a content item.")); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "SitemapPart", + builder => builder.Attachable().WithDescription("Provides an optional part that allows content items to be excluded, or configured, on a content item.") + ); return 1; } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Models/SitemapIndex.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Models/SitemapIndex.cs index 1fd578ea7b8..556c9faea4d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Models/SitemapIndex.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Models/SitemapIndex.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Sitemaps.Models { - public class SitemapIndex : SitemapType - { - } + public class SitemapIndex : SitemapType { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Models/SitemapIndexSource.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Models/SitemapIndexSource.cs index 6dd27c11e47..9c0b0e45361 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Models/SitemapIndexSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Models/SitemapIndexSource.cs @@ -2,7 +2,7 @@ namespace OrchardCore.Sitemaps.Models { // This is a single use Sitemap Index Source. // It is a SitemapSource because it works better when handling routing lookups. - // but it intentionally is hidden from normal sources and, + // but it intentionally is hidden from normal sources and, // will only ever be used a single time inside a sitemap. // For that reason there are no drivers. diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Permissions.cs index 2b44f442f14..89fbb680323 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageSitemaps = new("ManageSitemaps", "Manage sitemaps"); - private readonly IEnumerable _allPermissions = - [ - ManageSitemaps, - ]; + private readonly IEnumerable _allPermissions = [ManageSitemaps,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapEntries.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapEntries.cs index 6e78c73c299..cd02ca8ab8a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapEntries.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapEntries.cs @@ -48,10 +48,7 @@ public SitemapEntries(ISitemapManager sitemapManager) private async Task BuildEntriesAsync(string identifier) { - var document = new SitemapRouteDocument() - { - Identifier = identifier - }; + var document = new SitemapRouteDocument() { Identifier = identifier }; var sitemaps = await _sitemapManager.GetSitemapsAsync(); foreach (var sitemap in sitemaps) diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapRouteTransformer.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapRouteTransformer.cs index 9c695f0b094..4ec9ecff759 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapRouteTransformer.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapRouteTransformer.cs @@ -28,10 +28,7 @@ public override async ValueTask TransformAsync(HttpContext if (found) { - var routeValues = new RouteValueDictionary(_options.GlobalRouteValues) - { - [_options.SitemapIdKey] = sitemapId - }; + var routeValues = new RouteValueDictionary(_options.GlobalRouteValues) { [_options.SitemapIdKey] = sitemapId }; return routeValues; } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapValuesAddressScheme.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapValuesAddressScheme.cs index 6b62155db10..f312be7c464 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapValuesAddressScheme.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Routing/SitemapValuesAddressScheme.cs @@ -60,14 +60,7 @@ public IEnumerable FindEndpoints(RouteValuesAddress address) } } - var endpoint = new RouteEndpoint - ( - c => null, - RoutePatternFactory.Parse(path, routeValues, null), - 0, - null, - null - ); + var endpoint = new RouteEndpoint(c => null, RoutePatternFactory.Parse(path, routeValues, null), 0, null, null); return [endpoint]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/RazorPagesContentTypeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/RazorPagesContentTypeProvider.cs index 5c6391758d0..3b6eb75adff 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/RazorPagesContentTypeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/RazorPagesContentTypeProvider.cs @@ -15,10 +15,7 @@ public class RazorPagesContentTypeProvider : IRouteableContentTypeProvider private readonly SitemapsRazorPagesOptions _options; private readonly IContentDefinitionManager _contentDefinitionManager; - public RazorPagesContentTypeProvider( - IOptions options, - IContentDefinitionManager contentDefinitionManager - ) + public RazorPagesContentTypeProvider(IOptions options, IContentDefinitionManager contentDefinitionManager) { _options = options.Value; _contentDefinitionManager = contentDefinitionManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/SitemapHelperService.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/SitemapHelperService.cs index 8aaa0df2b1f..c5b037a3032 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/SitemapHelperService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/SitemapHelperService.cs @@ -21,11 +21,7 @@ public class SitemapHelperService : ISitemapHelperService private readonly ISitemapManager _sitemapManager; protected readonly IStringLocalizer S; - public SitemapHelperService( - ISlugService slugService, - ISitemapManager sitemapManager, - IStringLocalizer stringLocalizer - ) + public SitemapHelperService(ISlugService slugService, ISitemapManager sitemapManager, IStringLocalizer stringLocalizer) { _slugService = slugService; _sitemapManager = sitemapManager; @@ -43,7 +39,14 @@ public async Task ValidatePathAsync(string path, IUpdateModel updater, string si if (path.IndexOfAny(InvalidCharactersForPath) > -1 || path.IndexOf(' ') > -1) { var invalidCharactersForMessage = string.Join(", ", InvalidCharactersForPath.Select(c => $"\"{c}\"")); - updater.ModelState.AddModelError(Prefix, Path, S["Please do not use any of the following characters in your permalink: {0}. No spaces are allowed (please use dashes or underscores instead).", invalidCharactersForMessage]); + updater.ModelState.AddModelError( + Prefix, + Path, + S[ + "Please do not use any of the following characters in your permalink: {0}. No spaces are allowed (please use dashes or underscores instead).", + invalidCharactersForMessage + ] + ); } // Precludes possibility of collision with Autoroute as Autoroute excludes . as a valid path character. @@ -60,13 +63,13 @@ public async Task ValidatePathAsync(string path, IUpdateModel updater, string si var routeExists = false; if (string.IsNullOrEmpty(sitemapId)) { - routeExists = (await _sitemapManager.GetSitemapsAsync()) - .Any(p => string.Equals(p.Path, path.TrimStart('/'), StringComparison.OrdinalIgnoreCase)); + routeExists = (await _sitemapManager.GetSitemapsAsync()).Any(p => string.Equals(p.Path, path.TrimStart('/'), StringComparison.OrdinalIgnoreCase)); } else { - routeExists = (await _sitemapManager.GetSitemapsAsync()) - .Any(p => p.SitemapId != sitemapId && string.Equals(p.Path, path.TrimStart('/'), StringComparison.OrdinalIgnoreCase)); + routeExists = (await _sitemapManager.GetSitemapsAsync()).Any(p => + p.SitemapId != sitemapId && string.Equals(p.Path, path.TrimStart('/'), StringComparison.OrdinalIgnoreCase) + ); } if (routeExists) @@ -79,6 +82,5 @@ public string GetSitemapSlug(string name) { return _slugService.Slugify(name) + Sitemap.PathExtension; } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/SitemapsRobotsProvider.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/SitemapsRobotsProvider.cs index 55a0284f3f5..d02ec640c8b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/SitemapsRobotsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Services/SitemapsRobotsProvider.cs @@ -13,9 +13,7 @@ public class SitemapsRobotsProvider : IRobotsProvider private readonly ISitemapManager _sitemapManager; private readonly ISiteService _siteService; - public SitemapsRobotsProvider( - ISitemapManager sitemapManager, - ISiteService siteService) + public SitemapsRobotsProvider(ISitemapManager sitemapManager, ISiteService siteService) { _sitemapManager = sitemapManager; _siteService = siteService; diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Startup.cs index 3ea66075970..f8e7837d06f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Startup.cs @@ -1,3 +1,5 @@ +using System; +using System.Text.Json.Serialization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; @@ -23,8 +25,6 @@ using OrchardCore.Sitemaps.Recipes; using OrchardCore.Sitemaps.Routing; using OrchardCore.Sitemaps.Services; -using System; -using System.Text.Json.Serialization; namespace OrchardCore.Sitemaps { @@ -42,9 +42,9 @@ public override void ConfigureServices(IServiceCollection services) { options.GlobalRouteValues = new RouteValueDictionary { - {"Area", "OrchardCore.Sitemaps"}, - {"Controller", "Sitemap"}, - {"Action", "Index"} + { "Area", "OrchardCore.Sitemaps" }, + { "Controller", "Sitemap" }, + { "Action", "Index" } }; options.SitemapIdKey = "sitemapId"; @@ -69,9 +69,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); // Sitemap Part. - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); // Custom sitemap path. services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/CreateSitemapIndexViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/CreateSitemapIndexViewModel.cs index a2b3bfac5f2..f693be6f884 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/CreateSitemapIndexViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/CreateSitemapIndexViewModel.cs @@ -13,7 +13,6 @@ public class CreateSitemapIndexViewModel public bool Enabled { get; set; } public ContainableSitemapEntryViewModel[] ContainableSitemaps { get; set; } = []; - } public class ContainableSitemapEntryViewModel diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/CreateSourceViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/CreateSourceViewModel.cs index 12bf01a2b96..223688d1af2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/CreateSourceViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/CreateSourceViewModel.cs @@ -12,6 +12,5 @@ public class CreateSourceViewModel [BindNever] public SitemapSource SitemapSource { get; set; } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/EditSourceViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/EditSourceViewModel.cs index 494c288db5a..62e6493eb27 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/EditSourceViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/EditSourceViewModel.cs @@ -11,6 +11,5 @@ public class EditSourceViewModel [BindNever] public SitemapSource SitemapSource { get; set; } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/ListSitemapViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/ListSitemapViewModel.cs index 5174fa4e893..5ca14d7e9b6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/ListSitemapViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/ListSitemapViewModel.cs @@ -36,5 +36,4 @@ public enum ContentsBulkAction None, Remove } - } diff --git a/src/OrchardCore.Modules/OrchardCore.Sms/Activities/SmsTask.cs b/src/OrchardCore.Modules/OrchardCore.Sms/Activities/SmsTask.cs index f1dee6876be..6b6b96aaf89 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sms/Activities/SmsTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sms/Activities/SmsTask.cs @@ -14,11 +14,7 @@ public class SmsTask : TaskActivity private readonly IWorkflowExpressionEvaluator _expressionEvaluator; protected readonly IStringLocalizer S; - public SmsTask( - ISmsService smsService, - IWorkflowExpressionEvaluator expressionEvaluator, - IStringLocalizer stringLocalizer - ) + public SmsTask(ISmsService smsService, IWorkflowExpressionEvaluator expressionEvaluator, IStringLocalizer stringLocalizer) { _smsService = smsService; _expressionEvaluator = expressionEvaluator; diff --git a/src/OrchardCore.Modules/OrchardCore.Sms/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Sms/AdminMenu.cs index b0c79db75f0..35fbc7fa17a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sms/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sms/AdminMenu.cs @@ -9,11 +9,7 @@ namespace OrchardCore.Sms; public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", SmsSettings.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", SmsSettings.GroupId }, }; protected readonly IStringLocalizer S; @@ -29,25 +25,30 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["SMS"], S["SMS"].PrefixPosition(), sms => sms - .AddClass("sms") - .Id("sms") - .Action("Index", "Admin", _routeValues) - .Permission(SmsPermissions.ManageSmsSettings) - .LocalNav() - ) - .Add(S["SMS Test"], S["SMS Test"].PrefixPosition(), sms => sms - .AddClass("smstest") - .Id("smstest") - .Action(nameof(AdminController.Test), typeof(AdminController).ControllerName(), "OrchardCore.Sms") - .Permission(SmsPermissions.ManageSmsSettings) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings + .Add( + S["SMS"], + S["SMS"].PrefixPosition(), + sms => sms.AddClass("sms").Id("sms").Action("Index", "Admin", _routeValues).Permission(SmsPermissions.ManageSmsSettings).LocalNav() + ) + .Add( + S["SMS Test"], + S["SMS Test"].PrefixPosition(), + sms => + sms.AddClass("smstest") + .Id("smstest") + .Action(nameof(AdminController.Test), typeof(AdminController).ControllerName(), "OrchardCore.Sms") + .Permission(SmsPermissions.ManageSmsSettings) + .LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Sms/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Sms/Controllers/AdminController.cs index 50524101d11..6aff1ebe499 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sms/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sms/Controllers/AdminController.cs @@ -30,7 +30,8 @@ public AdminController( INotifier notifier, IAuthorizationService authorizationService, IHtmlLocalizer htmlLocalizer, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _smsProviderOptions = smsProviderOptions.Value; _phoneFormatValidator = phoneFormatValidator; @@ -79,11 +80,7 @@ public async Task Test(SmsTestViewModel model) } else { - var result = await provider.SendAsync(new SmsMessage() - { - To = model.PhoneNumber, - Body = S["This is a test SMS message."] - }); + var result = await provider.SendAsync(new SmsMessage() { To = model.PhoneNumber, Body = S["This is a test SMS message."] }); if (result.Succeeded) { @@ -105,8 +102,8 @@ public async Task Test(SmsTestViewModel model) private void PopulateModel(SmsTestViewModel model) { - model.Providers = _smsProviderOptions.Providers - .Where(entry => entry.Value.IsEnabled) + model.Providers = _smsProviderOptions + .Providers.Where(entry => entry.Value.IsEnabled) .Select(entry => new SelectListItem(entry.Key, entry.Key)) .OrderBy(item => item.Text) .ToArray(); diff --git a/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/SmsSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/SmsSettingsDisplayDriver.cs index ae34d3f81ec..259f07acc84 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/SmsSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/SmsSettingsDisplayDriver.cs @@ -34,7 +34,8 @@ public SmsSettingsDisplayDriver( IShellHost shellHost, IOptions smsProviders, ShellSettings shellSettings, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -44,26 +45,28 @@ public SmsSettingsDisplayDriver( S = stringLocalizer; } - public override IDisplayResult Edit(SmsSettings settings) - => Initialize("SmsSettings_Edit", model => - { - model.DefaultProvider = settings.DefaultProviderName; - model.Providers = _smsProviderOptions.Providers - .Where(entry => entry.Value.IsEnabled) - .Select(entry => new SelectListItem(entry.Key, entry.Key)) - .OrderBy(item => item.Text) - .ToArray(); - - }).Location("Content:1#Providers") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, SmsPermissions.ManageSmsSettings)) - .OnGroup(SmsSettings.GroupId); + public override IDisplayResult Edit(SmsSettings settings) => + Initialize( + "SmsSettings_Edit", + model => + { + model.DefaultProvider = settings.DefaultProviderName; + model.Providers = _smsProviderOptions + .Providers.Where(entry => entry.Value.IsEnabled) + .Select(entry => new SelectListItem(entry.Key, entry.Key)) + .OrderBy(item => item.Text) + .ToArray(); + } + ) + .Location("Content:1#Providers") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, SmsPermissions.ManageSmsSettings)) + .OnGroup(SmsSettings.GroupId); public override async Task UpdateAsync(SmsSettings settings, BuildEditorContext context) { var user = _httpContextAccessor.HttpContext?.User; - if (!context.GroupId.Equals(SmsSettings.GroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(user, SmsPermissions.ManageSmsSettings)) + if (!context.GroupId.Equals(SmsSettings.GroupId, StringComparison.OrdinalIgnoreCase) || !await _authorizationService.AuthorizeAsync(user, SmsPermissions.ManageSmsSettings)) { return null; } diff --git a/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/SmsTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/SmsTaskDisplayDriver.cs index 8afef0de028..a73b1ab56cf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/SmsTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/SmsTaskDisplayDriver.cs @@ -19,11 +19,7 @@ public class SmsTaskDisplayDriver : ActivityDisplayDriver stringLocalizer - ) + public SmsTaskDisplayDriver(IPhoneFormatValidator phoneFormatValidator, ILiquidTemplateManager liquidTemplateManager, IStringLocalizer stringLocalizer) { _phoneFormatValidator = phoneFormatValidator; _liquidTemplateManager = liquidTemplateManager; @@ -36,7 +32,7 @@ protected override void EditActivity(SmsTask activity, SmsTaskViewModel model) model.Body = activity.Body.Expression; } - public async override Task UpdateAsync(SmsTask activity, IUpdateModel updater) + public override async Task UpdateAsync(SmsTask activity, IUpdateModel updater) { var viewModel = new SmsTaskViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/TwilioSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/TwilioSettingsDisplayDriver.cs index ec6c7836d7b..c8816617284 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/TwilioSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sms/Drivers/TwilioSettingsDisplayDriver.cs @@ -43,7 +43,8 @@ public TwilioSettingsDisplayDriver( ShellSettings shellSettings, INotifier notifier, IHtmlLocalizer htmlLocalizer, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -58,23 +59,26 @@ public TwilioSettingsDisplayDriver( public override IDisplayResult Edit(TwilioSettings settings) { - return Initialize("TwilioSettings_Edit", model => - { - model.IsEnabled = settings.IsEnabled; - model.PhoneNumber = settings.PhoneNumber; - model.AccountSID = settings.AccountSID; - model.HasAuthToken = !string.IsNullOrEmpty(settings.AuthToken); - }).Location("Content:5#Twilio") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, SmsPermissions.ManageSmsSettings)) - .OnGroup(SmsSettings.GroupId); + return Initialize( + "TwilioSettings_Edit", + model => + { + model.IsEnabled = settings.IsEnabled; + model.PhoneNumber = settings.PhoneNumber; + model.AccountSID = settings.AccountSID; + model.HasAuthToken = !string.IsNullOrEmpty(settings.AuthToken); + } + ) + .Location("Content:5#Twilio") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, SmsPermissions.ManageSmsSettings)) + .OnGroup(SmsSettings.GroupId); } public override async Task UpdateAsync(ISite site, TwilioSettings settings, IUpdateModel updater, BuildEditorContext context) { var user = _httpContextAccessor.HttpContext?.User; - if (!context.GroupId.Equals(SmsSettings.GroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(user, SmsPermissions.ManageSmsSettings)) + if (!context.GroupId.Equals(SmsSettings.GroupId, StringComparison.OrdinalIgnoreCase) || !await _authorizationService.AuthorizeAsync(user, SmsPermissions.ManageSmsSettings)) { return null; } @@ -91,7 +95,11 @@ public override async Task UpdateAsync(ISite site, TwilioSetting if (hasChanges && smsSettings.DefaultProviderName == TwilioSmsProvider.TechnicalName) { - await _notifier.WarningAsync(H["You have successfully disabled the default SMS provider. The SMS service is now disable and will remain disabled until you designate a new default provider."]); + await _notifier.WarningAsync( + H[ + "You have successfully disabled the default SMS provider. The SMS service is now disable and will remain disabled until you designate a new default provider." + ] + ); smsSettings.DefaultProviderName = null; diff --git a/src/OrchardCore.Modules/OrchardCore.Sms/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Sms/Manifest.cs index 79948c20652..be288d56904 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sms/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sms/Manifest.cs @@ -1,26 +1,13 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] -[assembly: Feature( - Name = "SMS", - Id = "OrchardCore.Sms", - Description = "Provides settings and services to send SMS messages.", - Category = "SMS" -)] +[assembly: Feature(Name = "SMS", Id = "OrchardCore.Sms", Description = "Provides settings and services to send SMS messages.", Category = "SMS")] [assembly: Feature( Name = "SMS Notifications", Id = "OrchardCore.Notifications.Sms", Description = "Provides a way to send SMS notifications to users.", Category = "Notifications", - Dependencies = - [ - "OrchardCore.Notifications", - "OrchardCore.Sms", - ] + Dependencies = ["OrchardCore.Notifications", "OrchardCore.Sms",] )] diff --git a/src/OrchardCore.Modules/OrchardCore.Sms/SmsPermissionProvider.cs b/src/OrchardCore.Modules/OrchardCore.Sms/SmsPermissionProvider.cs index 56133661a61..f686eaf62b5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sms/SmsPermissionProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sms/SmsPermissionProvider.cs @@ -8,20 +8,9 @@ public class SmsPermissionProvider : IPermissionProvider { public static readonly Permission ManageSmsSettings = SmsPermissions.ManageSmsSettings; - private readonly IEnumerable _allPermissions = - [ - ManageSmsSettings, - ]; + private readonly IEnumerable _allPermissions = [ManageSmsSettings,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Sms/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Sms/Startup.cs index 6757fcb43ec..af877afd321 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sms/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sms/Startup.cs @@ -32,8 +32,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddLogSmsProvider(); } - services.AddTwilioSmsProvider() - .AddScoped, TwilioSettingsDisplayDriver>(); + services.AddTwilioSmsProvider().AddScoped, TwilioSettingsDisplayDriver>(); services.AddScoped(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Spatial/Drivers/GeoPointFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Spatial/Drivers/GeoPointFieldDisplayDriver.cs index cbdf28fb36d..35fd8f4ac52 100644 --- a/src/OrchardCore.Modules/OrchardCore.Spatial/Drivers/GeoPointFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Spatial/Drivers/GeoPointFieldDisplayDriver.cs @@ -26,26 +26,32 @@ public GeoPointFieldDisplayDriver(IStringLocalizer l public override IDisplayResult Display(GeoPointField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) .Location("Detail", "Content") .Location("Summary", "Content"); } public override IDisplayResult Edit(GeoPointField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.Latitude = Convert.ToString(field.Latitude, CultureInfo.InvariantCulture); - model.Longitude = Convert.ToString(field.Longitude, CultureInfo.InvariantCulture); - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + return Initialize( + GetEditorShapeType(context), + model => + { + model.Latitude = Convert.ToString(field.Latitude, CultureInfo.InvariantCulture); + model.Longitude = Convert.ToString(field.Longitude, CultureInfo.InvariantCulture); + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(GeoPointField field, IUpdateModel updater, UpdateFieldEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Spatial/Drivers/GeoPointFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.Spatial/Drivers/GeoPointFieldSettingsDriver.cs index d33fcdce8c1..8bf163800cd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Spatial/Drivers/GeoPointFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Spatial/Drivers/GeoPointFieldSettingsDriver.cs @@ -12,13 +12,16 @@ public class GeoPointFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriv { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("GeoPointFieldSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "GeoPointFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Hint = settings.Hint; - model.Required = settings.Required; - }) + model.Hint = settings.Hint; + model.Required = settings.Required; + } + ) .Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Spatial/Indexing/GeoPointFieldIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Spatial/Indexing/GeoPointFieldIndexHandler.cs index 9e66d3f269c..8433626763c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Spatial/Indexing/GeoPointFieldIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Spatial/Indexing/GeoPointFieldIndexHandler.cs @@ -13,11 +13,7 @@ public override Task BuildIndexAsync(GeoPointField field, BuildFieldIndexContext if (field.Longitude != null && field.Latitude != null) { - value = new DocumentIndex.GeoPoint - { - Longitude = (decimal)field.Longitude, - Latitude = (decimal)field.Latitude - }; + value = new DocumentIndex.GeoPoint { Longitude = (decimal)field.Longitude, Latitude = (decimal)field.Latitude }; } foreach (var key in context.Keys) diff --git a/src/OrchardCore.Modules/OrchardCore.Spatial/ResourceManagementOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Spatial/ResourceManagementOptionsConfiguration.cs index 0d2f4de2a8d..a92e6056d12 100644 --- a/src/OrchardCore.Modules/OrchardCore.Spatial/ResourceManagementOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Spatial/ResourceManagementOptionsConfiguration.cs @@ -15,14 +15,20 @@ static ResourceManagementOptionsConfiguration() .DefineScript("leaflet") .SetUrl("/OrchardCore.Spatial/Scripts/leaflet/leaflet.js", "/OrchardCore.Spatial/Scripts/leaflet/leaflet-src.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.js", "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet-src.js") - .SetCdnIntegrity("sha384-cxOPjt7s7Iz04uaHJceBmS+qpjv2JkIHNVcuOrM+YHwZOmJGBXI00mdUXEq65HTH", "sha384-4aETf8z71hiSsoK0xYsa5JtiJHfL3h7uMAsZ2QYOLvcySDL/cEDfdLt0SaBypTQZ") + .SetCdnIntegrity( + "sha384-cxOPjt7s7Iz04uaHJceBmS+qpjv2JkIHNVcuOrM+YHwZOmJGBXI00mdUXEq65HTH", + "sha384-4aETf8z71hiSsoK0xYsa5JtiJHfL3h7uMAsZ2QYOLvcySDL/cEDfdLt0SaBypTQZ" + ) .SetVersion("1.9.4"); _manifest .DefineStyle("leaflet") .SetUrl("/OrchardCore.Spatial/Styles/leaflet.min.css", "/OrchardCore.Spatial/Styles/leaflet.css") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css", "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.css") - .SetCdnIntegrity("sha384-c6Rcwz4e4CITMbu/NBmnNS8yN2sC3cUElMEMfP3vqqKFp7GOYaaBBCqmaWBjmkjb", "sha384-sHL9NAb7lN7rfvG5lfHpm643Xkcjzp4jFvuavGOndn6pjVqS6ny56CAt3nsEVT4H") + .SetCdnIntegrity( + "sha384-c6Rcwz4e4CITMbu/NBmnNS8yN2sC3cUElMEMfP3vqqKFp7GOYaaBBCqmaWBjmkjb", + "sha384-sHL9NAb7lN7rfvG5lfHpm643Xkcjzp4jFvuavGOndn6pjVqS6ny56CAt3nsEVT4H" + ) .SetVersion("1.9.4"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Spatial/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Spatial/Startup.cs index ec64a35dec1..184146a96e0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Spatial/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Spatial/Startup.cs @@ -22,9 +22,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddTransient, ResourceManagementOptionsConfiguration>(); // Coordinate Field - services.AddContentField() - .UseDisplayDriver() - .AddHandler(); + services.AddContentField().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/AdminMenu.cs index 9f556d2a5d7..3831b72f615 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/AdminMenu.cs @@ -8,11 +8,8 @@ namespace OrchardCore.Taxonomies { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", TaxonomyContentsAdminListSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = + new() { { "area", "OrchardCore.Settings" }, { "groupId", TaxonomyContentsAdminListSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -28,18 +25,26 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], "1", settings => settings - .Add(S["Taxonomy Filters"], S["Taxonomy Filters"].PrefixPosition(), filters => filters - .AddClass("taxonomyfilters") - .Id("taxonomyfilters") - .Permission(Permissions.ManageTaxonomies) - .Action("Index", "Admin", _routeValues) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + "1", + settings => + settings.Add( + S["Taxonomy Filters"], + S["Taxonomy Filters"].PrefixPosition(), + filters => + filters + .AddClass("taxonomyfilters") + .Id("taxonomyfilters") + .Permission(Permissions.ManageTaxonomies) + .Action("Index", "Admin", _routeValues) + .LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Controllers/AdminController.cs index 08b5ad0b717..e39c345fccd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Controllers/AdminController.cs @@ -37,7 +37,8 @@ public AdminController( IContentDefinitionManager contentDefinitionManager, INotifier notifier, IHtmlLocalizer localizer, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _contentManager = contentManager; _authorizationService = authorizationService; @@ -263,11 +264,10 @@ public async Task EditPost(string taxonomyContentItemId, string t return View(model); } - taxonomyItem.Merge((JsonObject)contentItem.Content, new JsonMergeSettings - { - MergeArrayHandling = MergeArrayHandling.Replace, - MergeNullValueHandling = MergeNullValueHandling.Merge - }); + taxonomyItem.Merge( + (JsonObject)contentItem.Content, + new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge } + ); // Merge doesn't copy the properties. taxonomyItem[nameof(ContentItem.DisplayText)] = contentItem.DisplayText; diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Controllers/TagController.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Controllers/TagController.cs index a598ea8e370..4dbe2f2501d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Controllers/TagController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Controllers/TagController.cs @@ -33,7 +33,8 @@ public TagController( IContentDefinitionManager contentDefinitionManager, IEnumerable contentHandlers, ISession session, - ILogger logger) + ILogger logger + ) { _contentManager = contentManager; _authorizationService = authorizationService; @@ -71,7 +72,7 @@ public async Task CreatePost(string taxonomyContentItemId, string // Create tag term but only run content handlers not content item display manager update editor. // This creates empty parts, if parts are attached to the tag term, with empty data. - // But still generates valid autoroute paths from the handler. + // But still generates valid autoroute paths from the handler. var contentItem = await _contentManager.NewAsync(part.TermContentType); contentItem.DisplayText = displayText; contentItem.Weld(); @@ -100,11 +101,7 @@ public async Task CreatePost(string taxonomyContentItemId, string await _session.SaveAsync(taxonomy); } - var viewModel = new CreatedTagViewModel - { - ContentItemId = contentItem.ContentItemId, - DisplayText = contentItem.DisplayText - }; + var viewModel = new CreatedTagViewModel { ContentItemId = contentItem.ContentItemId, DisplayText = contentItem.DisplayText }; return Ok(viewModel); } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyContentsAdminListDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyContentsAdminListDisplayDriver.cs index 865ea3d37a4..39573562384 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyContentsAdminListDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyContentsAdminListDisplayDriver.cs @@ -34,7 +34,8 @@ public TaxonomyContentsAdminListDisplayDriver( ISiteService siteService, IContentManager contentManager, IContentDefinitionManager contentDefinitionManager, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _siteService = siteService; _contentManager = contentManager; @@ -55,8 +56,7 @@ public override async Task EditAsync(ContentOptionsViewModel mod if (!string.IsNullOrEmpty(model.SelectedContentType)) { var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(model.SelectedContentType); - var fieldDefinitions = contentTypeDefinition - .Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(TaxonomyField))); + var fieldDefinitions = contentTypeDefinition.Parts.SelectMany(x => x.PartDefinition.Fields.Where(f => f.FieldDefinition.Name == nameof(TaxonomyField))); var fieldTaxonomyContentItemIds = fieldDefinitions.Select(x => x.GetSettings().TaxonomyContentItemId); taxonomyContentItemIds = taxonomyContentItemIds.Intersect(fieldTaxonomyContentItemIds).ToArray(); @@ -73,34 +73,37 @@ public override async Task EditAsync(ContentOptionsViewModel mod foreach (var taxonomy in taxonomies) { results.Add( - Initialize("ContentsAdminListTaxonomyFilter", m => - { - using var sb = ZString.CreateStringBuilder(); - var termEntries = new List(); - PopulateTermEntries(termEntries, taxonomy.As().Terms, 0); - var terms = new List - { - new() { Text = S["Clear filter"], Value = "" }, - new() { Text = S["Show all"], Value = "Taxonomy:" + taxonomy.ContentItemId } - }; - - foreach (var term in termEntries) - { - sb.Clear(); - for (var l = 0; l < term.Level; l++) + Initialize( + "ContentsAdminListTaxonomyFilter", + m => { - sb.Append(LevelPadding); + using var sb = ZString.CreateStringBuilder(); + var termEntries = new List(); + PopulateTermEntries(termEntries, taxonomy.As().Terms, 0); + var terms = new List + { + new() { Text = S["Clear filter"], Value = "" }, + new() { Text = S["Show all"], Value = "Taxonomy:" + taxonomy.ContentItemId } + }; + + foreach (var term in termEntries) + { + sb.Clear(); + for (var l = 0; l < term.Level; l++) + { + sb.Append(LevelPadding); + } + sb.Append(term.DisplayText); + var item = new SelectListItem { Text = sb.ToString(), Value = "Term:" + term.ContentItemId }; + terms.Add(item); + } + + m.DisplayText = taxonomy.DisplayText; + m.Taxonomies = terms; } - sb.Append(term.DisplayText); - var item = new SelectListItem { Text = sb.ToString(), Value = "Term:" + term.ContentItemId }; - terms.Add(item); - } - - m.DisplayText = taxonomy.DisplayText; - m.Taxonomies = terms; - }) - .Location("Actions:40." + position) - .Prefix("Taxonomy" + taxonomy.ContentItemId) + ) + .Location("Actions:40." + position) + .Prefix("Taxonomy" + taxonomy.ContentItemId) ); position += 5; diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyFieldDisplayDriver.cs index 0654ec92aa9..7cce7e17a82 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyFieldDisplayDriver.cs @@ -20,9 +20,7 @@ public class TaxonomyFieldDisplayDriver : ContentFieldDisplayDriver localizer) + public TaxonomyFieldDisplayDriver(IContentManager contentManager, IStringLocalizer localizer) { _contentManager = contentManager; S = localizer; @@ -30,36 +28,42 @@ public TaxonomyFieldDisplayDriver( public override IDisplayResult Display(TaxonomyField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(TaxonomyField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), async model => - { - var settings = context.PartFieldDefinition.GetSettings(); - model.Taxonomy = await _contentManager.GetAsync(settings.TaxonomyContentItemId, VersionOptions.Latest); - - if (model.Taxonomy != null) + return Initialize( + GetEditorShapeType(context), + async model => { - var termEntries = new List(); - TaxonomyFieldDriverHelper.PopulateTermEntries(termEntries, field, model.Taxonomy.As().Terms, 0); + var settings = context.PartFieldDefinition.GetSettings(); + model.Taxonomy = await _contentManager.GetAsync(settings.TaxonomyContentItemId, VersionOptions.Latest); - model.TermEntries = termEntries; - model.UniqueValue = termEntries.FirstOrDefault(x => x.Selected)?.ContentItemId; - } + if (model.Taxonomy != null) + { + var termEntries = new List(); + TaxonomyFieldDriverHelper.PopulateTermEntries(termEntries, field, model.Taxonomy.As().Terms, 0); + + model.TermEntries = termEntries; + model.UniqueValue = termEntries.FirstOrDefault(x => x.Selected)?.ContentItemId; + } - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ); } public override async Task UpdateAsync(TaxonomyField field, IUpdateModel updater, UpdateFieldEditorContext context) @@ -80,9 +84,7 @@ public override async Task UpdateAsync(TaxonomyField field, IUpd if (settings.Required && field.TermContentItemIds.Length == 0) { - updater.ModelState.AddModelError( - nameof(EditTaxonomyFieldViewModel.TermEntries), - S["A value is required for '{0}'", context.PartFieldDefinition.DisplayName()]); + updater.ModelState.AddModelError(nameof(EditTaxonomyFieldViewModel.TermEntries), S["A value is required for '{0}'", context.PartFieldDefinition.DisplayName()]); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyFieldTagsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyFieldTagsDisplayDriver.cs index cefbac24312..aeaac7d1436 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyFieldTagsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyFieldTagsDisplayDriver.cs @@ -23,9 +23,7 @@ public class TaxonomyFieldTagsDisplayDriver : ContentFieldDisplayDriver s) + public TaxonomyFieldTagsDisplayDriver(IContentManager contentManager, IStringLocalizer s) { _contentManager = contentManager; S = s; @@ -33,42 +31,48 @@ public TaxonomyFieldTagsDisplayDriver( public override IDisplayResult Display(TaxonomyField field, BuildFieldDisplayContext context) { - return Initialize(GetDisplayShapeType(context), model => - { - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }) - .Location("Detail", "Content") - .Location("Summary", "Content"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; + } + ) + .Location("Detail", "Content") + .Location("Summary", "Content"); } public override IDisplayResult Edit(TaxonomyField field, BuildFieldEditorContext context) { - return Initialize(GetEditorShapeType(context), async model => - { - var settings = context.PartFieldDefinition.GetSettings(); - model.Taxonomy = await _contentManager.GetAsync(settings.TaxonomyContentItemId, VersionOptions.Latest); - - if (model.Taxonomy != null) + return Initialize( + GetEditorShapeType(context), + async model => { - var termEntries = new List(); - TaxonomyFieldDriverHelper.PopulateTermEntries(termEntries, field, model.Taxonomy.As().Terms, 0); - var tagTermEntries = termEntries.Select(te => new TagTermEntry - { - ContentItemId = te.ContentItemId, - Selected = te.Selected, - DisplayText = te.Term.DisplayText, - IsLeaf = te.IsLeaf - }); + var settings = context.PartFieldDefinition.GetSettings(); + model.Taxonomy = await _contentManager.GetAsync(settings.TaxonomyContentItemId, VersionOptions.Latest); - model.TagTermEntries = JNode.FromObject(tagTermEntries, JOptions.CamelCase).ToJsonString(JOptions.Default); + if (model.Taxonomy != null) + { + var termEntries = new List(); + TaxonomyFieldDriverHelper.PopulateTermEntries(termEntries, field, model.Taxonomy.As().Terms, 0); + var tagTermEntries = termEntries.Select(te => new TagTermEntry + { + ContentItemId = te.ContentItemId, + Selected = te.Selected, + DisplayText = te.Term.DisplayText, + IsLeaf = te.IsLeaf + }); + + model.TagTermEntries = JNode.FromObject(tagTermEntries, JOptions.CamelCase).ToJsonString(JOptions.Default); + } + + model.Field = field; + model.Part = context.ContentPart; + model.PartFieldDefinition = context.PartFieldDefinition; } - - model.Field = field; - model.Part = context.ContentPart; - model.PartFieldDefinition = context.PartFieldDefinition; - }); + ); } public override async Task UpdateAsync(TaxonomyField field, IUpdateModel updater, UpdateFieldEditorContext context) @@ -81,14 +85,14 @@ public override async Task UpdateAsync(TaxonomyField field, IUpd field.TaxonomyContentItemId = settings.TaxonomyContentItemId; - field.TermContentItemIds = model.TermContentItemIds == null - ? [] : model.TermContentItemIds.Split(',', StringSplitOptions.RemoveEmptyEntries); + field.TermContentItemIds = model.TermContentItemIds == null ? [] : model.TermContentItemIds.Split(',', StringSplitOptions.RemoveEmptyEntries); if (settings.Required && field.TermContentItemIds.Length == 0) { updater.ModelState.AddModelError( nameof(EditTagTaxonomyFieldViewModel.TermContentItemIds), - S["A value is required for '{0}'", context.PartFieldDefinition.DisplayName()]); + S["A value is required for '{0}'", context.PartFieldDefinition.DisplayName()] + ); } // Update display text for tags. @@ -103,9 +107,7 @@ public override async Task UpdateAsync(TaxonomyField field, IUpd foreach (var termContentItemId in field.TermContentItemIds) { - var term = TaxonomyOrchardHelperExtensions.FindTerm( - (JsonArray)taxonomy.Content["TaxonomyPart"]["Terms"], - termContentItemId); + var term = TaxonomyOrchardHelperExtensions.FindTerm((JsonArray)taxonomy.Content["TaxonomyPart"]["Terms"], termContentItemId); terms.Add(term); } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyPartDisplayDriver.cs index df668d7331f..0fbbdd7f162 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TaxonomyPartDisplayDriver.cs @@ -27,21 +27,27 @@ public TaxonomyPartDisplayDriver(IStringLocalizer str public override IDisplayResult Display(TaxonomyPart part, BuildPartDisplayContext context) { var hasItems = part.Terms.Count > 0; - return Initialize(hasItems ? "TaxonomyPart" : "TaxonomyPart_Empty", m => - { - m.ContentItem = part.ContentItem; - m.TaxonomyPart = part; - }) - .Location("Detail", "Content"); + return Initialize( + hasItems ? "TaxonomyPart" : "TaxonomyPart_Empty", + m => + { + m.ContentItem = part.ContentItem; + m.TaxonomyPart = part; + } + ) + .Location("Detail", "Content"); } public override IDisplayResult Edit(TaxonomyPart part) { - return Initialize("TaxonomyPart_Edit", model => - { - model.TermContentType = part.TermContentType; - model.TaxonomyPart = part; - }); + return Initialize( + "TaxonomyPart_Edit", + model => + { + model.TermContentType = part.TermContentType; + model.TaxonomyPart = part; + } + ); } public override async Task UpdateAsync(TaxonomyPart part, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TermPartContentDriver.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TermPartContentDriver.cs index 82c0f02e403..ebe168996e7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TermPartContentDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Drivers/TermPartContentDriver.cs @@ -24,10 +24,7 @@ public class TermPartContentDriver : ContentDisplayDriver private readonly PagerOptions _pagerOptions; private readonly IContentManager _contentManager; - public TermPartContentDriver( - ISession session, - IOptions pagerOptions, - IContentManager contentManager) + public TermPartContentDriver(ISession session, IOptions pagerOptions, IContentManager contentManager) { _session = session; _pagerOptions = pagerOptions.Value; @@ -39,15 +36,20 @@ public override Task DisplayAsync(ContentItem model, BuildDispla var part = model.As(); if (part != null) { - return Task.FromResult(Initialize("TermPart", async m => - { - var pager = await GetPagerAsync(context.Updater, _pagerOptions.GetPageSize()); - m.TaxonomyContentItemId = part.TaxonomyContentItemId; - m.ContentItem = part.ContentItem; - m.ContentItems = (await QueryTermItemsAsync(part, pager)).ToArray(); - m.Pager = await context.New.PagerSlim(pager); - }) - .Location("Detail", "Content:5")); + return Task.FromResult( + Initialize( + "TermPart", + async m => + { + var pager = await GetPagerAsync(context.Updater, _pagerOptions.GetPageSize()); + m.TaxonomyContentItemId = part.TaxonomyContentItemId; + m.ContentItem = part.ContentItem; + m.ContentItems = (await QueryTermItemsAsync(part, pager)).ToArray(); + m.Pager = await context.New.PagerSlim(pager); + } + ) + .Location("Detail", "Content:5") + ); } return Task.FromResult(null); @@ -58,7 +60,8 @@ private async Task> QueryTermItemsAsync(TermPart termPa if (pager.Before != null) { var beforeValue = new DateTime(long.Parse(pager.Before)); - var query = _session.Query() + var query = _session + .Query() .With(x => x.TermContentItemId == termPart.ContentItem.ContentItemId) .With(CreateContentIndexFilter(beforeValue, null)) .OrderBy(x => x.CreatedUtc) @@ -88,7 +91,8 @@ private async Task> QueryTermItemsAsync(TermPart termPa else if (pager.After != null) { var afterValue = new DateTime(long.Parse(pager.After)); - var query = _session.Query() + var query = _session + .Query() .With(x => x.TermContentItemId == termPart.ContentItem.ContentItemId) .With(CreateContentIndexFilter(null, afterValue)) .OrderByDescending(x => x.CreatedUtc) @@ -115,7 +119,8 @@ private async Task> QueryTermItemsAsync(TermPart termPa } else { - var query = _session.Query() + var query = _session + .Query() .With(x => x.TermContentItemId == termPart.ContentItem.ContentItemId) .With(CreateContentIndexFilter(null, null)) .OrderByDescending(x => x.CreatedUtc) diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Fields/TagNamesExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Fields/TagNamesExtensions.cs index 2c8dc075fd3..d68975d9be3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Fields/TagNamesExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Fields/TagNamesExtensions.cs @@ -6,7 +6,7 @@ public static class TagNamesExtensions { /// /// Tag names are a less well known property of a taxonomy field - /// managed by the tags editor and tags display mode. + /// managed by the tags editor and tags display mode. /// public static string[] GetTagNames(this TaxonomyField taxonomyField) { diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/GraphQL/TaxonomyFieldQueryObjectType.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/GraphQL/TaxonomyFieldQueryObjectType.cs index ad4942e525d..4d1eefad881 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/GraphQL/TaxonomyFieldQueryObjectType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/GraphQL/TaxonomyFieldQueryObjectType.cs @@ -49,9 +49,7 @@ public TaxonomyFieldQueryObjectType() foreach (var termContentItemId in ids) { - var term = TaxonomyOrchardHelperExtensions.FindTerm( - (JsonArray)taxonomy.Content["TaxonomyPart"]["Terms"], - termContentItemId); + var term = TaxonomyOrchardHelperExtensions.FindTerm((JsonArray)taxonomy.Content["TaxonomyPart"]["Terms"], termContentItemId); terms.Add(term); } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Handlers/TaxonomyPartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Handlers/TaxonomyPartHandler.cs index 58fd760402c..b85d534be6c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Handlers/TaxonomyPartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Handlers/TaxonomyPartHandler.cs @@ -12,10 +12,12 @@ public override Task GetContentItemAspectAsync(ContentItemAspectContext context, { return context.ForAsync(aspect => { - aspect.Accessors.Add((jsonObject) => - { - return jsonObject["TaxonomyPart"]["Terms"] as JsonArray; - }); + aspect.Accessors.Add( + (jsonObject) => + { + return jsonObject["TaxonomyPart"]["Terms"] as JsonArray; + } + ); return Task.CompletedTask; }); diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Handlers/TermPartContentHandler.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Handlers/TermPartContentHandler.cs index 2fde41a6d46..ff5a6c4fccc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Handlers/TermPartContentHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Handlers/TermPartContentHandler.cs @@ -14,10 +14,12 @@ public override Task GetContentItemAspectAsync(ContentItemAspectContext context) // Check this content item contains Terms. if (((JsonNode)context.ContentItem.Content)["Terms"] is JsonArray) { - aspect.Accessors.Add((jsonObject) => - { - return jsonObject["Terms"] as JsonArray; - }); + aspect.Accessors.Add( + (jsonObject) => + { + return jsonObject["Terms"] as JsonArray; + } + ); } return Task.CompletedTask; diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Helper/TaxonomyOrchardHelperExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Helper/TaxonomyOrchardHelperExtensions.cs index a533078fa5e..0f3f9dc30b5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Helper/TaxonomyOrchardHelperExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Helper/TaxonomyOrchardHelperExtensions.cs @@ -60,7 +60,10 @@ public static async Task> GetInheritedTermsAsync(this IOrchard /// /// Query content items. /// - public static async Task> QueryCategorizedContentItemsAsync(this IOrchardHelper orchardHelper, Func, IQuery> query) + public static async Task> QueryCategorizedContentItemsAsync( + this IOrchardHelper orchardHelper, + Func, IQuery> query + ) { var contentManager = orchardHelper.HttpContext.RequestServices.GetService(); var session = orchardHelper.HttpContext.RequestServices.GetService(); diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Indexing/TaxonomyIndex.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Indexing/TaxonomyIndex.cs index a0500909d4e..c63c13cc3e3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Indexing/TaxonomyIndex.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Indexing/TaxonomyIndex.cs @@ -36,7 +36,8 @@ public TaxonomyIndexProvider(IServiceProvider serviceProvider) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(async contentItem => { // Remove index records of soft deleted items. @@ -96,17 +97,19 @@ public override void Describe(DescribeContext context) foreach (var termContentItemId in field.TermContentItemIds) { - results.Add(new TaxonomyIndex - { - TaxonomyContentItemId = field.TaxonomyContentItemId, - ContentItemId = contentItem.ContentItemId, - ContentType = contentItem.ContentType, - ContentPart = fieldDefinition.PartDefinition.Name, - ContentField = fieldDefinition.Name, - TermContentItemId = termContentItemId, - Published = contentItem.Published, - Latest = contentItem.Latest - }); + results.Add( + new TaxonomyIndex + { + TaxonomyContentItemId = field.TaxonomyContentItemId, + ContentItemId = contentItem.ContentItemId, + ContentType = contentItem.ContentType, + ContentPart = fieldDefinition.PartDefinition.Name, + ContentField = fieldDefinition.Name, + TermContentItemId = termContentItemId, + Published = contentItem.Published, + Latest = contentItem.Latest + } + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Liquid/InheritedTermsFilter.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Liquid/InheritedTermsFilter.cs index 7bb674db146..60026b7abf8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Liquid/InheritedTermsFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Liquid/InheritedTermsFilter.cs @@ -19,9 +19,7 @@ public InheritedTermsFilter(IContentManager contentManager) public async ValueTask ProcessAsync(FluidValue input, FilterArguments arguments, LiquidTemplateContext ctx) { - var termContentItemId = input.Type == FluidValues.Object && input.ToObjectValue() is ContentItem term - ? term.ContentItemId - : input.ToStringValue(); + var termContentItemId = input.Type == FluidValues.Object && input.ToObjectValue() is ContentItem term ? term.ContentItemId : input.ToStringValue(); var firstArg = arguments.At(0); if (firstArg.Type != FluidValues.Object || input.ToObjectValue() is not ContentItem taxonomy) diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Liquid/TaxonomyTermsFilter.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Liquid/TaxonomyTermsFilter.cs index ad2f392701a..e8bca4c1578 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Liquid/TaxonomyTermsFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Liquid/TaxonomyTermsFilter.cs @@ -29,10 +29,12 @@ public async ValueTask ProcessAsync(FluidValue input, FilterArgument taxonomyContentItemId = field.TaxonomyContentItemId; termContentItemIds = field.TermContentItemIds; } - else if (input.Type == FluidValues.Object + else if ( + input.Type == FluidValues.Object && input.ToObjectValue() is JsonObject jobj && jobj.ContainsKey(nameof(TaxonomyField.TermContentItemIds)) - && jobj.ContainsKey(nameof(TaxonomyField.TaxonomyContentItemId))) + && jobj.ContainsKey(nameof(TaxonomyField.TaxonomyContentItemId)) + ) { taxonomyContentItemId = jobj["TaxonomyContentItemId"].Value(); termContentItemIds = jobj["TermContentItemIds"].Values().ToArray(); @@ -58,9 +60,7 @@ public async ValueTask ProcessAsync(FluidValue input, FilterArgument foreach (var termContentItemId in termContentItemIds) { - var term = TaxonomyOrchardHelperExtensions.FindTerm( - (JsonArray)taxonomy.Content["TaxonomyPart"]["Terms"], - termContentItemId); + var term = TaxonomyOrchardHelperExtensions.FindTerm((JsonArray)taxonomy.Content["TaxonomyPart"]["Terms"], termContentItemId); if (term is not null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Manifest.cs index df7190dfb2f..fbe19794964 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Manifest.cs @@ -1,11 +1,6 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Taxonomies", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Taxonomies", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Taxonomies", diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Migrations.cs index 15aa789f3b2..f5b7a1d955a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Migrations.cs @@ -21,59 +21,45 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterTypeDefinitionAsync("Taxonomy", taxonomy => taxonomy - .Draftable() - .Versionable() - .Creatable() - .Listable() - .WithPart("TitlePart", part => part.WithPosition("1")) - .WithPart("AliasPart", part => part - .WithPosition("2") - .WithSettings(new AliasPartSettings - { - Pattern = "{{ Model.ContentItem | display_text | slugify }}" - })) - .WithPart("AutoroutePart", part => part - .WithPosition("3") - .WithSettings(new AutoroutePartSettings - { - Pattern = "{{ Model.ContentItem | display_text | slugify }}", - AllowRouteContainedItems = true - })) - .WithPart("TaxonomyPart", part => part.WithPosition("4")) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Taxonomy", + taxonomy => + taxonomy + .Draftable() + .Versionable() + .Creatable() + .Listable() + .WithPart("TitlePart", part => part.WithPosition("1")) + .WithPart("AliasPart", part => part.WithPosition("2").WithSettings(new AliasPartSettings { Pattern = "{{ Model.ContentItem | display_text | slugify }}" })) + .WithPart( + "AutoroutePart", + part => + part.WithPosition("3") + .WithSettings(new AutoroutePartSettings { Pattern = "{{ Model.ContentItem | display_text | slugify }}", AllowRouteContainedItems = true }) + ) + .WithPart("TaxonomyPart", part => part.WithPosition("4")) ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("TaxonomyContentItemId", c => c.WithLength(26)) - .Column("ContentItemId", c => c.WithLength(26)) - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) - .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) - .Column("TermContentItemId", column => column.WithLength(26)) - .Column("Published", c => c.WithDefault(true)) - .Column("Latest", c => c.WithDefault(false)) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("TaxonomyContentItemId", c => c.WithLength(26)) + .Column("ContentItemId", c => c.WithLength(26)) + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize)) + .Column("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize)) + .Column("TermContentItemId", column => column.WithLength(26)) + .Column("Published", c => c.WithDefault(true)) + .Column("Latest", c => c.WithDefault(false)) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TaxonomyIndex_DocumentId", - "DocumentId", - "TaxonomyContentItemId", - "ContentItemId", - "TermContentItemId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TaxonomyIndex_DocumentId", "DocumentId", "TaxonomyContentItemId", "ContentItemId", "TermContentItemId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TaxonomyIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TaxonomyIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); // Shortcut other migration steps on new content definition schemas. @@ -91,15 +77,17 @@ public async Task UpdateFrom1Async() // This code can be removed in a later version. public async Task UpdateFrom2Async() { - await _contentDefinitionManager.AlterTypeDefinitionAsync("Taxonomy", taxonomy => taxonomy - .WithPart("AutoroutePart", part => part - .WithPosition("3") - .WithSettings(new AutoroutePartSettings - { - Pattern = "{{ Model.ContentItem | display_text | slugify }}", - AllowRouteContainedItems = true - })) - .WithPart("TaxonomyPart", part => part.WithPosition("4")) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + "Taxonomy", + taxonomy => + taxonomy + .WithPart( + "AutoroutePart", + part => + part.WithPosition("3") + .WithSettings(new AutoroutePartSettings { Pattern = "{{ Model.ContentItem | display_text | slugify }}", AllowRouteContainedItems = true }) + ) + .WithPart("TaxonomyPart", part => part.WithPosition("4")) ); return 3; @@ -109,35 +97,19 @@ await _contentDefinitionManager.AlterTypeDefinitionAsync("Taxonomy", taxonomy => public async Task UpdateFrom3Async() { // This step has been updated to also add these new columns. - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Published", c => c.WithDefault(true)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Published", c => c.WithDefault(true))); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Latest", c => c.WithDefault(false)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Latest", c => c.WithDefault(false))); // So that the new indexes can be fully created. - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TaxonomyIndex_DocumentId", - "DocumentId", - "TaxonomyContentItemId", - "ContentItemId", - "TermContentItemId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TaxonomyIndex_DocumentId", "DocumentId", "TaxonomyContentItemId", "ContentItemId", "TermContentItemId", "Published", "Latest") ); // The index in MySQL can accommodate up to 768 characters or 3072 bytes. // DocumentId (2) + ContentType (254) + ContentPart (254) + ContentField (254) + Published and Latest (1) = 765 (< 768). - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TaxonomyIndex_DocumentId_ContentType", - "DocumentId", - "ContentType(254)", - "ContentPart(254)", - "ContentField(254)", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_TaxonomyIndex_DocumentId_ContentType", "DocumentId", "ContentType(254)", "ContentPart(254)", "ContentField(254)", "Published", "Latest") ); // We then shortcut the next migration step. @@ -149,21 +121,12 @@ public async Task UpdateFrom4Async() { // This step run only if the previous one was executed before // it was updated, so here we also add the following columns. - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Published", c => c.WithDefault(true)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Published", c => c.WithDefault(true))); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Latest", c => c.WithDefault(false)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Latest", c => c.WithDefault(false))); // But we create a separate index for these new columns. - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_TaxonomyIndex_DocumentId_Published", - "DocumentId", - "Published", - "Latest") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_TaxonomyIndex_DocumentId_Published", "DocumentId", "Published", "Latest")); return 5; } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Permissions.cs index 7cd8497a04f..ba7eaead84c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageTaxonomies = new("ManageTaxonomy", "Manage taxonomies"); - private readonly IEnumerable _allPermissions = - [ - ManageTaxonomies, - ]; + private readonly IEnumerable _allPermissions = [ManageTaxonomies,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Services/TaxonomyContentsAdminListFilter.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Services/TaxonomyContentsAdminListFilter.cs index d96284818ad..02b74d7a579 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Services/TaxonomyContentsAdminListFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Services/TaxonomyContentsAdminListFilter.cs @@ -38,16 +38,12 @@ public async Task FilterAsync(ContentOptionsViewModel model, IQuery if (viewModel.SelectedContentItemId.StartsWith("Taxonomy:", StringComparison.OrdinalIgnoreCase)) { viewModel.SelectedContentItemId = viewModel.SelectedContentItemId[9..]; - query.All( - x => query.With(x => x.TaxonomyContentItemId == viewModel.SelectedContentItemId) - ); + query.All(x => query.With(x => x.TaxonomyContentItemId == viewModel.SelectedContentItemId)); } else if (viewModel.SelectedContentItemId.StartsWith("Term:", StringComparison.OrdinalIgnoreCase)) { viewModel.SelectedContentItemId = viewModel.SelectedContentItemId[5..]; - query.All( - x => query.With(x => x.TermContentItemId == viewModel.SelectedContentItemId) - ); + query.All(x => query.With(x => x.TermContentItemId == viewModel.SelectedContentItemId)); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyContentsAdminListSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyContentsAdminListSettingsDisplayDriver.cs index 34a69553ef9..b114999c941 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyContentsAdminListSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyContentsAdminListSettingsDisplayDriver.cs @@ -22,10 +22,7 @@ public class TaxonomyContentsAdminListSettingsDisplayDriver : SectionDisplayDriv private readonly IAuthorizationService _authorizationService; private readonly YesSql.ISession _session; - public TaxonomyContentsAdminListSettingsDisplayDriver( - IHttpContextAccessor httpContextAccessor, - IAuthorizationService authorizationService, - YesSql.ISession session) + public TaxonomyContentsAdminListSettingsDisplayDriver(IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService, YesSql.ISession session) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -42,17 +39,24 @@ public override async Task EditAsync(TaxonomyContentsAdminListSe var taxonomies = await _session.Query(q => q.ContentType == "Taxonomy" && q.Published).ListAsync(); - var entries = taxonomies.Select(x => new TaxonomyEntry - { - DisplayText = x.DisplayText, - ContentItemId = x.ContentItemId, - IsChecked = settings.TaxonomyContentItemIds.Any(id => string.Equals(x.ContentItemId, id, StringComparison.OrdinalIgnoreCase)) - }).ToArray(); + var entries = taxonomies + .Select(x => new TaxonomyEntry + { + DisplayText = x.DisplayText, + ContentItemId = x.ContentItemId, + IsChecked = settings.TaxonomyContentItemIds.Any(id => string.Equals(x.ContentItemId, id, StringComparison.OrdinalIgnoreCase)) + }) + .ToArray(); - return Initialize("TaxonomyContentsAdminListSettings_Edit", model => - { - model.TaxonomyEntries = entries; - }).Location("Content:2").OnGroup(GroupId); + return Initialize( + "TaxonomyContentsAdminListSettings_Edit", + model => + { + model.TaxonomyEntries = entries; + } + ) + .Location("Content:2") + .OnGroup(GroupId); } public override async Task UpdateAsync(TaxonomyContentsAdminListSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyFieldSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyFieldSettingsDriver.cs index e70cc65b180..61dc96e5a10 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyFieldSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyFieldSettingsDriver.cs @@ -11,17 +11,20 @@ public class TaxonomyFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriv { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("TaxonomyFieldSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "TaxonomyFieldSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Hint = settings.Hint; - model.Required = settings.Required; - model.TaxonomyContentItemId = settings.TaxonomyContentItemId; - model.Unique = settings.Unique; - model.LeavesOnly = settings.LeavesOnly; - model.Open = settings.Open; - }) + model.Hint = settings.Hint; + model.Required = settings.Required; + model.TaxonomyContentItemId = settings.TaxonomyContentItemId; + model.Unique = settings.Unique; + model.LeavesOnly = settings.LeavesOnly; + model.Open = settings.Open; + } + ) .Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyFieldTagsEditorSettingsDriver.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyFieldTagsEditorSettingsDriver.cs index b40c5972991..59fd7facee4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyFieldTagsEditorSettingsDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Settings/TaxonomyFieldTagsEditorSettingsDriver.cs @@ -11,12 +11,15 @@ public class TaxonomyFieldTagsEditorSettingsDriver : ContentPartFieldDefinitionD { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { - return Initialize("TaxonomyFieldTagsEditorSettings_Edit", model => - { - var settings = partFieldDefinition.Settings.ToObject(); + return Initialize( + "TaxonomyFieldTagsEditorSettings_Edit", + model => + { + var settings = partFieldDefinition.Settings.ToObject(); - model.Open = settings.Open; - }) + model.Open = settings.Open; + } + ) .Location("Content"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Startup.cs index 9add4f47987..e3fbb842866 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/Startup.cs @@ -1,3 +1,4 @@ +using System; using Fluid; using Microsoft.Extensions.DependencyInjection; using OrchardCore.Apis; @@ -28,7 +29,6 @@ using OrchardCore.Taxonomies.Services; using OrchardCore.Taxonomies.Settings; using OrchardCore.Taxonomies.ViewModels; -using System; namespace OrchardCore.Taxonomies { @@ -36,28 +36,28 @@ public class Startup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.Configure(o => - { - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - }) - .AddLiquidFilter("inherited_terms") - .AddLiquidFilter("taxonomy_terms"); + services + .Configure(o => + { + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); + }) + .AddLiquidFilter("inherited_terms") + .AddLiquidFilter("taxonomy_terms"); services.AddDataMigration(); services.AddScoped(); services.AddScoped(); // Taxonomy Part - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); // Taxonomy Field - services.AddContentField() + services + .AddContentField() .UseDisplayDriver(d => !string.Equals(d, "Tags", StringComparison.OrdinalIgnoreCase)) .AddHandler(); @@ -65,8 +65,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped(); // Taxonomy Tags Display Mode and Editor. - services.AddContentField() - .UseDisplayDriver(d => string.Equals(d, "Tags", StringComparison.OrdinalIgnoreCase)); + services.AddContentField().UseDisplayDriver(d => string.Equals(d, "Tags", StringComparison.OrdinalIgnoreCase)); services.AddScoped(); @@ -98,7 +97,10 @@ public class ContentsAdminListDeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddSiteSettingsPropertyDeploymentStep(S => S["Taxonomy Filters settings"], S => S["Exports the Taxonomy filters settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Taxonomy Filters settings"], + S => S["Exports the Taxonomy filters settings."] + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Taxonomies/TermShapes.cs b/src/OrchardCore.Modules/OrchardCore.Taxonomies/TermShapes.cs index bbd5edeaec5..4d95b28d62f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Taxonomies/TermShapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.Taxonomies/TermShapes.cs @@ -19,7 +19,8 @@ public class TermShapes : ShapeTableProvider public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { // Add standard alternates to a TermPart because it is rendered by a content display driver not a part display driver. - builder.Describe("TermPart") + builder + .Describe("TermPart") .OnDisplaying(context => { var viewModel = context.Shape as TermPartViewModel; @@ -37,7 +38,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("Term") + builder + .Describe("Term") .OnProcessing(async context => { var termShape = context.Shape; @@ -58,9 +60,10 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) var contentManager = context.ServiceProvider.GetRequiredService(); var handleManager = context.ServiceProvider.GetRequiredService(); - var taxonomyContentItemId = termShape.TryGetProperty("Alias", out object alias) && alias != null - ? await handleManager.GetContentItemIdAsync(alias.ToString()) - : termShape.Properties["TaxonomyContentItemId"].ToString(); + var taxonomyContentItemId = + termShape.TryGetProperty("Alias", out object alias) && alias != null + ? await handleManager.GetContentItemIdAsync(alias.ToString()) + : termShape.Properties["TaxonomyContentItemId"].ToString(); if (taxonomyContentItemId == null) { @@ -96,10 +99,7 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) return; } - termItems = - [ - termContentItem - ]; + termItems = [termContentItem]; } else { @@ -138,14 +138,19 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) childTerms = termsArray.ToObject(); } - var shape = await shapeFactory.CreateAsync("TermItem", Arguments.From(new - { - Level = level, - Term = termShape, - TermContentItem = termContentItem, - Terms = childTerms ?? [], - TaxonomyContentItem = taxonomyContentItem - })); + var shape = await shapeFactory.CreateAsync( + "TermItem", + Arguments.From( + new + { + Level = level, + Term = termShape, + TermContentItem = termContentItem, + Terms = childTerms ?? [], + TaxonomyContentItem = taxonomyContentItem + } + ) + ); shape.Metadata.Differentiator = differentiator; @@ -154,7 +159,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("TermItem") + builder + .Describe("TermItem") .OnDisplaying(async context => { var termItem = context.Shape; @@ -175,14 +181,19 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { childTerms = termsArray.ToObject(); } - var shape = await shapeFactory.CreateAsync("TermItem", Arguments.From(new - { - Level = level + 1, - TaxonomyContentItem = taxonomyContentItem, - TermContentItem = termContentItem, - Term = termShape, - Terms = childTerms ?? [] - })); + var shape = await shapeFactory.CreateAsync( + "TermItem", + Arguments.From( + new + { + Level = level + 1, + TaxonomyContentItem = taxonomyContentItem, + TermContentItem = termContentItem, + Term = termShape, + Terms = childTerms ?? [] + } + ) + ); shape.Metadata.Differentiator = differentiator; @@ -215,7 +226,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe("TermContentItem") + builder + .Describe("TermContentItem") .OnDisplaying(displaying => { var termItem = displaying.Shape; diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Templates/AdminMenu.cs index bcaef4ac4bb..1d2c6a0abac 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/AdminMenu.cs @@ -20,14 +20,15 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Design"], design => design - .Add(S["Templates"], S["Templates"].PrefixPosition(), import => import - .Action("Index", "Template", "OrchardCore.Templates") - .Permission(Permissions.ManageTemplates) - .LocalNav() + builder.Add( + S["Design"], + design => + design.Add( + S["Templates"], + S["Templates"].PrefixPosition(), + import => import.Action("Index", "Template", "OrchardCore.Templates").Permission(Permissions.ManageTemplates).LocalNav() ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/AdminTemplatesAdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Templates/AdminTemplatesAdminMenu.cs index a502dec5a8a..a983997d962 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/AdminTemplatesAdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/AdminTemplatesAdminMenu.cs @@ -20,14 +20,15 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Design"], design => design - .Add(S["Admin Templates"], S["Admin Templates"].PrefixPosition(), import => import - .Action("Admin", "Template", "OrchardCore.Templates") - .Permission(AdminTemplatesPermissions.ManageAdminTemplates) - .LocalNav() + builder.Add( + S["Design"], + design => + design.Add( + S["Admin Templates"], + S["Admin Templates"].PrefixPosition(), + import => import.Action("Admin", "Template", "OrchardCore.Templates").Permission(AdminTemplatesPermissions.ManageAdminTemplates).LocalNav() ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/AdminTemplatesPermissions.cs b/src/OrchardCore.Modules/OrchardCore.Templates/AdminTemplatesPermissions.cs index 4eb873a2e05..97996a92988 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/AdminTemplatesPermissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/AdminTemplatesPermissions.cs @@ -8,20 +8,9 @@ public class AdminTemplatesPermissions : IPermissionProvider { public static readonly Permission ManageAdminTemplates = new("ManageAdminTemplates", "Manage admin templates", isSecurityCritical: true); - private readonly IEnumerable _allPermissions = - [ - ManageAdminTemplates, - ]; + private readonly IEnumerable _allPermissions = [ManageAdminTemplates,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/PreviewController.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/PreviewController.cs index 6704c665dd4..b9fae1f56aa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/PreviewController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/PreviewController.cs @@ -29,7 +29,8 @@ public PreviewController( IAuthorizationService authorizationService, ISiteService siteService, IUpdateModelAccessor updateModelAccessor, - IHttpContextAccessor httpContextAccessor) + IHttpContextAccessor httpContextAccessor + ) { _contentManager = contentManager; _contentHandleManager = contentHandleManager; @@ -77,8 +78,7 @@ public async Task Render() { var index = handle.IndexOf(_homeUrl, StringComparison.Ordinal); - handle = (index < 0 ? handle : handle[_homeUrl.Length..]) - .ToUriComponents(UriFormat.SafeUnescaped); + handle = (index < 0 ? handle : handle[_homeUrl.Length..]).ToUriComponents(UriFormat.SafeUnescaped); contentItemId = await _contentHandleManager.GetContentItemIdAsync("slug:" + handle); } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/TemplateController.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/TemplateController.cs index 679c39b5e8f..720a33f0ff1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/TemplateController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/TemplateController.cs @@ -43,7 +43,8 @@ public TemplateController( IOptions pagerOptions, IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer, - INotifier notifier) + INotifier notifier + ) { _authorizationService = authorizationService; _templatesManager = templatesManager; @@ -77,10 +78,7 @@ public async Task Index(ContentOptions options, PagerParameters p } var pager = new Pager(pagerParameters, _pagerOptions.GetPageSize()); - var templatesDocument = options.AdminTemplates - ? await _adminTemplatesManager.GetTemplatesDocumentAsync() - : await _templatesManager.GetTemplatesDocumentAsync() - ; + var templatesDocument = options.AdminTemplates ? await _adminTemplatesManager.GetTemplatesDocumentAsync() : await _templatesManager.GetTemplatesDocumentAsync(); var templates = templatesDocument.Templates.ToList(); @@ -91,9 +89,7 @@ public async Task Index(ContentOptions options, PagerParameters p var count = templates.Count; - templates = templates.OrderBy(x => x.Key) - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize).ToList(); + templates = templates.OrderBy(x => x.Key).Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -111,10 +107,7 @@ public async Task Index(ContentOptions options, PagerParameters p Pager = pagerShape }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; // The 'Admin' action redirect the user to the 'Index' action. // To ensure we render the same 'Index' view in both cases, we have to explicitly specify the name of the view that should be rendered. @@ -123,11 +116,7 @@ public async Task Index(ContentOptions options, PagerParameters p [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(TemplateIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(TemplateIndexViewModel model) => RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Create(string name = null, bool adminTemplates = false, string returnUrl = null) { @@ -141,11 +130,7 @@ public async Task Create(string name = null, bool adminTemplates return Forbid(); } - var model = new TemplateViewModel - { - AdminTemplates = adminTemplates, - Name = name - }; + var model = new TemplateViewModel { AdminTemplates = adminTemplates, Name = name }; ViewData["ReturnUrl"] = returnUrl; return View(model); @@ -178,10 +163,7 @@ public async Task CreatePost(TemplateViewModel model, string subm } else { - var templatesDocument = model.AdminTemplates - ? await _adminTemplatesManager.GetTemplatesDocumentAsync() - : await _templatesManager.GetTemplatesDocumentAsync() - ; + var templatesDocument = model.AdminTemplates ? await _adminTemplatesManager.GetTemplatesDocumentAsync() : await _templatesManager.GetTemplatesDocumentAsync(); if (templatesDocument.Templates.ContainsKey(model.Name)) { @@ -194,16 +176,21 @@ public async Task CreatePost(TemplateViewModel model, string subm { var template = new Template { Content = model.Content, Description = model.Description }; - await (model.AdminTemplates - ? _adminTemplatesManager.UpdateTemplateAsync(model.Name, template) - : _templatesManager.UpdateTemplateAsync(model.Name, template) - ); + await (model.AdminTemplates ? _adminTemplatesManager.UpdateTemplateAsync(model.Name, template) : _templatesManager.UpdateTemplateAsync(model.Name, template)); await _notifier.SuccessAsync(H["The \"{0}\" template has been created.", model.Name]); if (submit == "SaveAndContinue") { - return RedirectToAction(nameof(Edit), new { name = model.Name, adminTemplates = model.AdminTemplates, returnUrl }); + return RedirectToAction( + nameof(Edit), + new + { + name = model.Name, + adminTemplates = model.AdminTemplates, + returnUrl + } + ); } else { @@ -227,10 +214,7 @@ public async Task Edit(string name, bool adminTemplates = false, return Forbid(); } - var templatesDocument = adminTemplates - ? await _adminTemplatesManager.GetTemplatesDocumentAsync() - : await _templatesManager.GetTemplatesDocumentAsync() - ; + var templatesDocument = adminTemplates ? await _adminTemplatesManager.GetTemplatesDocumentAsync() : await _templatesManager.GetTemplatesDocumentAsync(); if (!templatesDocument.Templates.TryGetValue(name, out var template)) { @@ -262,10 +246,7 @@ public async Task Edit(string sourceName, TemplateViewModel model return Forbid(); } - var templatesDocument = model.AdminTemplates - ? await _adminTemplatesManager.LoadTemplatesDocumentAsync() - : await _templatesManager.LoadTemplatesDocumentAsync() - ; + var templatesDocument = model.AdminTemplates ? await _adminTemplatesManager.LoadTemplatesDocumentAsync() : await _templatesManager.LoadTemplatesDocumentAsync(); if (ModelState.IsValid) { @@ -292,15 +273,9 @@ public async Task Edit(string sourceName, TemplateViewModel model { var template = new Template { Content = model.Content, Description = model.Description }; - await (model.AdminTemplates - ? _adminTemplatesManager.RemoveTemplateAsync(sourceName) - : _templatesManager.RemoveTemplateAsync(sourceName) - ); + await (model.AdminTemplates ? _adminTemplatesManager.RemoveTemplateAsync(sourceName) : _templatesManager.RemoveTemplateAsync(sourceName)); - await (model.AdminTemplates - ? _adminTemplatesManager.UpdateTemplateAsync(model.Name, template) - : _templatesManager.UpdateTemplateAsync(model.Name, template) - ); + await (model.AdminTemplates ? _adminTemplatesManager.UpdateTemplateAsync(model.Name, template) : _templatesManager.UpdateTemplateAsync(model.Name, template)); if (submit != "SaveAndContinue") { @@ -330,18 +305,14 @@ public async Task Delete(string name, string returnUrl, bool admi return Forbid(); } - var templatesDocument = adminTemplates - ? await _adminTemplatesManager.LoadTemplatesDocumentAsync() - : await _templatesManager.LoadTemplatesDocumentAsync(); + var templatesDocument = adminTemplates ? await _adminTemplatesManager.LoadTemplatesDocumentAsync() : await _templatesManager.LoadTemplatesDocumentAsync(); if (!templatesDocument.Templates.ContainsKey(name)) { return NotFound(); } - await (adminTemplates - ? _adminTemplatesManager.RemoveTemplateAsync(name) - : _templatesManager.RemoveTemplateAsync(name)); + await (adminTemplates ? _adminTemplatesManager.RemoveTemplateAsync(name) : _templatesManager.RemoveTemplateAsync(name)); await _notifier.SuccessAsync(H["Template deleted successfully."]); @@ -359,9 +330,7 @@ public async Task ListPost(ContentOptions options, IEnumerable 0) { - var templatesDocument = options.AdminTemplates - ? await _adminTemplatesManager.LoadTemplatesDocumentAsync() - : await _templatesManager.LoadTemplatesDocumentAsync(); + var templatesDocument = options.AdminTemplates ? await _adminTemplatesManager.LoadTemplatesDocumentAsync() : await _templatesManager.LoadTemplatesDocumentAsync(); var checkedContentItems = templatesDocument.Templates.Where(x => itemIds.Contains(x.Key)); switch (options.BulkAction) @@ -371,9 +340,7 @@ public async Task ListPost(ContentOptions options, IEnumerable("AllAdminTemplatesDeploymentStep_Fields_Edit", model => model.ExportAsFiles = step.ExportAsFiles).Location("Content"); + return Initialize("AllAdminTemplatesDeploymentStep_Fields_Edit", model => model.ExportAsFiles = step.ExportAsFiles) + .Location("Content"); } + public override async Task UpdateAsync(AllAdminTemplatesDeploymentStep step, IUpdateModel updater) { await updater.TryUpdateModelAsync(step, Prefix, x => x.ExportAsFiles); diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentSource.cs index 83d004cc175..c98d1ca4129 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentSource.cs @@ -46,11 +46,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan } } - result.Steps.Add(new JsonObject - { - ["name"] = "Templates", - ["Templates"] = templateObjects, - }); + result.Steps.Add(new JsonObject { ["name"] = "Templates", ["Templates"] = templateObjects, }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentStep.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentStep.cs index 089b1a3e210..23851744914 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentStep.cs @@ -11,6 +11,7 @@ public AllTemplatesDeploymentStep() { Name = "AllTemplates"; } + public bool ExportAsFiles { get; set; } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentStepDriver.cs index 9330c7668bb..5695871e218 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllTemplatesDeploymentStepDriver.cs @@ -11,17 +11,17 @@ public class AllTemplatesDeploymentStepDriver : DisplayDriver("AllTemplatesDeploymentStep_Fields_Edit", model => model.ExportAsFiles = step.ExportAsFiles).Location("Content"); } + public override async Task UpdateAsync(AllTemplatesDeploymentStep step, IUpdateModel updater) { await updater.TryUpdateModelAsync(step, Prefix, x => x.ExportAsFiles); diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Manifest.cs index 0885de6f1f9..99c875ce23b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Manifest.cs @@ -1,11 +1,6 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Templates", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Templates", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Templates", diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Models/AdminTemplatesDocument.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Models/AdminTemplatesDocument.cs index 62265e6fa9d..6ff42b6480b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Models/AdminTemplatesDocument.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Models/AdminTemplatesDocument.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Templates.Models { - public class AdminTemplatesDocument : TemplatesDocument - { - } + public class AdminTemplatesDocument : TemplatesDocument { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Permissions.cs index 753281617a6..e5dac9a163f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Permissions.cs @@ -8,25 +8,10 @@ public class Permissions : IPermissionProvider { public static readonly Permission ManageTemplates = new("ManageTemplates", "Manage templates", isSecurityCritical: true); - private readonly IEnumerable _allPermissions = - [ - ManageTemplates, - ]; + private readonly IEnumerable _allPermissions = [ManageTemplates,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _allPermissions, - }, - ]; + [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, }, new PermissionStereotype { Name = "Editor", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Services/AdminTemplatesShapeBindingResolver.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Services/AdminTemplatesShapeBindingResolver.cs index b04c6690c07..395fcb8e2b9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Services/AdminTemplatesShapeBindingResolver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Services/AdminTemplatesShapeBindingResolver.cs @@ -23,7 +23,8 @@ public AdminTemplatesShapeBindingResolver( ILiquidTemplateManager liquidTemplateManager, AdminPreviewTemplatesProvider previewTemplatesProvider, IHttpContextAccessor httpContextAccessor, - HtmlEncoder htmlEncoder) + HtmlEncoder htmlEncoder + ) { _templatesManager = templatesManager; _liquidTemplateManager = liquidTemplateManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Services/TemplatesShapeBindingResolver.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Services/TemplatesShapeBindingResolver.cs index d4788f2009f..0e74844a00b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Services/TemplatesShapeBindingResolver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Services/TemplatesShapeBindingResolver.cs @@ -23,7 +23,8 @@ public TemplatesShapeBindingResolver( ILiquidTemplateManager liquidTemplateManager, PreviewTemplatesProvider previewTemplatesProvider, IHttpContextAccessor httpContextAccessor, - HtmlEncoder htmlEncoder) + HtmlEncoder htmlEncoder + ) { _templatesManager = templatesManager; _liquidTemplateManager = liquidTemplateManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentPartDefinitionDriver.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentPartDefinitionDriver.cs index cc4cbc2e75b..6ff2bf4ca21 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentPartDefinitionDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentPartDefinitionDriver.cs @@ -18,22 +18,28 @@ public TemplateContentPartDefinitionDriver(IStringLocalizer("TemplateSettings", model => - { - model.ContentSettingsEntries.Add( - new ContentSettingsEntry + return Initialize( + "TemplateSettings", + model => { - Key = contentPartDefinition.Name, - Description = S["Template for a {0} part in detail views", contentPartDefinition.DisplayName()] - }); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + Key = contentPartDefinition.Name, + Description = S["Template for a {0} part in detail views", contentPartDefinition.DisplayName()] + } + ); - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - Key = $"{contentPartDefinition.Name}_Summary", - Description = S["Template for a {0} part in summary views", contentPartDefinition.DisplayName()] - }); - }).Location("Shortcuts"); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + Key = $"{contentPartDefinition.Name}_Summary", + Description = S["Template for a {0} part in summary views", contentPartDefinition.DisplayName()] + } + ); + } + ) + .Location("Shortcuts"); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentTypeDefinitionDriver.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentTypeDefinitionDriver.cs index dd3e2a51b28..77c09dbbf66 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentTypeDefinitionDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentTypeDefinitionDriver.cs @@ -17,27 +17,33 @@ public TemplateContentTypeDefinitionDriver(IStringLocalizer("TemplateSettings", model => - { - if (!contentTypeDefinition.TryGetStereotype(out var stereotype)) - { - stereotype = "Content"; - } - - model.ContentSettingsEntries.Add( - new ContentSettingsEntry + return Initialize( + "TemplateSettings", + model => { - Key = $"{stereotype}__{contentTypeDefinition.Name}", - Description = S["Template for a {0} content item in detail views", contentTypeDefinition.DisplayName] - }); + if (!contentTypeDefinition.TryGetStereotype(out var stereotype)) + { + stereotype = "Content"; + } - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - Key = $"{stereotype}_Summary__{contentTypeDefinition.Name}", - Description = S["Template for a {0} content item in summary views", contentTypeDefinition.DisplayName] - }); - }).Location("Shortcuts"); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + Key = $"{stereotype}__{contentTypeDefinition.Name}", + Description = S["Template for a {0} content item in detail views", contentTypeDefinition.DisplayName] + } + ); + + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + Key = $"{stereotype}_Summary__{contentTypeDefinition.Name}", + Description = S["Template for a {0} content item in summary views", contentTypeDefinition.DisplayName] + } + ); + } + ) + .Location("Shortcuts"); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentTypePartDefinitionDriver.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentTypePartDefinitionDriver.cs index ac1e84fa6cd..37fc32483bb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentTypePartDefinitionDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentTypePartDefinitionDriver.cs @@ -17,25 +17,31 @@ public TemplateContentTypePartDefinitionDriver(IStringLocalizer("TemplateSettings", model => - { - var contentType = contentTypePartDefinition.ContentTypeDefinition.Name; - var partName = contentTypePartDefinition.Name; - - model.ContentSettingsEntries.Add( - new ContentSettingsEntry + return Initialize( + "TemplateSettings", + model => { - Key = $"{contentType}__{partName}", - Description = S["Template for the {0} part in a {1} type in detail views", partName, contentTypePartDefinition.ContentTypeDefinition.DisplayName] - }); + var contentType = contentTypePartDefinition.ContentTypeDefinition.Name; + var partName = contentTypePartDefinition.Name; - model.ContentSettingsEntries.Add( - new ContentSettingsEntry - { - Key = $"{contentType}_Summary__{partName}", - Description = S["Template for the {0} part in a {1} type in summary views", partName, contentTypePartDefinition.ContentTypeDefinition.DisplayName] - }); - }).Location("Shortcuts"); + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + Key = $"{contentType}__{partName}", + Description = S["Template for the {0} part in a {1} type in detail views", partName, contentTypePartDefinition.ContentTypeDefinition.DisplayName] + } + ); + + model.ContentSettingsEntries.Add( + new ContentSettingsEntry + { + Key = $"{contentType}_Summary__{partName}", + Description = S["Template for the {0} part in a {1} type in summary views", partName, contentTypePartDefinition.ContentTypeDefinition.DisplayName] + } + ); + } + ) + .Location("Shortcuts"); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/AdminMenu.cs index 3f43ce9d27c..45da14de941 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/AdminMenu.cs @@ -29,16 +29,20 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Multi-Tenancy"], "after", tenancy => tenancy - .AddClass("menu-multitenancy") - .Id("multitenancy") - .Add(S["Tenants"], S["Tenants"].PrefixPosition(), tenant => tenant - .Action("Index", "Admin", "OrchardCore.Tenants") - .Permission(Permissions.ManageTenants) - .LocalNav() - ), - priority: 1); + builder.Add( + S["Multi-Tenancy"], + "after", + tenancy => + tenancy + .AddClass("menu-multitenancy") + .Id("multitenancy") + .Add( + S["Tenants"], + S["Tenants"].PrefixPosition(), + tenant => tenant.Action("Index", "Admin", "OrchardCore.Tenants").Permission(Permissions.ManageTenants).LocalNav() + ), + priority: 1 + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/AdminController.cs index 294d926dfda..8f4d75f7eca 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/AdminController.cs @@ -68,7 +68,8 @@ public AdminController( ILogger logger, IShapeFactory shapeFactory, IStringLocalizer stringLocalizer, - IHtmlLocalizer htmlLocalizer) + IHtmlLocalizer htmlLocalizer + ) { _shellHost = shellHost; _shellSettingsManager = shellSettingsManager; @@ -108,30 +109,40 @@ public async Task Index(TenantIndexOptions options, PagerParamete var pager = new Pager(pagerParameters, _pagerOptions.GetPageSize()); - var entries = allSettings.Select(settings => - { - var entry = new ShellSettingsEntry - { - Category = settings["Category"], - Description = settings["Description"], - Name = settings.Name, - ShellSettings = settings, - }; - - if (settings.IsUninitialized() && !string.IsNullOrEmpty(settings["Secret"])) - { - entry.Token = dataProtector.Protect(settings["Secret"], _clock.UtcNow.Add(new TimeSpan(24, 0, 0))); - } - - return entry; - }).ToList(); + var entries = allSettings + .Select(settings => + { + var entry = new ShellSettingsEntry + { + Category = settings["Category"], + Description = settings["Description"], + Name = settings.Name, + ShellSettings = settings, + }; + + if (settings.IsUninitialized() && !string.IsNullOrEmpty(settings["Secret"])) + { + entry.Token = dataProtector.Protect(settings["Secret"], _clock.UtcNow.Add(new TimeSpan(24, 0, 0))); + } + + return entry; + }) + .ToList(); if (!string.IsNullOrWhiteSpace(options.Search)) { - entries = entries.Where(t => t.Name.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1 || - (t.ShellSettings != null && - ((t.ShellSettings.RequestUrlHost != null && t.ShellSettings.RequestUrlHost.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1) || - (t.ShellSettings.RequestUrlPrefix != null && t.ShellSettings.RequestUrlPrefix.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1)))).ToList(); + entries = entries + .Where(t => + t.Name.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1 + || ( + t.ShellSettings != null + && ( + (t.ShellSettings.RequestUrlHost != null && t.ShellSettings.RequestUrlHost.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1) + || (t.ShellSettings.RequestUrlPrefix != null && t.ShellSettings.RequestUrlPrefix.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1) + ) + ) + ) + .ToList(); } if (!string.IsNullOrWhiteSpace(options.Category)) @@ -154,9 +165,7 @@ public async Task Index(TenantIndexOptions options, PagerParamete _ => entries.OrderByDescending(t => t.Name).ToList(), }; - var results = entries - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize).ToList(); + var results = entries.Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links var routeData = new RouteData(); @@ -189,10 +198,7 @@ public async Task Index(TenantIndexOptions options, PagerParamete .Select(group => new SelectListItem(group.Key, group.Key, string.Equals(options.Category, group.Key, StringComparison.OrdinalIgnoreCase))) .ToList(); - model.Options.TenantsCategories.Insert(0, new SelectListItem( - S["All"], - string.Empty, - selected: string.IsNullOrEmpty(options.Category))); + model.Options.TenantsCategories.Insert(0, new SelectListItem(S["All"], string.Empty, selected: string.IsNullOrEmpty(options.Category))); model.Options.TenantsStates = [ @@ -219,15 +225,18 @@ public async Task Index(TenantIndexOptions options, PagerParamete [HttpPost, ActionName("Index")] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(AdminIndexViewModel model) - => RedirectToAction("Index", new RouteValueDictionary - { - { "Options.Category", model.Options.Category }, - { "Options.Status", model.Options.Status }, - { "Options.OrderBy", model.Options.OrderBy }, - { "Options.Search", model.Options.Search }, - { "Options.TenantsStates", model.Options.TenantsStates } - }); + public ActionResult IndexFilterPOST(AdminIndexViewModel model) => + RedirectToAction( + "Index", + new RouteValueDictionary + { + { "Options.Category", model.Options.Category }, + { "Options.Status", model.Options.Status }, + { "Options.OrderBy", model.Options.OrderBy }, + { "Options.Search", model.Options.Search }, + { "Options.TenantsStates", model.Options.TenantsStates } + } + ); [HttpPost] [FormValueRequired("submit.BulkAction")] @@ -311,10 +320,7 @@ public async Task Create() var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).OrderBy(r => r.DisplayName).ToArray(); // Creates a default shell settings based on the configuration. - using var shellSettings = _shellSettingsManager - .CreateDefaultSettings() - .AsUninitialized() - .AsDisposable(); + using var shellSettings = _shellSettingsManager.CreateDefaultSettings().AsUninitialized().AsDisposable(); var currentFeatureProfiles = shellSettings.GetFeatureProfiles(); var featureProfiles = await GetFeatureProfilesAsync(currentFeatureProfiles); @@ -333,9 +339,7 @@ public async Task Create() Schema = shellSettings["Schema"], }; - model.DatabaseConfigurationPreset = - !string.IsNullOrEmpty(model.ConnectionString) || - !string.IsNullOrEmpty(model.DatabaseProvider); + model.DatabaseConfigurationPreset = !string.IsNullOrEmpty(model.ConnectionString) || !string.IsNullOrEmpty(model.DatabaseProvider); model.Recipes = recipes; @@ -363,10 +367,7 @@ public async Task Create(EditTenantViewModel model) if (ModelState.IsValid) { // Creates a default shell settings based on the configuration. - using var shellSettings = _shellSettingsManager - .CreateDefaultSettings() - .AsUninitialized() - .AsDisposable(); + using var shellSettings = _shellSettingsManager.CreateDefaultSettings().AsUninitialized().AsDisposable(); shellSettings.Name = model.Name; shellSettings.RequestUrlHost = model.RequestUrlHost; diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/ApiController.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/ApiController.cs index 50759932fb9..fd28ca50c69 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/ApiController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/ApiController.cs @@ -65,7 +65,8 @@ public ApiController( IEnumerable databaseProviders, ITenantValidator tenantValidator, IStringLocalizer stringLocalizer, - ILogger logger) + ILogger logger + ) { _shellHost = shellHost; _currentShellSettings = currentShellSettings; @@ -105,10 +106,7 @@ public async Task Create(TenantApiModel model) if (model.IsNewTenant) { // Creates a default shell settings based on the configuration. - using var shellSettings = _shellSettingsManager - .CreateDefaultSettings() - .AsUninitialized() - .AsDisposable(); + using var shellSettings = _shellSettingsManager.CreateDefaultSettings().AsUninitialized().AsDisposable(); shellSettings.Name = model.Name; shellSettings.RequestUrlHost = model.RequestUrlHost; @@ -282,7 +280,8 @@ public async Task Remove(string tenantName) return Problem( title: S["An error occurred while removing the tenant '{0}'.", tenantName], detail: context.ErrorMessage, - statusCode: (int)HttpStatusCode.BadRequest); + statusCode: (int)HttpStatusCode.BadRequest + ); } if (_logger.IsEnabled(LogLevel.Warning)) diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/FeatureProfilesController.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/FeatureProfilesController.cs index 7b50c1b44a7..0f6ea95aa9a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/FeatureProfilesController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Controllers/FeatureProfilesController.cs @@ -46,7 +46,7 @@ public FeatureProfilesController( IShapeFactory shapeFactory, IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer - ) + ) { _authorizationService = authorizationService; _featureProfilesManager = featureProfilesManager; @@ -77,9 +77,7 @@ public async Task Index(ContentOptions options, PagerParameters p var count = featureProfiles.Count; - featureProfiles = featureProfiles.OrderBy(x => x.Key) - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize).ToList(); + featureProfiles = featureProfiles.OrderBy(x => x.Key).Skip(pager.GetStartIndex()).Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links. var routeData = new RouteData(); @@ -93,31 +91,27 @@ public async Task Index(ContentOptions options, PagerParameters p var model = new FeatureProfilesIndexViewModel { - FeatureProfiles = featureProfiles.Select(x => new FeatureProfileEntry - { - Name = x.Value.Name ?? x.Key, - FeatureProfile = x.Value, - Id = x.Key - }).ToList(), + FeatureProfiles = featureProfiles + .Select(x => new FeatureProfileEntry + { + Name = x.Value.Name ?? x.Key, + FeatureProfile = x.Value, + Id = x.Key + }) + .ToList(), Options = options, Pager = pagerShape }; - model.Options.ContentsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), - ]; + model.Options.ContentsBulkAction = [new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)),]; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(FeatureProfilesIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { _optionsSearch, model.Options.Search } - }); + public ActionResult IndexFilterPOST(FeatureProfilesIndexViewModel model) => + RedirectToAction(nameof(Index), new RouteValueDictionary { { _optionsSearch, model.Options.Search } }); public async Task Create() { @@ -126,10 +120,7 @@ public async Task Create() return Forbid(); } - var viewModel = new FeatureProfileViewModel() - { - Id = IdGenerator.GenerateId(), - }; + var viewModel = new FeatureProfileViewModel() { Id = IdGenerator.GenerateId(), }; return View(viewModel); } @@ -137,10 +128,15 @@ public async Task Create() [HttpPost, ActionName(nameof(Create))] public async Task CreatePost(FeatureProfileViewModel model, string submit) { - return await ProcessSaveAsync(model, submit, true, async (profile) => - { - await _featureProfilesManager.UpdateFeatureProfileAsync(profile.Id, profile); - }); + return await ProcessSaveAsync( + model, + submit, + true, + async (profile) => + { + await _featureProfilesManager.UpdateFeatureProfileAsync(profile.Id, profile); + } + ); } public async Task Edit(string id) @@ -172,12 +168,17 @@ public async Task Edit(string id) [HttpPost, ActionName(nameof(Edit))] public async Task EditPost(FeatureProfileViewModel model, string submit) { - return await ProcessSaveAsync(model, submit, false, async (profile) => - { - await _featureProfilesManager.RemoveFeatureProfileAsync(profile.Id); + return await ProcessSaveAsync( + model, + submit, + false, + async (profile) => + { + await _featureProfilesManager.RemoveFeatureProfileAsync(profile.Id); - await _featureProfilesManager.UpdateFeatureProfileAsync(profile.Id, profile); - }); + await _featureProfilesManager.UpdateFeatureProfileAsync(profile.Id, profile); + } + ); } [HttpPost] diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Deployment/AllFeatureProfilesDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Deployment/AllFeatureProfilesDeploymentSource.cs index b415fb40f8e..a786f6e13c9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Deployment/AllFeatureProfilesDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Deployment/AllFeatureProfilesDeploymentSource.cs @@ -29,11 +29,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan featureProfileObjects[featureProfile.Key] = JObject.FromObject(featureProfile.Value); } - result.Steps.Add(new JsonObject - { - ["name"] = "FeatureProfiles", - ["FeatureProfiles"] = featureProfileObjects, - }); + result.Steps.Add(new JsonObject { ["name"] = "FeatureProfiles", ["FeatureProfiles"] = featureProfileObjects, }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Deployment/AllFeatureProfilesDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Deployment/AllFeatureProfilesDeploymentStepDriver.cs index 46f30f3cdf4..37c92909d50 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Deployment/AllFeatureProfilesDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Deployment/AllFeatureProfilesDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class AllFeatureProfilesDeploymentStepDriver : DisplayDriver tenancy - .AddClass("menu-multitenancy") - .Add(S["Feature Profiles"], S["Feature Profiles"].PrefixPosition(), featureProfiles => featureProfiles - .Action("Index", "FeatureProfiles", "OrchardCore.Tenants") - .Permission(Permissions.ManageTenantFeatureProfiles) - .LocalNav() - ) - ); + builder.Add( + S["Multi-Tenancy"], + tenancy => + tenancy + .AddClass("menu-multitenancy") + .Add( + S["Feature Profiles"], + S["Feature Profiles"].PrefixPosition(), + featureProfiles => + featureProfiles.Action("Index", "FeatureProfiles", "OrchardCore.Tenants").Permission(Permissions.ManageTenantFeatureProfiles).LocalNav() + ) + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/HttpContextExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/HttpContextExtensions.cs index b2bfc9dd1b4..23da3e322bf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/HttpContextExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/HttpContextExtensions.cs @@ -4,6 +4,7 @@ using OrchardCore.Tenants.ViewModels; namespace OrchardCore.Tenants; + public static class HttpContextExtensions { public static string GetEncodedUrl(this HttpContext httpContext, ShellSettingsEntry entry, bool appendQuery = true) diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Manifest.cs index c2094cbd2fb..942c98d29bd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Manifest.cs @@ -1,11 +1,6 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Tenants", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Tenants", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Tenants", diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Models/TenantApiModel.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Models/TenantApiModel.cs index b4face4a6c6..c0ddb6ff33d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Models/TenantApiModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Models/TenantApiModel.cs @@ -1,5 +1,3 @@ namespace OrchardCore.Tenants.Models; -public class TenantApiModel : TenantModelBase -{ -} +public class TenantApiModel : TenantModelBase { } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Permissions.cs index 97330139bd4..1c7291cad3e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Permissions.cs @@ -9,21 +9,9 @@ public class Permissions : IPermissionProvider public static readonly Permission ManageTenants = new("ManageTenants", "Manage tenants"); public static readonly Permission ManageTenantFeatureProfiles = new("ManageTenantFeatureProfiles", "Manage tenant feature profiles"); - private readonly IEnumerable _allPermissions = - [ - ManageTenants, - ManageTenantFeatureProfiles, - ]; + private readonly IEnumerable _allPermissions = [ManageTenants, ManageTenantFeatureProfiles,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/FeatureProfilesSchemaService.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/FeatureProfilesSchemaService.cs index 4cde1640875..572caea5af1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/FeatureProfilesSchemaService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/FeatureProfilesSchemaService.cs @@ -13,9 +13,7 @@ public class FeatureProfilesSchemaService : IFeatureProfilesSchemaService private readonly FeatureProfilesRuleOptions _featureProfilesRuleOptions; private readonly IHostEnvironment _hostEnvironment; - public FeatureProfilesSchemaService( - IOptions options, - IHostEnvironment hostEnvironment) + public FeatureProfilesSchemaService(IOptions options, IHostEnvironment hostEnvironment) { _hostEnvironment = hostEnvironment; _featureProfilesRuleOptions = options.Value; @@ -31,11 +29,7 @@ public string GetJsonSchema() if (schema.Definitions.TryGetValue(nameof(FeatureRule), out var featureRule) && featureRule.ActualProperties.TryGetValue(nameof(FeatureRule.Rule), out var rule)) { - var ruleProperty = new JsonSchema() - { - Type = JsonObjectType.String, - Description = "The rule to apply to this expression" - }; + var ruleProperty = new JsonSchema() { Type = JsonObjectType.String, Description = "The rule to apply to this expression" }; foreach (var ruleOption in _featureProfilesRuleOptions.Rules.Keys) { diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/ITenantFileProvider.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/ITenantFileProvider.cs index 1fe3d6931b0..d2111133605 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/ITenantFileProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/ITenantFileProvider.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Tenants.Services { - public interface ITenantFileProvider : IStaticFileProvider - { - } + public interface ITenantFileProvider : IStaticFileProvider { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFeatureProfileShapeTableProvider.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFeatureProfileShapeTableProvider.cs index 26a8bec69ee..3b162d67c37 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFeatureProfileShapeTableProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFeatureProfileShapeTableProvider.cs @@ -12,14 +12,15 @@ public class TenantFeatureProfileShapeTableProvider : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("TenantActionTags") - .OnDisplaying(async displaying => - { - if (displaying.Shape.TryGetProperty("ShellSettingsEntry", out ShellSettingsEntry entry)) - { - await displaying.Shape.AddAsync(new ShapeViewModel("ProfileFeatureTags", entry), "10"); - } - }); + builder + .Describe("TenantActionTags") + .OnDisplaying(async displaying => + { + if (displaying.Shape.TryGetProperty("ShellSettingsEntry", out ShellSettingsEntry entry)) + { + await displaying.Shape.AddAsync(new ShapeViewModel("ProfileFeatureTags", entry), "10"); + } + }); return ValueTask.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFeatureShapeTableProvider.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFeatureShapeTableProvider.cs index 36c02f92603..9806150913a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFeatureShapeTableProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFeatureShapeTableProvider.cs @@ -12,14 +12,15 @@ public class TenantFeatureShapeTableProvider : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("TenantActionButtons") - .OnDisplaying(async displaying => - { - if (displaying.Shape.TryGetProperty("ShellSettingsEntry", out ShellSettingsEntry entry)) - { - await displaying.Shape.AddAsync(new ShapeViewModel("ManageFeaturesActionButton", entry), "10"); - } - }); + builder + .Describe("TenantActionButtons") + .OnDisplaying(async displaying => + { + if (displaying.Shape.TryGetProperty("ShellSettingsEntry", out ShellSettingsEntry entry)) + { + await displaying.Shape.AddAsync(new ShapeViewModel("ManageFeaturesActionButton", entry), "10"); + } + }); return ValueTask.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFileProvider.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFileProvider.cs index 0b03b45b415..b68ad9d2882 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFileProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantFileProvider.cs @@ -5,12 +5,10 @@ namespace OrchardCore.Tenants.Services { public class TenantFileProvider : PhysicalFileProvider, ITenantFileProvider { - public TenantFileProvider(string root) : base(root) - { - } + public TenantFileProvider(string root) + : base(root) { } - public TenantFileProvider(string root, ExclusionFilters filters) : base(root, filters) - { - } + public TenantFileProvider(string root, ExclusionFilters filters) + : base(root, filters) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantShapeTableProvider.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantShapeTableProvider.cs index 164c83e3cb7..67ec3a8e814 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantShapeTableProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantShapeTableProvider.cs @@ -10,16 +10,18 @@ public class TenantShapeTableProvider : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("TenantActionTags") + builder + .Describe("TenantActionTags") .OnDisplaying(async displaying => - { - if (displaying.Shape.TryGetProperty("ShellSettingsEntry", out ShellSettingsEntry entry)) - { - await displaying.Shape.AddAsync(new ShapeViewModel("ManageTenantActionTags", entry), "5"); - } - }); + { + if (displaying.Shape.TryGetProperty("ShellSettingsEntry", out ShellSettingsEntry entry)) + { + await displaying.Shape.AddAsync(new ShapeViewModel("ManageTenantActionTags", entry), "5"); + } + }); - builder.Describe("TenantActionButtons") + builder + .Describe("TenantActionButtons") .OnDisplaying(async displaying => { if (displaying.Shape.TryGetProperty("ShellSettingsEntry", out ShellSettingsEntry entry)) diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantValidator.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantValidator.cs index d1c7082f94a..5612481102f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantValidator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Services/TenantValidator.cs @@ -25,7 +25,8 @@ public TenantValidator( IShellSettingsManager shellSettingsManager, IFeatureProfilesService featureProfilesService, IDbConnectionValidator dbConnectionValidator, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _shellHost = shellHost; _shellSettingsManager = shellSettingsManager; @@ -68,10 +69,11 @@ public async Task> ValidateAsync(TenantModelBase model) errors.Add(new ModelError(nameof(model.RequestUrlPrefix), S["The url prefix can not contain more than one segment."])); } - if (_shellHost.GetAllSettings().Any(settings => - settings != existingShellSettings && - settings.HasUrlPrefix(model.RequestUrlPrefix) && - settings.HasUrlHost(model.RequestUrlHost))) + if ( + _shellHost + .GetAllSettings() + .Any(settings => settings != existingShellSettings && settings.HasUrlPrefix(model.RequestUrlPrefix) && settings.HasUrlHost(model.RequestUrlHost)) + ) { errors.Add(new ModelError(nameof(model.RequestUrlPrefix), S["A tenant with the same host and prefix already exists."])); } @@ -82,10 +84,7 @@ public async Task> ValidateAsync(TenantModelBase model) if (existingShellSettings is null) { // Set the settings to be validated. - shellSettings = _shellSettingsManager - .CreateDefaultSettings() - .AsUninitialized() - .AsDisposable(); + shellSettings = _shellSettingsManager.CreateDefaultSettings().AsUninitialized().AsDisposable(); shellSettings.Name = model.Name; } @@ -125,35 +124,33 @@ private async Task ValidateConnectionAsync(DbConnectionValidatorContext validati switch (await _dbConnectionValidator.ValidateAsync(validationContext)) { case DbConnectionValidatorResult.UnsupportedProvider: - errors.Add(new ModelError(nameof( - TenantViewModel.DatabaseProvider), - S["The provided database provider is not supported."])); + errors.Add(new ModelError(nameof(TenantViewModel.DatabaseProvider), S["The provided database provider is not supported."])); break; case DbConnectionValidatorResult.InvalidConnection: - errors.Add(new ModelError( - nameof(TenantViewModel.ConnectionString), - S["The provided connection string is invalid or server is unreachable."])); + errors.Add(new ModelError(nameof(TenantViewModel.ConnectionString), S["The provided connection string is invalid or server is unreachable."])); break; case DbConnectionValidatorResult.InvalidCertificate: - errors.Add(new ModelError( - nameof(TenantViewModel.ConnectionString), - S["The security certificate on the server is from a non-trusted source (the certificate issuing authority isn't listed as a trusted authority in Trusted Root Certification Authorities on the client machine). In a development environment, you have the option to use the '{0}' parameter in your connection string to bypass the validation performed by the certificate authority.", "TrustServerCertificate=True"])); + errors.Add( + new ModelError( + nameof(TenantViewModel.ConnectionString), + S[ + "The security certificate on the server is from a non-trusted source (the certificate issuing authority isn't listed as a trusted authority in Trusted Root Certification Authorities on the client machine). In a development environment, you have the option to use the '{0}' parameter in your connection string to bypass the validation performed by the certificate authority.", + "TrustServerCertificate=True" + ] + ) + ); break; case DbConnectionValidatorResult.DocumentTableFound: if (validationContext.DatabaseProvider == DatabaseProviderValue.Sqlite) { - errors.Add(new ModelError( - string.Empty, - S["The related database file is already in use."])); + errors.Add(new ModelError(string.Empty, S["The related database file is already in use."])); break; } - errors.Add(new ModelError( - nameof(TenantViewModel.TablePrefix), - S["The provided database, table prefix and schema are already in use."])); + errors.Add(new ModelError(nameof(TenantViewModel.TablePrefix), S["The provided database, table prefix and schema are already in use."])); break; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/ShellSettingsExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/ShellSettingsExtensions.cs index 09029dc9723..f8a3c0b1530 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/ShellSettingsExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/ShellSettingsExtensions.cs @@ -7,7 +7,6 @@ public static class ShellSettingsExtensions { public static string[] GetFeatureProfiles(this ShellSettings shellSettings) { - return shellSettings["FeatureProfile"]?.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) - ?? []; + return shellSettings["FeatureProfile"]?.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) ?? []; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Startup.cs index 470987bca65..10ea5101d89 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Startup.cs @@ -1,3 +1,5 @@ +using System; +using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; @@ -17,8 +19,6 @@ using OrchardCore.Tenants.Deployment; using OrchardCore.Tenants.Recipes; using OrchardCore.Tenants.Services; -using System; -using System.IO; namespace OrchardCore.Tenants { @@ -80,18 +80,21 @@ public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder ro { var tenantFileProvider = serviceProvider.GetRequiredService(); - app.UseStaticFiles(new StaticFileOptions - { - FileProvider = tenantFileProvider, - DefaultContentType = "application/octet-stream", - ServeUnknownFileTypes = true, - - // Cache the tenant static files for 30 days. - OnPrepareResponse = ctx => + app.UseStaticFiles( + new StaticFileOptions { - ctx.Context.Response.Headers[HeaderNames.CacheControl] = $"public, max-age={TimeSpan.FromDays(30).TotalSeconds}, s-max-age={TimeSpan.FromDays(365.25).TotalSeconds}"; + FileProvider = tenantFileProvider, + DefaultContentType = "application/octet-stream", + ServeUnknownFileTypes = true, + + // Cache the tenant static files for 30 days. + OnPrepareResponse = ctx => + { + ctx.Context.Response.Headers[HeaderNames.CacheControl] = + $"public, max-age={TimeSpan.FromDays(30).TotalSeconds}, s-max-age={TimeSpan.FromDays(365.25).TotalSeconds}"; + } } - }); + ); } private static string GetContentRoot(ShellOptions shellOptions, ShellSettings shellSettings) => diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/ViewModels/CreateApiViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/ViewModels/CreateApiViewModel.cs index 8602c8c44b1..1af11548b98 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/ViewModels/CreateApiViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/ViewModels/CreateApiViewModel.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Tenants.ViewModels { - public class CreateApiViewModel : TenantViewModel - { - } + public class CreateApiViewModel : TenantViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/ViewModels/TenantViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/ViewModels/TenantViewModel.cs index 979d4723b96..a425fd84bc8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/ViewModels/TenantViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/ViewModels/TenantViewModel.cs @@ -2,8 +2,5 @@ namespace OrchardCore.Tenants.ViewModels { - public class TenantViewModel : TenantModelBase - { - - } + public class TenantViewModel : TenantModelBase { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/CreateTenantTask.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/CreateTenantTask.cs index 6e158d335eb..872e0932fee 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/CreateTenantTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/CreateTenantTask.cs @@ -18,10 +18,9 @@ public CreateTenantTask( IShellHost shellHost, IWorkflowExpressionEvaluator expressionEvaluator, IWorkflowScriptEvaluator scriptEvaluator, - IStringLocalizer localizer) - : base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer) - { - } + IStringLocalizer localizer + ) + : base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer) { } public override string Name => nameof(CreateTenantTask); @@ -88,7 +87,7 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex return Outcomes(S["Done"], S["Failed"]); } - public async override Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) + public override async Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { if (!ShellScope.Context.Settings.IsDefaultShell()) { @@ -118,10 +117,7 @@ public async override Task ExecuteAsync(WorkflowExecuti var featureProfile = (await ExpressionEvaluator.EvaluateAsync(FeatureProfile, workflowContext, null))?.Trim(); // Creates a default shell settings based on the configuration. - using var shellSettings = ShellSettingsManager - .CreateDefaultSettings() - .AsUninitialized() - .AsDisposable(); + using var shellSettings = ShellSettingsManager.CreateDefaultSettings().AsUninitialized().AsDisposable(); shellSettings.Name = tenantName; diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/DisableTenantTask.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/DisableTenantTask.cs index 8c53e002ae7..e4e39f6b2db 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/DisableTenantTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/DisableTenantTask.cs @@ -12,10 +12,15 @@ namespace OrchardCore.Tenants.Workflows.Activities { public class DisableTenantTask : TenantTask { - public DisableTenantTask(IShellSettingsManager shellSettingsManager, IShellHost shellHost, IWorkflowExpressionEvaluator expressionEvaluator, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) - : base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer) - { - } + public DisableTenantTask( + IShellSettingsManager shellSettingsManager, + IShellHost shellHost, + IWorkflowExpressionEvaluator expressionEvaluator, + IWorkflowScriptEvaluator scriptEvaluator, + IStringLocalizer localizer + ) + : base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer) { } + public override string Name => nameof(DisableTenantTask); public override LocalizedString Category => S["Tenant"]; diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/EnableTenantTask.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/EnableTenantTask.cs index 0b671b689d9..a451880e84f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/EnableTenantTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/EnableTenantTask.cs @@ -12,10 +12,14 @@ namespace OrchardCore.Tenants.Workflows.Activities { public class EnableTenantTask : TenantTask { - public EnableTenantTask(IShellSettingsManager shellSettingsManager, IShellHost shellHost, IWorkflowExpressionEvaluator expressionEvaluator, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) - : base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer) - { - } + public EnableTenantTask( + IShellSettingsManager shellSettingsManager, + IShellHost shellHost, + IWorkflowExpressionEvaluator expressionEvaluator, + IWorkflowScriptEvaluator scriptEvaluator, + IStringLocalizer localizer + ) + : base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer) { } public override string Name => nameof(EnableTenantTask); diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/SetupTenantTask.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/SetupTenantTask.cs index 2856346634b..2a0fbeebb49 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/SetupTenantTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/SetupTenantTask.cs @@ -35,7 +35,8 @@ public SetupTenantTask( ISetupService setupService, IWorkflowExpressionEvaluator expressionEvaluator, IWorkflowScriptEvaluator scriptEvaluator, - IStringLocalizer localizer) + IStringLocalizer localizer + ) : base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer) { SetupService = setupService; diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/TenantActivity.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/TenantActivity.cs index 7612f6a3384..c05a2a646aa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/TenantActivity.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/TenantActivity.cs @@ -12,7 +12,13 @@ public abstract class TenantActivity : Activity { protected readonly IStringLocalizer S; - protected TenantActivity(IShellSettingsManager shellSettingsManager, IShellHost shellHost, IWorkflowExpressionEvaluator expressionEvaluator, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + protected TenantActivity( + IShellSettingsManager shellSettingsManager, + IShellHost shellHost, + IWorkflowExpressionEvaluator expressionEvaluator, + IWorkflowScriptEvaluator scriptEvaluator, + IStringLocalizer localizer + ) { ShellSettingsManager = shellSettingsManager; ShellHost = shellHost; diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/TenantTask.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/TenantTask.cs index 17d323d5445..e59cda672c5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/TenantTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/TenantTask.cs @@ -7,9 +7,13 @@ namespace OrchardCore.Tenants.Workflows.Activities { public abstract class TenantTask : TenantActivity, ITask { - protected TenantTask(IShellSettingsManager shellSettingsManager, IShellHost shellHost, IWorkflowExpressionEvaluator expressionEvaluator, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) - : base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer) - { - } + protected TenantTask( + IShellSettingsManager shellSettingsManager, + IShellHost shellHost, + IWorkflowExpressionEvaluator expressionEvaluator, + IWorkflowScriptEvaluator scriptEvaluator, + IStringLocalizer localizer + ) + : base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Drivers/TenantTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Drivers/TenantTaskDisplayDriver.cs index 1006d398191..9abfeb4f6fd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Drivers/TenantTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Drivers/TenantTaskDisplayDriver.cs @@ -6,7 +6,8 @@ namespace OrchardCore.Tenants.Workflows.Drivers { public abstract class TenantTaskDisplayDriver : ActivityDisplayDriver - where TActivity : TenantTask where TViewModel : TenantTaskViewModel, new() + where TActivity : TenantTask + where TViewModel : TenantTaskViewModel, new() { public string TenantName { get; set; } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/DisableTenantTaskViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/DisableTenantTaskViewModel.cs index 5b12376671b..c91fc4473a3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/DisableTenantTaskViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/DisableTenantTaskViewModel.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Tenants.Workflows.ViewModels { - public class DisableTenantTaskViewModel : TenantTaskViewModel - { - } + public class DisableTenantTaskViewModel : TenantTaskViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/EnableTenantTaskViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/EnableTenantTaskViewModel.cs index 03653726412..a4d2e6a7321 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/EnableTenantTaskViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/EnableTenantTaskViewModel.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Tenants.Workflows.ViewModels { - public class EnableTenantTaskViewModel : TenantTaskViewModel - { - } + public class EnableTenantTaskViewModel : TenantTaskViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/TenantTaskViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/TenantTaskViewModel.cs index 5739ab95050..a52ebd705f2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/TenantTaskViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/ViewModels/TenantTaskViewModel.cs @@ -3,13 +3,12 @@ namespace OrchardCore.Tenants.Workflows.ViewModels { - public class TenantTaskViewModel : ActivityViewModel where T : TenantTask + public class TenantTaskViewModel : ActivityViewModel + where T : TenantTask { public string TenantNameExpression { get; set; } - public TenantTaskViewModel() - { - } + public TenantTaskViewModel() { } public TenantTaskViewModel(T activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Themes/AdminMenu.cs index eae2d8f1754..d9ed0226de0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/AdminMenu.cs @@ -20,15 +20,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Design"], NavigationConstants.AdminMenuDesignPosition, design => design - .AddClass("themes").Id("themes") - .Add(S["Themes"], S["Themes"].PrefixPosition(), themes => themes - .Action("Index", "Admin", "OrchardCore.Themes") - .Permission(Permissions.ApplyTheme) - .LocalNav() - ) - ); + builder.Add( + S["Design"], + NavigationConstants.AdminMenuDesignPosition, + design => + design + .AddClass("themes") + .Id("themes") + .Add( + S["Themes"], + S["Themes"].PrefixPosition(), + themes => themes.Action("Index", "Admin", "OrchardCore.Themes").Permission(Permissions.ApplyTheme).LocalNav() + ) + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Themes/Controllers/AdminController.cs index 1862947547f..b84298a7727 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/Controllers/AdminController.cs @@ -32,7 +32,8 @@ public AdminController( IHtmlLocalizer localizer, IShellFeaturesManager shellFeaturesManager, IAuthorizationService authorizationService, - INotifier notifier) + INotifier notifier + ) { _siteThemeService = siteThemeService; _adminThemeService = adminThemeService; @@ -118,8 +119,9 @@ public async Task SetCurrentTheme(string id) } else { - var feature = (await _shellFeaturesManager.GetAvailableFeaturesAsync()) - .FirstOrDefault(f => f.Id == id && !f.IsAlwaysEnabled && !f.EnabledByDependencyOnly && f.IsTheme()); + var feature = (await _shellFeaturesManager.GetAvailableFeaturesAsync()).FirstOrDefault(f => + f.Id == id && !f.IsAlwaysEnabled && !f.EnabledByDependencyOnly && f.IsTheme() + ); if (feature == null) { @@ -193,8 +195,9 @@ public async Task Disable(string id) return Forbid(); } - var feature = (await _shellFeaturesManager.GetAvailableFeaturesAsync()) - .FirstOrDefault(f => f.Id == id && !f.IsAlwaysEnabled && !f.EnabledByDependencyOnly && f.IsTheme()); + var feature = (await _shellFeaturesManager.GetAvailableFeaturesAsync()).FirstOrDefault(f => + f.Id == id && !f.IsAlwaysEnabled && !f.EnabledByDependencyOnly && f.IsTheme() + ); if (feature == null) { @@ -216,8 +219,9 @@ public async Task Enable(string id) return Forbid(); } - var feature = (await _shellFeaturesManager.GetAvailableFeaturesAsync()) - .FirstOrDefault(f => f.Id == id && !f.IsAlwaysEnabled && !f.EnabledByDependencyOnly && f.IsTheme()); + var feature = (await _shellFeaturesManager.GetAvailableFeaturesAsync()).FirstOrDefault(f => + f.Id == id && !f.IsAlwaysEnabled && !f.EnabledByDependencyOnly && f.IsTheme() + ); if (feature == null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/Deployment/ThemesDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Themes/Deployment/ThemesDeploymentSource.cs index 7a4ffc13d64..84321189f3d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/Deployment/ThemesDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/Deployment/ThemesDeploymentSource.cs @@ -27,12 +27,14 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan return; } - result.Steps.Add(new JsonObject - { - ["name"] = "Themes", - [nameof(ThemeStepModel.Site)] = await _siteThemeService.GetSiteThemeNameAsync(), - [nameof(ThemeStepModel.Admin)] = await _adminThemeService.GetAdminThemeNameAsync(), - }); + result.Steps.Add( + new JsonObject + { + ["name"] = "Themes", + [nameof(ThemeStepModel.Site)] = await _siteThemeService.GetSiteThemeNameAsync(), + [nameof(ThemeStepModel.Admin)] = await _adminThemeService.GetAdminThemeNameAsync(), + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/Deployment/ThemesDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Themes/Deployment/ThemesDeploymentStepDriver.cs index 9a6bb5fc134..0233f185e67 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/Deployment/ThemesDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/Deployment/ThemesDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class ThemesDeploymentStepDriver : DisplayDriver /// The theme's name. /// - public string Name { get { return Extension.Manifest.Name; } } + public string Name + { + get { return Extension.Manifest.Name; } + } /// /// Boolean value indicating whether this is an admin theme. diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Themes/Permissions.cs index fddc1b32fad..5943a550859 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ApplyTheme = new("ApplyTheme", "Apply a Theme"); - private readonly IEnumerable _allPermissions = - [ - ApplyTheme, - ]; + private readonly IEnumerable _allPermissions = [ApplyTheme,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/Recipes/ThemesStep.cs b/src/OrchardCore.Modules/OrchardCore.Themes/Recipes/ThemesStep.cs index 0b258a10dd9..6673b2c736a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/Recipes/ThemesStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/Recipes/ThemesStep.cs @@ -16,9 +16,7 @@ public class ThemesStep : IRecipeStepHandler private readonly ISiteThemeService _siteThemeService; private readonly IAdminThemeService _adminThemeService; - public ThemesStep( - ISiteThemeService siteThemeService, - IAdminThemeService adminThemeService) + public ThemesStep(ISiteThemeService siteThemeService, IAdminThemeService adminThemeService) { _adminThemeService = adminThemeService; _siteThemeService = siteThemeService; diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/Services/DarkModeService.cs b/src/OrchardCore.Modules/OrchardCore.Themes/Services/DarkModeService.cs index 67e9a05438b..34148bd9930 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/Services/DarkModeService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/Services/DarkModeService.cs @@ -14,10 +14,7 @@ public class DarkModeService private readonly IHttpContextAccessor _httpContextAccessor; private readonly ISiteService _siteService; - public DarkModeService( - IHttpContextAccessor httpContextAccessor, - ISiteService siteService, - ShellSettings shellSettings) + public DarkModeService(IHttpContextAccessor httpContextAccessor, ISiteService siteService, ShellSettings shellSettings) { _httpContextAccessor = httpContextAccessor; _siteService = siteService; diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/Services/SiteThemeSelector.cs b/src/OrchardCore.Modules/OrchardCore.Themes/Services/SiteThemeSelector.cs index 4a6a6eb86c0..4ea46e3a66d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/Services/SiteThemeSelector.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/Services/SiteThemeSelector.cs @@ -25,11 +25,7 @@ public async Task GetThemeAsync() return null; } - return new ThemeSelectorResult - { - Priority = 0, - ThemeName = currentThemeName - }; + return new ThemeSelectorResult { Priority = 0, ThemeName = currentThemeName }; } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/Services/SiteThemeService.cs b/src/OrchardCore.Modules/OrchardCore.Themes/Services/SiteThemeService.cs index 483a81d9ee2..0a82e812c2f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/Services/SiteThemeService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/Services/SiteThemeService.cs @@ -9,9 +9,7 @@ public class SiteThemeService : ISiteThemeService private readonly ISiteService _siteService; private readonly IExtensionManager _extensionManager; - public SiteThemeService( - ISiteService siteService, - IExtensionManager extensionManager) + public SiteThemeService(ISiteService siteService, IExtensionManager extensionManager) { _siteService = siteService; _extensionManager = extensionManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/Services/ThemeService.cs b/src/OrchardCore.Modules/OrchardCore.Themes/Services/ThemeService.cs index 72a59eab844..3211116d495 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/Services/ThemeService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/Services/ThemeService.cs @@ -23,7 +23,8 @@ public ThemeService( IShellFeaturesManager shellFeaturesManager, ISiteThemeService siteThemeService, IHtmlLocalizer htmlLocalizer, - INotifier notifier) + INotifier notifier + ) { _extensionManager = extensionManager; _shellFeaturesManager = shellFeaturesManager; @@ -45,9 +46,7 @@ public async Task DisableThemeFeaturesAsync(string themeName) break; themes.Enqueue(themeName); - themeName = !string.IsNullOrWhiteSpace(theme.Manifest.Name) - ? theme.Manifest.Name - : null; + themeName = !string.IsNullOrWhiteSpace(theme.Manifest.Name) ? theme.Manifest.Name : null; } var currentTheme = await _siteThemeService.GetSiteThemeNameAsync(); @@ -104,9 +103,7 @@ public Task EnableFeaturesAsync(IEnumerable featureIds) /// Boolean parameter indicating if the feature should enable it's dependencies if required or fail otherwise. public async Task EnableFeaturesAsync(IEnumerable featureIds, bool force) { - var featuresToEnable = _extensionManager - .GetFeatures() - .Where(x => featureIds.Contains(x.Id)); + var featuresToEnable = _extensionManager.GetFeatures().Where(x => featureIds.Contains(x.Id)); var enabledFeatures = await _shellFeaturesManager.EnableFeaturesAsync(featuresToEnable, force); foreach (var enabledFeature in enabledFeatures) @@ -131,9 +128,7 @@ public Task DisableFeaturesAsync(IEnumerable featureIds) /// Boolean parameter indicating if the feature should disable the features which depend on it if required or fail otherwise. public async Task DisableFeaturesAsync(IEnumerable featureIds, bool force) { - var featuresToDisable = _extensionManager - .GetFeatures() - .Where(x => featureIds.Contains(x.Id)); + var featuresToDisable = _extensionManager.GetFeatures().Where(x => featureIds.Contains(x.Id)); var features = await _shellFeaturesManager.DisableFeaturesAsync(featuresToDisable, force); foreach (var feature in features) diff --git a/src/OrchardCore.Modules/OrchardCore.Themes/Services/ThemeTogglerService.cs b/src/OrchardCore.Modules/OrchardCore.Themes/Services/ThemeTogglerService.cs index a134f22e182..a9c0cf57c7c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Themes/Services/ThemeTogglerService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Themes/Services/ThemeTogglerService.cs @@ -11,10 +11,7 @@ public class ThemeTogglerService private readonly IHttpContextAccessor _httpContextAccessor; private readonly ISiteService _siteService; - public ThemeTogglerService( - IHttpContextAccessor httpContextAccessor, - ISiteService siteService, - ShellSettings shellSettings) + public ThemeTogglerService(IHttpContextAccessor httpContextAccessor, ISiteService siteService, ShellSettings shellSettings) { _httpContextAccessor = httpContextAccessor; _siteService = siteService; @@ -31,8 +28,7 @@ public async Task CurrentTheme() { var cookieName = $"{CurrentTenant}-admintheme"; - if (_httpContextAccessor.HttpContext.Request.Cookies.TryGetValue(cookieName, out var value) - && !string.IsNullOrWhiteSpace(value)) + if (_httpContextAccessor.HttpContext.Request.Cookies.TryGetValue(cookieName, out var value) && !string.IsNullOrWhiteSpace(value)) { return value; } diff --git a/src/OrchardCore.Modules/OrchardCore.Title/Drivers/TitlePartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Title/Drivers/TitlePartDisplayDriver.cs index 9087cfac5c4..cedaf6af2e8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Title/Drivers/TitlePartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Title/Drivers/TitlePartDisplayDriver.cs @@ -28,25 +28,31 @@ public override IDisplayResult Display(TitlePart titlePart, BuildPartDisplayCont return null; } - return Initialize(GetDisplayShapeType(context), model => - { - model.Title = titlePart.ContentItem.DisplayText; - model.TitlePart = titlePart; - model.ContentItem = titlePart.ContentItem; - }) - .Location("Detail", "Header") - .Location("Summary", "Header"); + return Initialize( + GetDisplayShapeType(context), + model => + { + model.Title = titlePart.ContentItem.DisplayText; + model.TitlePart = titlePart; + model.ContentItem = titlePart.ContentItem; + } + ) + .Location("Detail", "Header") + .Location("Summary", "Header"); } public override IDisplayResult Edit(TitlePart titlePart, BuildPartEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.Title = titlePart.ContentItem.DisplayText; - model.TitlePart = titlePart; - model.ContentItem = titlePart.ContentItem; - model.Settings = context.TypePartDefinition.GetSettings(); - }); + return Initialize( + GetEditorShapeType(context), + model => + { + model.Title = titlePart.ContentItem.DisplayText; + model.TitlePart = titlePart; + model.ContentItem = titlePart.ContentItem; + model.Settings = context.TypePartDefinition.GetSettings(); + } + ); } public override async Task UpdateAsync(TitlePart model, IUpdateModel updater, UpdatePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Title/Handlers/TitlePartHandler.cs b/src/OrchardCore.Modules/OrchardCore.Title/Handlers/TitlePartHandler.cs index 992cafaf223..3334fd434c6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Title/Handlers/TitlePartHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Title/Handlers/TitlePartHandler.cs @@ -23,7 +23,8 @@ public class TitlePartHandler : ContentPartHandler public TitlePartHandler( ILiquidTemplateManager liquidTemplateManager, IContentDefinitionManager contentDefinitionManager, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _liquidTemplateManager = liquidTemplateManager; _contentDefinitionManager = contentDefinitionManager; @@ -85,11 +86,12 @@ private async Task SetTitleAsync(TitlePart part) ContentItem = part.ContentItem, }; - var title = await _liquidTemplateManager.RenderStringAsync(settings.Pattern, NullEncoder.Default, model, - new Dictionary() - { - ["ContentItem"] = new ObjectValue(model.ContentItem) - }); + var title = await _liquidTemplateManager.RenderStringAsync( + settings.Pattern, + NullEncoder.Default, + model, + new Dictionary() { ["ContentItem"] = new ObjectValue(model.ContentItem) } + ); title = title.Replace("\r", string.Empty).Replace("\n", string.Empty); diff --git a/src/OrchardCore.Modules/OrchardCore.Title/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Title/Migrations.cs index f9a92b3581f..b5937e9d7f5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Title/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Title/Migrations.cs @@ -18,10 +18,7 @@ public class Migrations : DataMigration private readonly ISession _session; private readonly ILogger _logger; - public Migrations( - IContentDefinitionManager contentDefinitionManager, - ISession session, - ILogger logger) + public Migrations(IContentDefinitionManager contentDefinitionManager, ISession session, ILogger logger) { _contentDefinitionManager = contentDefinitionManager; _session = session; @@ -30,11 +27,10 @@ public Migrations( public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("TitlePart", builder => builder - .Attachable() - .WithDescription("Provides a Title for your content item.") - .WithDefaultPosition("0") - ); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "TitlePart", + builder => builder.Attachable().WithDescription("Provides a Title for your content item.").WithDefaultPosition("0") + ); // Shortcut other migration steps on new content definition schemas. return 2; @@ -60,8 +56,7 @@ public async Task UpdateFrom1() foreach (var contentItemVersion in contentItemVersions) { - if (string.IsNullOrEmpty(contentItemVersion.DisplayText) - && UpdateTitle((JsonObject)contentItemVersion.Content)) + if (string.IsNullOrEmpty(contentItemVersion.DisplayText) && UpdateTitle((JsonObject)contentItemVersion.Content)) { await _session.SaveAsync(contentItemVersion); _logger.LogInformation("A content item version's Title was upgraded: {ContentItemVersionId}", contentItemVersion.ContentItemVersionId); @@ -94,7 +89,6 @@ static bool UpdateTitle(JsonNode content) } else if (content.GetValueKind() == JsonValueKind.Array) { - foreach (var node in content.AsArray()) { changed = UpdateTitle(node) || changed; diff --git a/src/OrchardCore.Modules/OrchardCore.Title/Settings/TitlePartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Title/Settings/TitlePartSettingsDisplayDriver.cs index 5b2b19684c1..bd03f624504 100644 --- a/src/OrchardCore.Modules/OrchardCore.Title/Settings/TitlePartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Title/Settings/TitlePartSettingsDisplayDriver.cs @@ -23,25 +23,26 @@ public TitlePartSettingsDisplayDriver(ILiquidTemplateManager templateManager, IS public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("TitlePartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + "TitlePartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); - model.Options = settings.Options; - model.Pattern = settings.Pattern; - model.RenderTitle = settings.RenderTitle; - model.TitlePartSettings = settings; - }).Location("Content"); + model.Options = settings.Options; + model.Pattern = settings.Pattern; + model.RenderTitle = settings.RenderTitle; + model.TitlePartSettings = settings; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) { var model = new TitlePartSettingsViewModel(); - await context.Updater.TryUpdateModelAsync(model, Prefix, - m => m.Pattern, - m => m.Options, - m => m.RenderTitle); + await context.Updater.TryUpdateModelAsync(model, Prefix, m => m.Pattern, m => m.Options, m => m.RenderTitle); if (!string.IsNullOrEmpty(model.Pattern) && !_templateManager.Validate(model.Pattern, out var errors)) { @@ -49,7 +50,14 @@ await context.Updater.TryUpdateModelAsync(model, Prefix, } else { - context.Builder.WithSettings(new TitlePartSettings { Pattern = model.Pattern, Options = model.Options, RenderTitle = model.RenderTitle }); + context.Builder.WithSettings( + new TitlePartSettings + { + Pattern = model.Pattern, + Options = model.Options, + RenderTitle = model.RenderTitle + } + ); } return Edit(contentTypePartDefinition, context.Updater); diff --git a/src/OrchardCore.Modules/OrchardCore.Title/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Title/Startup.cs index e1143648573..e7a15f4e989 100644 --- a/src/OrchardCore.Modules/OrchardCore.Title/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Title/Startup.cs @@ -26,9 +26,7 @@ public override void ConfigureServices(IServiceCollection services) }); // Title Part - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddScoped(); diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/AdminMenuSignin.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/AdminMenuSignin.cs index abc62fd55fe..7b8637c4c4e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/AdminMenuSignin.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/AdminMenuSignin.cs @@ -9,11 +9,7 @@ namespace OrchardCore.Twitter [Feature(TwitterConstants.Features.Signin)] public class AdminMenuSignin : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", TwitterConstants.Features.Signin }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", TwitterConstants.Features.Signin }, }; protected readonly IStringLocalizer S; @@ -29,17 +25,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Authentication"], authentication => authentication - .Add(S["Sign in with Twitter"], S["Sign in with Twitter"].PrefixPosition(), twitter => twitter - .AddClass("twitter") - .Id("twitter") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageTwitterSignin) - .LocalNav()) + builder.Add( + S["Security"], + security => + security.Add( + S["Authentication"], + authentication => + authentication.Add( + S["Sign in with Twitter"], + S["Sign in with Twitter"].PrefixPosition(), + twitter => twitter.AddClass("twitter").Id("twitter").Action("Index", "Admin", _routeValues).Permission(Permissions.ManageTwitterSignin).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } @@ -48,11 +46,7 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) [Feature(TwitterConstants.Features.Twitter)] public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", TwitterConstants.Features.Twitter }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", TwitterConstants.Features.Twitter }, }; protected readonly IStringLocalizer S; @@ -68,17 +62,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Configuration"], configuration => configuration - .Add(S["Settings"], settings => settings - .Add(S["Twitter"], S["Twitter"].PrefixPosition(), twitter => twitter - .AddClass("twitter").Id("twitter") - .Action("Index", "Admin", _routeValues) - .Permission(Permissions.ManageTwitter) - .LocalNav() - ) + builder.Add( + S["Configuration"], + configuration => + configuration.Add( + S["Settings"], + settings => + settings.Add( + S["Twitter"], + S["Twitter"].PrefixPosition(), + twitter => twitter.AddClass("twitter").Id("twitter").Action("Index", "Admin", _routeValues).Permission(Permissions.ManageTwitter).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Drivers/TwitterSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Drivers/TwitterSettingsDisplayDriver.cs index 833805ebd4e..7da65ce4c3f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Drivers/TwitterSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Drivers/TwitterSettingsDisplayDriver.cs @@ -29,7 +29,8 @@ public TwitterSettingsDisplayDriver( IHttpContextAccessor httpContextAccessor, IShellHost shellHost, ShellSettings shellSettings, - ILogger logger) + ILogger logger + ) { _authorizationService = authorizationService; _dataProtectionProvider = dataProtectionProvider; @@ -48,47 +49,52 @@ public override async Task EditAsync(TwitterSettings settings, B return null; } - return Initialize("TwitterSettings_Edit", model => - { - model.APIKey = settings.ConsumerKey; - if (!string.IsNullOrWhiteSpace(settings.ConsumerSecret)) - { - try - { - var protector = _dataProtectionProvider.CreateProtector(TwitterConstants.Features.Twitter); - model.APISecretKey = protector.Unprotect(settings.ConsumerSecret); - } - catch (CryptographicException) + return Initialize( + "TwitterSettings_Edit", + model => { - _logger.LogError("The API secret key could not be decrypted. It may have been encrypted using a different key."); - model.APISecretKey = string.Empty; - model.HasDecryptionError = true; + model.APIKey = settings.ConsumerKey; + if (!string.IsNullOrWhiteSpace(settings.ConsumerSecret)) + { + try + { + var protector = _dataProtectionProvider.CreateProtector(TwitterConstants.Features.Twitter); + model.APISecretKey = protector.Unprotect(settings.ConsumerSecret); + } + catch (CryptographicException) + { + _logger.LogError("The API secret key could not be decrypted. It may have been encrypted using a different key."); + model.APISecretKey = string.Empty; + model.HasDecryptionError = true; + } + } + else + { + model.APISecretKey = string.Empty; + } + model.AccessToken = settings.AccessToken; + if (!string.IsNullOrWhiteSpace(settings.AccessTokenSecret)) + { + try + { + var protector = _dataProtectionProvider.CreateProtector(TwitterConstants.Features.Twitter); + model.AccessTokenSecret = protector.Unprotect(settings.AccessTokenSecret); + } + catch (CryptographicException) + { + _logger.LogError("The access token secret could not be decrypted. It may have been encrypted using a different key."); + model.AccessTokenSecret = string.Empty; + model.HasDecryptionError = true; + } + } + else + { + model.AccessTokenSecret = string.Empty; + } } - } - else - { - model.APISecretKey = string.Empty; - } - model.AccessToken = settings.AccessToken; - if (!string.IsNullOrWhiteSpace(settings.AccessTokenSecret)) - { - try - { - var protector = _dataProtectionProvider.CreateProtector(TwitterConstants.Features.Twitter); - model.AccessTokenSecret = protector.Unprotect(settings.AccessTokenSecret); - } - catch (CryptographicException) - { - _logger.LogError("The access token secret could not be decrypted. It may have been encrypted using a different key."); - model.AccessTokenSecret = string.Empty; - model.HasDecryptionError = true; - } - } - else - { - model.AccessTokenSecret = string.Empty; - } - }).Location("Content:5").OnGroup(TwitterConstants.Features.Twitter); + ) + .Location("Content:5") + .OnGroup(TwitterConstants.Features.Twitter); } public override async Task UpdateAsync(TwitterSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Extensions/OrchardCoreBuilderExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Extensions/OrchardCoreBuilderExtensions.cs index 65dc6025dec..3c75524002c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Extensions/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Extensions/OrchardCoreBuilderExtensions.cs @@ -8,12 +8,14 @@ public static class OrchardCoreBuilderExtensions { public static OrchardCoreBuilder ConfigureTwitterSettings(this OrchardCoreBuilder builder) { - builder.ConfigureServices((tenantServices, serviceProvider) => - { - var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Twitter"); + builder.ConfigureServices( + (tenantServices, serviceProvider) => + { + var configurationSection = serviceProvider.GetRequiredService().GetSection("OrchardCore_Twitter"); - tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); - }); + tenantServices.PostConfigure(settings => configurationSection.Bind(settings)); + } + ); return builder; } diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Permissions.cs index 2235a81af65..df551045308 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Permissions.cs @@ -10,21 +10,9 @@ public class Permissions : IPermissionProvider public static readonly Permission ManageTwitterSignin = new("ManageTwitterSignin", "Manage Sign in with Twitter settings"); - private readonly IEnumerable _allPermissions = - [ - ManageTwitter, - ManageTwitterSignin, - ]; + private readonly IEnumerable _allPermissions = [ManageTwitter, ManageTwitterSignin,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterClient.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterClient.cs index be84bc5fad1..ad503207d55 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterClient.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterClient.cs @@ -25,10 +25,7 @@ public async Task UpdateStatus(string status, params string { try { - var parameters = new Dictionary - { - { "status", status } - }; + var parameters = new Dictionary { { "status", status } }; if (optionalParameters is not null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterClientMessageHandler.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterClientMessageHandler.cs index ff7af14ca8f..8db2097fc0a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterClientMessageHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterClientMessageHandler.cs @@ -20,10 +20,7 @@ public class TwitterClientMessageHandler : DelegatingHandler private readonly IDataProtectionProvider _dataProtectionProvider; private readonly IClock _clock; - public TwitterClientMessageHandler( - IClock clock, - IOptions twitterSettings, - IDataProtectionProvider dataProtectionProvider) + public TwitterClientMessageHandler(IClock clock, IOptions twitterSettings, IDataProtectionProvider dataProtectionProvider) { _twitterSettings = twitterSettings.Value; _dataProtectionProvider = dataProtectionProvider; @@ -94,9 +91,13 @@ public async Task ConfigureOAuthAsync(HttpRequestMessage request) } } - var baseString = string.Concat(request.Method.Method.ToUpperInvariant(), "&", - Uri.EscapeDataString(request.RequestUri.AbsoluteUri.ToString()), "&", - Uri.EscapeDataString(string.Join("&", sortedParameters.Select(c => string.Format("{0}={1}", c.Key, c.Value))))); + var baseString = string.Concat( + request.Method.Method.ToUpperInvariant(), + "&", + Uri.EscapeDataString(request.RequestUri.AbsoluteUri.ToString()), + "&", + Uri.EscapeDataString(string.Join("&", sortedParameters.Select(c => string.Format("{0}={1}", c.Key, c.Value)))) + ); var secret = string.Concat(_twitterSettings.ConsumerSecret, "&", _twitterSettings.AccessTokenSecret); diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterSettingsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterSettingsConfiguration.cs index 14433f8c3d7..8afacd7b0bb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterSettingsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterSettingsConfiguration.cs @@ -14,10 +14,7 @@ public class TwitterSettingsConfiguration : IConfigureOptions private readonly ShellSettings _shellSettings; private readonly ILogger _logger; - public TwitterSettingsConfiguration( - ITwitterSettingsService twitterSettingsService, - ShellSettings shellSettings, - ILogger logger) + public TwitterSettingsConfiguration(ITwitterSettingsService twitterSettingsService, ShellSettings shellSettings, ILogger logger) { _twitterSettingsService = twitterSettingsService; _shellSettings = shellSettings; @@ -26,9 +23,7 @@ public TwitterSettingsConfiguration( public void Configure(TwitterSettings options) { - var settings = GetTwitterSettingsAsync() - .GetAwaiter() - .GetResult(); + var settings = GetTwitterSettingsAsync().GetAwaiter().GetResult(); if (settings != null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterSettingsService.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterSettingsService.cs index bbbeb3920fc..9b7fd5c3214 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterSettingsService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Services/TwitterSettingsService.cs @@ -14,9 +14,7 @@ public class TwitterSettingsService : ITwitterSettingsService private readonly ISiteService _siteService; protected readonly IStringLocalizer S; - public TwitterSettingsService( - ISiteService siteService, - IStringLocalizer stringLocalizer) + public TwitterSettingsService(ISiteService siteService, IStringLocalizer stringLocalizer) { _siteService = siteService; S = stringLocalizer; @@ -39,13 +37,16 @@ public async Task UpdateSettingsAsync(TwitterSettings settings) ArgumentNullException.ThrowIfNull(settings); var container = await _siteService.LoadSiteSettingsAsync(); - container.Alter(nameof(TwitterSettings), aspect => - { - aspect.ConsumerKey = settings.ConsumerKey; - aspect.ConsumerSecret = settings.ConsumerSecret; - aspect.AccessToken = settings.AccessToken; - aspect.AccessTokenSecret = settings.AccessTokenSecret; - }); + container.Alter( + nameof(TwitterSettings), + aspect => + { + aspect.ConsumerKey = settings.ConsumerKey; + aspect.ConsumerSecret = settings.ConsumerSecret; + aspect.AccessToken = settings.AccessToken; + aspect.AccessTokenSecret = settings.AccessTokenSecret; + } + ); await _siteService.UpdateSiteSettingsAsync(container); } diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Configuration/TwitterOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Configuration/TwitterOptionsConfiguration.cs index 5035132fa3f..b39875fe9e5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Configuration/TwitterOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Configuration/TwitterOptionsConfiguration.cs @@ -17,9 +17,7 @@ namespace OrchardCore.Twitter.Signin.Configuration { - public class TwitterOptionsConfiguration : - IConfigureOptions, - IConfigureNamedOptions + public class TwitterOptionsConfiguration : IConfigureOptions, IConfigureNamedOptions { private readonly ITwitterSettingsService _twitterService; private readonly ITwitterSigninService _twitterSigninService; @@ -34,7 +32,8 @@ public TwitterOptionsConfiguration( IDataProtectionProvider dataProtectionProvider, IHttpContextAccessor httpContextAccessor, ShellSettings shellSettings, - ILogger logger) + ILogger logger + ) { _twitterService = twitterService; _twitterSigninService = twitterSigninService; @@ -59,19 +58,21 @@ public void Configure(AuthenticationOptions options) return; } - if (string.IsNullOrWhiteSpace(settings.Item1.ConsumerKey) || - string.IsNullOrWhiteSpace(settings.Item1.ConsumerSecret)) + if (string.IsNullOrWhiteSpace(settings.Item1.ConsumerKey) || string.IsNullOrWhiteSpace(settings.Item1.ConsumerSecret)) { _logger.LogWarning("The Twitter login provider is enabled but not configured."); return; } - options.AddScheme(TwitterDefaults.AuthenticationScheme, builder => - { - builder.DisplayName = "Twitter"; - builder.HandlerType = typeof(TwitterHandler); - }); + options.AddScheme( + TwitterDefaults.AuthenticationScheme, + builder => + { + builder.DisplayName = "Twitter"; + builder.HandlerType = typeof(TwitterHandler); + } + ); } public void Configure(string name, TwitterOptions options) diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Drivers/TwitterSigninSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Drivers/TwitterSigninSettingsDisplayDriver.cs index 29966c14a00..6fbad1fab4f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Drivers/TwitterSigninSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Drivers/TwitterSigninSettingsDisplayDriver.cs @@ -22,7 +22,8 @@ public TwitterSigninSettingsDisplayDriver( IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor, IShellHost shellHost, - ShellSettings shellSettings) + ShellSettings shellSettings + ) { _authorizationService = authorizationService; _httpContextAccessor = httpContextAccessor; @@ -38,14 +39,19 @@ public override async Task EditAsync(TwitterSigninSettings setti return null; } - return Initialize("TwitterSigninSettings_Edit", model => - { - if (settings.CallbackPath.HasValue) - { - model.CallbackPath = settings.CallbackPath; - } - model.SaveTokens = settings.SaveTokens; - }).Location("Content:5").OnGroup(TwitterConstants.Features.Signin); + return Initialize( + "TwitterSigninSettings_Edit", + model => + { + if (settings.CallbackPath.HasValue) + { + model.CallbackPath = settings.CallbackPath; + } + model.SaveTokens = settings.SaveTokens; + } + ) + .Location("Content:5") + .OnGroup(TwitterConstants.Features.Signin); } public override async Task UpdateAsync(TwitterSigninSettings settings, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Services/TwitterSigninService.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Services/TwitterSigninService.cs index 11182f78f51..087288582f3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Services/TwitterSigninService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Signin/Services/TwitterSigninService.cs @@ -10,8 +10,7 @@ public class TwitterSigninService : ITwitterSigninService { private readonly ISiteService _siteService; - public TwitterSigninService( - ISiteService siteService) + public TwitterSigninService(ISiteService siteService) { _siteService = siteService; } @@ -33,10 +32,13 @@ public async Task UpdateSettingsAsync(TwitterSigninSettings settings) ArgumentNullException.ThrowIfNull(settings); var container = await _siteService.LoadSiteSettingsAsync(); - container.Alter(nameof(TwitterSigninSettings), aspect => - { - aspect.CallbackPath = settings.CallbackPath; - }); + container.Alter( + nameof(TwitterSigninSettings), + aspect => + { + aspect.CallbackPath = settings.CallbackPath; + } + ); await _siteService.UpdateSiteSettingsAsync(container); } diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Startup.cs index fbf9b8990a7..731b9c09375 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Startup.cs @@ -47,26 +47,29 @@ public override void ConfigureServices(IServiceCollection services) services.AddTransient(); services.AddTransient, TwitterSettingsConfiguration>(); - services.AddHttpClient() + services + .AddHttpClient() .AddHttpMessageHandler() - .AddResilienceHandler("oc-handler", builder => builder - .AddRetry(new HttpRetryStrategyOptions - { - Name = "oc-retry", - MaxRetryAttempts = 3, - OnRetry = attempt => - { - attempt.RetryDelay.Add(TimeSpan.FromSeconds(0.5 * attempt.AttemptNumber)); + .AddResilienceHandler( + "oc-handler", + builder => + builder.AddRetry( + new HttpRetryStrategyOptions + { + Name = "oc-retry", + MaxRetryAttempts = 3, + OnRetry = attempt => + { + attempt.RetryDelay.Add(TimeSpan.FromSeconds(0.5 * attempt.AttemptNumber)); - return ValueTask.CompletedTask; - } - }) + return ValueTask.CompletedTask; + } + } + ) ); } - public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) - { - } + public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { } } [Feature(TwitterConstants.Features.Signin)] @@ -78,14 +81,16 @@ public override void ConfigureServices(IServiceCollection services) services.AddSingleton(); services.AddScoped, TwitterSigninSettingsDisplayDriver>(); // Register the options initializers required by the Twitter Handler. - services.TryAddEnumerable(new[] - { - // Orchard-specific initializers: - ServiceDescriptor.Transient, TwitterOptionsConfiguration>(), - ServiceDescriptor.Transient, TwitterOptionsConfiguration>(), - // Built-in initializers: - ServiceDescriptor.Transient, TwitterPostConfigureOptions>() - }); + services.TryAddEnumerable( + new[] + { + // Orchard-specific initializers: + ServiceDescriptor.Transient, TwitterOptionsConfiguration>(), + ServiceDescriptor.Transient, TwitterOptionsConfiguration>(), + // Built-in initializers: + ServiceDescriptor.Transient, TwitterPostConfigureOptions>() + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Twitter/Workflows/Activities/UpdateTwitterStatusTask.cs b/src/OrchardCore.Modules/OrchardCore.Twitter/Workflows/Activities/UpdateTwitterStatusTask.cs index 82cb93b2294..75596fbbeec 100644 --- a/src/OrchardCore.Modules/OrchardCore.Twitter/Workflows/Activities/UpdateTwitterStatusTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Twitter/Workflows/Activities/UpdateTwitterStatusTask.cs @@ -15,11 +15,7 @@ public class UpdateTwitterStatusTask : TaskActivity private readonly IWorkflowExpressionEvaluator _expressionEvaluator; protected readonly IStringLocalizer S; - public UpdateTwitterStatusTask( - TwitterClient twitterClient, - IWorkflowExpressionEvaluator expressionEvaluator, - IStringLocalizer localizer - ) + public UpdateTwitterStatusTask(TwitterClient twitterClient, IWorkflowExpressionEvaluator expressionEvaluator, IStringLocalizer localizer) { _twitterClient = twitterClient; _expressionEvaluator = expressionEvaluator; diff --git a/src/OrchardCore.Modules/OrchardCore.Users/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Users/AdminMenu.cs index 0737ea30d32..56061534123 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/AdminMenu.cs @@ -10,11 +10,7 @@ namespace OrchardCore.Users { public class AdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", LoginSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", LoginSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -30,26 +26,35 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], NavigationConstants.AdminMenuSecurityPosition, security => security - .AddClass("security") - .Id("security") - .Add(S["Users"], S["Users"].PrefixPosition(), users => users - .AddClass("users") - .Id("users") - .Action("Index", "Admin", "OrchardCore.Users") - .Permission(CommonPermissions.ListUsers) - .Resource(new User()) - .LocalNav() - ) - .Add(S["Settings"], settings => settings - .Add(S["User Login"], S["User Login"].PrefixPosition(), login => login - .Permission(CommonPermissions.ManageUsers) - .Action("Index", "Admin", _routeValues) - .LocalNav() + builder.Add( + S["Security"], + NavigationConstants.AdminMenuSecurityPosition, + security => + security + .AddClass("security") + .Id("security") + .Add( + S["Users"], + S["Users"].PrefixPosition(), + users => + users + .AddClass("users") + .Id("users") + .Action("Index", "Admin", "OrchardCore.Users") + .Permission(CommonPermissions.ListUsers) + .Resource(new User()) + .LocalNav() ) - ) - ); + .Add( + S["Settings"], + settings => + settings.Add( + S["User Login"], + S["User Login"].PrefixPosition(), + login => login.Permission(CommonPermissions.ManageUsers).Action("Index", "Admin", _routeValues).LocalNav() + ) + ) + ); return Task.CompletedTask; } @@ -58,11 +63,7 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) [Feature("OrchardCore.Users.ChangeEmail")] public class ChangeEmailAdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", ChangeEmailSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", ChangeEmailSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -78,16 +79,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Settings"], settings => settings - .Add(S["User Change email"], S["User Change email"].PrefixPosition(), email => email - .Permission(CommonPermissions.ManageUsers) - .Action("Index", "Admin", _routeValues) - .LocalNav() - ) + builder.Add( + S["Security"], + security => + security.Add( + S["Settings"], + settings => + settings.Add( + S["User Change email"], + S["User Change email"].PrefixPosition(), + email => email.Permission(CommonPermissions.ManageUsers).Action("Index", "Admin", _routeValues).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } @@ -96,11 +100,7 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) [Feature("OrchardCore.Users.Registration")] public class RegistrationAdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", RegistrationSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", RegistrationSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -116,16 +116,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Settings"], settings => settings - .Add(S["User Registration"], S["User Registration"].PrefixPosition(), registration => registration - .Permission(CommonPermissions.ManageUsers) - .Action("Index", "Admin", _routeValues) - .LocalNav() - ) + builder.Add( + S["Security"], + security => + security.Add( + S["Settings"], + settings => + settings.Add( + S["User Registration"], + S["User Registration"].PrefixPosition(), + registration => registration.Permission(CommonPermissions.ManageUsers).Action("Index", "Admin", _routeValues).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } @@ -134,11 +137,7 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) [Feature("OrchardCore.Users.ResetPassword")] public class ResetPasswordAdminMenu : INavigationProvider { - private static readonly RouteValueDictionary _routeValues = new() - { - { "area", "OrchardCore.Settings" }, - { "groupId", ResetPasswordSettingsDisplayDriver.GroupId }, - }; + private static readonly RouteValueDictionary _routeValues = new() { { "area", "OrchardCore.Settings" }, { "groupId", ResetPasswordSettingsDisplayDriver.GroupId }, }; protected readonly IStringLocalizer S; @@ -154,16 +153,19 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Security"], security => security - .Add(S["Settings"], settings => settings - .Add(S["User Reset password"], S["User Reset password"].PrefixPosition(), password => password - .Permission(CommonPermissions.ManageUsers) - .Action("Index", "Admin", _routeValues) - .LocalNav() - ) + builder.Add( + S["Security"], + security => + security.Add( + S["Settings"], + settings => + settings.Add( + S["User Reset password"], + S["User Reset password"].PrefixPosition(), + password => password.Permission(CommonPermissions.ManageUsers).Action("Index", "Admin", _routeValues).LocalNav() + ) ) - ); + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Handlers/UserEventHandler.cs b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Handlers/UserEventHandler.cs index eda8d4ab415..9a410f9a872 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Handlers/UserEventHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Handlers/UserEventHandler.cs @@ -20,60 +20,77 @@ public class UserEventHandler : ILoginFormEvent, IUserEventHandler private readonly IServiceProvider _serviceProvider; private UserManager _userManager; - public UserEventHandler( - IAuditTrailManager auditTrailManager, - IHttpContextAccessor httpContextAccessor, - IServiceProvider serviceProvider) + public UserEventHandler(IAuditTrailManager auditTrailManager, IHttpContextAccessor httpContextAccessor, IServiceProvider serviceProvider) { _auditTrailManager = auditTrailManager; _httpContextAccessor = httpContextAccessor; _serviceProvider = serviceProvider; } - public Task LoggedInAsync(IUser user) - => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.LoggedIn, user); + public Task LoggedInAsync(IUser user) => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.LoggedIn, user); - public Task LoggingInFailedAsync(IUser user) - => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.LogInFailed, user); + public Task LoggingInFailedAsync(IUser user) => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.LogInFailed, user); - public Task LoggingInFailedAsync(string userName) - => _auditTrailManager.RecordEventAsync( - new AuditTrailContext - ( - name: UserAuditTrailEventConfiguration.LogInFailed, - category: UserAuditTrailEventConfiguration.User, - correlationId: string.Empty, - userId: string.Empty, - userName: userName, - new AuditTrailUserEvent - { - UserId = string.Empty, - UserName = userName - } - )); - - public Task IsLockedOutAsync(IUser user) - => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.LogInFailed, user); - - public Task DisabledAsync(UserContext context) - => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.Disabled, context.User, _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), _httpContextAccessor.HttpContext.User?.Identity?.Name); - - public Task EnabledAsync(UserContext context) - => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.Enabled, context.User, _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), _httpContextAccessor.HttpContext.User?.Identity?.Name); - - public Task CreatedAsync(UserCreateContext context) - => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.Created, context.User, _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), _httpContextAccessor.HttpContext.User?.Identity?.Name); - - public Task UpdatedAsync(UserUpdateContext context) - => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.Updated, context.User, _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), _httpContextAccessor.HttpContext.User?.Identity?.Name); - - public Task DeletedAsync(UserDeleteContext context) - => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.Deleted, context.User, _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), _httpContextAccessor.HttpContext.User?.Identity?.Name); + public Task LoggingInFailedAsync(string userName) => + _auditTrailManager.RecordEventAsync( + new AuditTrailContext( + name: UserAuditTrailEventConfiguration.LogInFailed, + category: UserAuditTrailEventConfiguration.User, + correlationId: string.Empty, + userId: string.Empty, + userName: userName, + new AuditTrailUserEvent { UserId = string.Empty, UserName = userName } + ) + ); + + public Task IsLockedOutAsync(IUser user) => RecordAuditTrailEventAsync(UserAuditTrailEventConfiguration.LogInFailed, user); + + public Task DisabledAsync(UserContext context) => + RecordAuditTrailEventAsync( + UserAuditTrailEventConfiguration.Disabled, + context.User, + _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), + _httpContextAccessor.HttpContext.User?.Identity?.Name + ); + + public Task EnabledAsync(UserContext context) => + RecordAuditTrailEventAsync( + UserAuditTrailEventConfiguration.Enabled, + context.User, + _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), + _httpContextAccessor.HttpContext.User?.Identity?.Name + ); + + public Task CreatedAsync(UserCreateContext context) => + RecordAuditTrailEventAsync( + UserAuditTrailEventConfiguration.Created, + context.User, + _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), + _httpContextAccessor.HttpContext.User?.Identity?.Name + ); + + public Task UpdatedAsync(UserUpdateContext context) => + RecordAuditTrailEventAsync( + UserAuditTrailEventConfiguration.Updated, + context.User, + _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), + _httpContextAccessor.HttpContext.User?.Identity?.Name + ); + + public Task DeletedAsync(UserDeleteContext context) => + RecordAuditTrailEventAsync( + UserAuditTrailEventConfiguration.Deleted, + context.User, + _httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier), + _httpContextAccessor.HttpContext.User?.Identity?.Name + ); #region Unused user events public Task CreatingAsync(UserCreateContext context) => Task.CompletedTask; + public Task UpdatingAsync(UserUpdateContext context) => Task.CompletedTask; + public Task DeletingAsync(UserDeleteContext context) => Task.CompletedTask; #endregion @@ -102,19 +119,15 @@ private async Task RecordAuditTrailEventAsync(string name, IUser user, string us } await _auditTrailManager.RecordEventAsync( - new AuditTrailContext - ( + new AuditTrailContext( name: name, category: UserAuditTrailEventConfiguration.User, correlationId: userId, userId: userIdActual, userName: userNameActual, - new AuditTrailUserEvent - { - UserId = userId, - UserName = userName - } - )); + new AuditTrailUserEvent { UserId = userId, UserName = userName } + ) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Registration/UserRegistrationAuditTrailEventConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Registration/UserRegistrationAuditTrailEventConfiguration.cs index 31722fa2a07..0e1a586a270 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Registration/UserRegistrationAuditTrailEventConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Registration/UserRegistrationAuditTrailEventConfiguration.cs @@ -10,7 +10,8 @@ public class UserRegistrationAuditTrailEventConfiguration : IConfigureOptions(User, S => S["User"]) + options + .For(User, S => S["User"]) .WithEvent(Registered, S => S["Registered"], S => S["A user was successfully registered."], true); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Registration/UserRegistrationEventHandler.cs b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Registration/UserRegistrationEventHandler.cs index a091dc94102..583cdd69f22 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Registration/UserRegistrationEventHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Registration/UserRegistrationEventHandler.cs @@ -15,16 +15,13 @@ public class UserRegistrationEventHandler : IRegistrationFormEvents private readonly IServiceProvider _serviceProvider; private UserManager _userManager; - public UserRegistrationEventHandler( - IAuditTrailManager auditTrailManager, - IServiceProvider serviceProvider) + public UserRegistrationEventHandler(IAuditTrailManager auditTrailManager, IServiceProvider serviceProvider) { _auditTrailManager = auditTrailManager; _serviceProvider = serviceProvider; } - public Task RegisteredAsync(IUser user) => - RecordAuditTrailEventAsync(UserRegistrationAuditTrailEventConfiguration.Registered, user); + public Task RegisteredAsync(IUser user) => RecordAuditTrailEventAsync(UserRegistrationAuditTrailEventConfiguration.Registered, user); #region Unused events @@ -40,19 +37,15 @@ private async Task RecordAuditTrailEventAsync(string name, IUser user) var userId = await _userManager.GetUserIdAsync(user); await _auditTrailManager.RecordEventAsync( - new AuditTrailContext - ( + new AuditTrailContext( name, UserRegistrationAuditTrailEventConfiguration.User, userId, userId, userName, - new AuditTrailUserEvent - { - UserId = userId, - UserName = userName - } - )); + new AuditTrailUserEvent { UserId = userId, UserName = userName } + ) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ResetPassword/UserResetPasswordAuditTrailEventConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ResetPassword/UserResetPasswordAuditTrailEventConfiguration.cs index cb6111fd708..75c1b7dfd15 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ResetPassword/UserResetPasswordAuditTrailEventConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ResetPassword/UserResetPasswordAuditTrailEventConfiguration.cs @@ -11,7 +11,8 @@ public class UserResetPasswordAuditTrailEventConfiguration : IConfigureOptions(User, S => S["User"]) + options + .For(User, S => S["User"]) .WithEvent(PasswordReset, S => S["Password reset"], S => S["A user successfully reset the password."], true) .WithEvent(PasswordRecovered, S => S["Password recovered"], S => S["A user successfully recovered the password."], true); } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ResetPassword/UserResetPasswordEventHandler.cs b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ResetPassword/UserResetPasswordEventHandler.cs index 2d6c234a677..c3bbabcddbf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ResetPassword/UserResetPasswordEventHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ResetPassword/UserResetPasswordEventHandler.cs @@ -15,19 +15,16 @@ public class UserResetPasswordEventHandler : IPasswordRecoveryFormEvents private readonly IServiceProvider _serviceProvider; private UserManager _userManager; - public UserResetPasswordEventHandler( - IAuditTrailManager auditTrailManager, - IServiceProvider serviceProvider) + public UserResetPasswordEventHandler(IAuditTrailManager auditTrailManager, IServiceProvider serviceProvider) { _auditTrailManager = auditTrailManager; _serviceProvider = serviceProvider; } - public Task PasswordRecoveredAsync(PasswordRecoveryContext context) - => RecordAuditTrailEventAsync(UserResetPasswordAuditTrailEventConfiguration.PasswordRecovered, context.User); + public Task PasswordRecoveredAsync(PasswordRecoveryContext context) => + RecordAuditTrailEventAsync(UserResetPasswordAuditTrailEventConfiguration.PasswordRecovered, context.User); - public Task PasswordResetAsync(PasswordRecoveryContext context) - => RecordAuditTrailEventAsync(UserResetPasswordAuditTrailEventConfiguration.PasswordReset, context.User); + public Task PasswordResetAsync(PasswordRecoveryContext context) => RecordAuditTrailEventAsync(UserResetPasswordAuditTrailEventConfiguration.PasswordReset, context.User); #region Unused events @@ -44,19 +41,15 @@ private async Task RecordAuditTrailEventAsync(string name, IUser user) var userId = await _userManager.GetUserIdAsync(user); await _auditTrailManager.RecordEventAsync( - new AuditTrailContext - ( + new AuditTrailContext( name, UserResetPasswordAuditTrailEventConfiguration.User, userId, userId, userName, - new AuditTrailUserEvent - { - UserId = userId, - UserName = userName - } - )); + new AuditTrailUserEvent { UserId = userId, UserName = userName } + ) + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Services/UserAuditTrailEventConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Services/UserAuditTrailEventConfiguration.cs index cd8c6ad1676..85aa36c604e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Services/UserAuditTrailEventConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Services/UserAuditTrailEventConfiguration.cs @@ -18,7 +18,8 @@ public class UserAuditTrailEventConfiguration : IConfigureOptions(User, S => S["User"]) + options + .For(User, S => S["User"]) .WithEvent(LoggedIn, S => S["Logged in"], S => S["A user was successfully logged in."], true) .WithEvent(LogInFailed, S => S["Login failed"], S => S["An attempt to login failed."], false) // Intentionally not enabled by default. .WithEvent(LogInIsLockedOut, S => S["Login account locked"], S => S["An attempt to login failed because the user is locked out."], true) diff --git a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Startup.cs index 13436b2e910..dc14bc3d1fc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/Startup.cs @@ -19,7 +19,8 @@ public override void ConfigureServices(IServiceCollection services) { services.AddTransient, UserAuditTrailEventConfiguration>(); - services.AddScoped() + services + .AddScoped() .AddScoped(sp => sp.GetRequiredService()) .AddScoped(sp => sp.GetRequiredService()); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ViewModels/AuditTrailUserEventDetailViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ViewModels/AuditTrailUserEventDetailViewModel.cs index 570dbe04658..94cc44d7952 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ViewModels/AuditTrailUserEventDetailViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/AuditTrail/ViewModels/AuditTrailUserEventDetailViewModel.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Users.AuditTrail.ViewModels { - public class AuditTrailUserEventDetailViewModel : AuditTrailUserEventViewModel - { - } + public class AuditTrailUserEventDetailViewModel : AuditTrailUserEventViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/CacheTicketStoreStartup.cs b/src/OrchardCore.Modules/OrchardCore.Users/CacheTicketStoreStartup.cs index b5104a8f330..af01d663a4c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/CacheTicketStoreStartup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/CacheTicketStoreStartup.cs @@ -33,8 +33,6 @@ public void Configure(string name, CookieAuthenticationOptions options) } } - public void Configure(CookieAuthenticationOptions options) - { - } + public void Configure(CookieAuthenticationOptions options) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Commands/UserCommands.cs b/src/OrchardCore.Modules/OrchardCore.Users/Commands/UserCommands.cs index c86dfd638dd..5fd5f5c5b83 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Commands/UserCommands.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Commands/UserCommands.cs @@ -12,9 +12,8 @@ public class UserCommands : DefaultCommandHandler { private readonly IUserService _userService; - public UserCommands( - IUserService userService, - IStringLocalizer localizer) : base(localizer) + public UserCommands(IUserService userService, IStringLocalizer localizer) + : base(localizer) { _userService = userService; } @@ -43,11 +42,22 @@ public async Task CreateUserAsync() var valid = true; - await _userService.CreateUserAsync(new User { UserName = UserName, Email = Email, PhoneNumber = PhoneNumber, RoleNames = roleNames, EmailConfirmed = true }, Password, (key, message) => - { - valid = false; - Context.Output.WriteLine(message); - }); + await _userService.CreateUserAsync( + new User + { + UserName = UserName, + Email = Email, + PhoneNumber = PhoneNumber, + RoleNames = roleNames, + EmailConfirmed = true + }, + Password, + (key, message) => + { + valid = false; + Context.Output.WriteLine(message); + } + ); if (valid) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountBaseController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountBaseController.cs index 43a584c1fe0..31aaab35c0e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountBaseController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountBaseController.cs @@ -23,8 +23,7 @@ protected async Task LoggedInActionResultAsync(IUser user, string ["Roles"] = u.RoleNames, ["Provider"] = info?.LoginProvider }; - await workflowManager.TriggerEventAsync(nameof(Workflows.Activities.UserLoggedInEvent), - input: input, correlationId: u.UserId); + await workflowManager.TriggerEventAsync(nameof(Workflows.Activities.UserLoggedInEvent), input: input, correlationId: u.UserId); } return RedirectToLocal(returnUrl); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountController.cs index 68939d50549..cb85b64e0be 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountController.cs @@ -57,7 +57,8 @@ public AccountController( IClock clock, IDistributedCache distributedCache, IDataProtectionProvider dataProtectionProvider, - IEnumerable externalLoginHandlers) + IEnumerable externalLoginHandlers + ) { _signInManager = signInManager; _userManager = userManager; @@ -93,8 +94,7 @@ public async Task Login(string returnUrl = null) var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync(); if (schemes.Count() == 1) { - var dataProtector = _dataProtectionProvider.CreateProtector(DefaultExternalLoginProtector) - .ToTimeLimitedDataProtector(); + var dataProtector = _dataProtectionProvider.CreateProtector(DefaultExternalLoginProtector).ToTimeLimitedDataProtector(); var token = Guid.NewGuid(); var expiration = new TimeSpan(0, 0, 5); @@ -121,8 +121,7 @@ public async Task DefaultExternalLogin(string protectedToken, str var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync(); if (schemes.Count() == 1) { - var dataProtector = _dataProtectionProvider.CreateProtector(DefaultExternalLoginProtector) - .ToTimeLimitedDataProtector(); + var dataProtector = _dataProtectionProvider.CreateProtector(DefaultExternalLoginProtector).ToTimeLimitedDataProtector(); try { @@ -164,7 +163,12 @@ public async Task Login(LoginViewModel model, string returnUrl = } else { - await _accountEvents.InvokeAsync((e, model, modelState) => e.LoggingInAsync(model.UserName, (key, message) => modelState.AddModelError(key, message)), model, ModelState, _logger); + await _accountEvents.InvokeAsync( + (e, model, modelState) => e.LoggingInAsync(model.UserName, (key, message) => modelState.AddModelError(key, message)), + model, + ModelState, + _logger + ); if (ModelState.IsValid) { var user = await _userService.GetUserAsync(model.UserName); @@ -189,13 +193,11 @@ public async Task Login(LoginViewModel model, string returnUrl = if (result.RequiresTwoFactor) { - return RedirectToAction(nameof(TwoFactorAuthenticationController.LoginWithTwoFactorAuthentication), + return RedirectToAction( + nameof(TwoFactorAuthenticationController.LoginWithTwoFactorAuthentication), typeof(TwoFactorAuthenticationController).ControllerName(), - new - { - returnUrl, - model.RememberMe - }); + new { returnUrl, model.RememberMe } + ); } if (result.IsLockedOut) @@ -264,9 +266,7 @@ public async Task ChangePassword(ChangePasswordViewModel model, s } [HttpGet] - public IActionResult ChangePasswordConfirmation() - => View(); - + public IActionResult ChangePasswordConfirmation() => View(); [HttpPost] [AllowAnonymous] @@ -351,7 +351,12 @@ public async Task ExternalLoginCallback(string returnUrl = null, { if (!await AddConfirmEmailErrorAsync(iUser) && !AddUserEnabledError(iUser)) { - await _accountEvents.InvokeAsync((e, user, modelState) => e.LoggingInAsync(user.UserName, (key, message) => modelState.AddModelError(key, message)), iUser, ModelState, _logger); + await _accountEvents.InvokeAsync( + (e, user, modelState) => e.LoggingInAsync(user.UserName, (key, message) => modelState.AddModelError(key, message)), + iUser, + ModelState, + _logger + ); var signInResult = await ExternalLoginSignInAsync(iUser, info); if (signInResult.Succeeded) @@ -380,13 +385,15 @@ public async Task ExternalLoginCallback(string returnUrl = null, { if (iUser is User userToLink && registrationSettings.UsersMustValidateEmail && !userToLink.EmailConfirmed) { - return RedirectToAction(nameof(RegistrationController.ConfirmEmailSent), + return RedirectToAction( + nameof(RegistrationController.ConfirmEmailSent), new { Area = "OrchardCore.Users", Controller = typeof(RegistrationController).ControllerName(), ReturnUrl = returnUrl, - }); + } + ); } // Link external login to an existing user @@ -418,24 +425,29 @@ public async Task ExternalLoginCallback(string returnUrl = null, // The user doesn't exist and no information required, we can create the account locally // instead of redirecting to the ExternalLogin. - var noInformationRequired = externalLoginViewModel.NoPassword - && externalLoginViewModel.NoEmail - && externalLoginViewModel.NoUsername; + var noInformationRequired = externalLoginViewModel.NoPassword && externalLoginViewModel.NoEmail && externalLoginViewModel.NoUsername; if (noInformationRequired) { - iUser = await this.RegisterUser(new RegisterViewModel() - { - UserName = externalLoginViewModel.UserName, - Email = externalLoginViewModel.Email, - Password = null, - ConfirmPassword = null - }, S["Confirm your account"], _logger); + iUser = await this.RegisterUser( + new RegisterViewModel() + { + UserName = externalLoginViewModel.UserName, + Email = externalLoginViewModel.Email, + Password = null, + ConfirmPassword = null + }, + S["Confirm your account"], + _logger + ); // If the registration was successful we can link the external provider and redirect the user. if (iUser != null) { - var identityResult = await _signInManager.UserManager.AddLoginAsync(iUser, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName)); + var identityResult = await _signInManager.UserManager.AddLoginAsync( + iUser, + new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName) + ); if (identityResult.Succeeded) { _logger.LogInformation(3, "User account linked to {LoginProvider} provider.", info.LoginProvider); @@ -445,24 +457,28 @@ public async Task ExternalLoginCallback(string returnUrl = null, { if (registrationSettings.UsersMustValidateEmail && !user.EmailConfirmed) { - return RedirectToAction(nameof(RegistrationController.ConfirmEmailSent), + return RedirectToAction( + nameof(RegistrationController.ConfirmEmailSent), new { Area = "OrchardCore.Users", Controller = typeof(RegistrationController).ControllerName(), ReturnUrl = returnUrl, - }); + } + ); } if (registrationSettings.UsersAreModerated && !user.IsEnabled) { - return RedirectToAction(nameof(RegistrationController.RegistrationPending), + return RedirectToAction( + nameof(RegistrationController.RegistrationPending), new { Area = "OrchardCore.Users", Controller = typeof(RegistrationController).ControllerName(), ReturnUrl = returnUrl, - }); + } + ); } } @@ -547,7 +563,10 @@ public async Task RegisterExternalLogin(RegisterExternalLoginView Email = model.Email, Password = model.Password, ConfirmPassword = model.ConfirmPassword - }, S["Confirm your account"], _logger); + }, + S["Confirm your account"], + _logger + ); if (iUser is null) { @@ -565,24 +584,28 @@ public async Task RegisterExternalLogin(RegisterExternalLoginView { if (settings.UsersMustValidateEmail && !user.EmailConfirmed) { - return RedirectToAction(nameof(RegistrationController.ConfirmEmailSent), + return RedirectToAction( + nameof(RegistrationController.ConfirmEmailSent), new { Area = "OrchardCore.Users", Controller = typeof(RegistrationController).ControllerName(), ReturnUrl = returnUrl, - }); + } + ); } if (settings.UsersAreModerated && !user.IsEnabled) { - return RedirectToAction(nameof(RegistrationController.RegistrationPending), + return RedirectToAction( + nameof(RegistrationController.RegistrationPending), new { Area = "OrchardCore.Users", Controller = typeof(RegistrationController).ControllerName(), ReturnUrl = returnUrl, - }); + } + ); } } @@ -620,15 +643,24 @@ public async Task LinkExternalLogin(LinkExternalLoginViewModel mo if (user == null) { - _logger.LogWarning("Suspicious login detected from external provider. {provider} with key [{providerKey}] for {identity}", - info.LoginProvider, info.ProviderKey, info.Principal?.Identity?.Name); + _logger.LogWarning( + "Suspicious login detected from external provider. {provider} with key [{providerKey}] for {identity}", + info.LoginProvider, + info.ProviderKey, + info.Principal?.Identity?.Name + ); return RedirectToAction(nameof(Login)); } if (ModelState.IsValid) { - await _accountEvents.InvokeAsync((e, model, modelState) => e.LoggingInAsync(user.UserName, (key, message) => modelState.AddModelError(key, message)), model, ModelState, _logger); + await _accountEvents.InvokeAsync( + (e, model, modelState) => e.LoggingInAsync(user.UserName, (key, message) => modelState.AddModelError(key, message)), + model, + ModelState, + _logger + ); var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false); if (!signInResult.Succeeded) @@ -668,9 +700,7 @@ public async Task ExternalLogins() } var model = new ExternalLoginsViewModel { CurrentLogins = await _userManager.GetLoginsAsync(user) }; - model.OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()) - .Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider)) - .ToList(); + model.OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider)).ToList(); model.ShowRemoveButton = await _userManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1; // model.StatusMessage = StatusMessage; @@ -754,7 +784,12 @@ public async Task RemoveLogin(RemoveLoginViewModel model) { if (!(await _userManager.RemoveAuthenticationTokenAsync(user, model.LoginProvider, item.Name)).Succeeded) { - _logger.LogError("Could not remove '{TokenName}' token while unlinking '{LoginProvider}' provider from user '{UserName}'.", item.Name, model.LoginProvider, user.UserName); + _logger.LogError( + "Could not remove '{TokenName}' token while unlinking '{LoginProvider}' provider from user '{UserName}'.", + item.Name, + model.LoginProvider, + user.UserName + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AdminController.cs index 6cd8a633dea..a1e22b63205 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AdminController.cs @@ -66,7 +66,8 @@ public AdminController( ILogger logger, IHtmlLocalizer htmlLocalizer, IStringLocalizer stringLocalizer, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _userDisplayManager = userDisplayManager; _userOptionsDisplayManager = userOptionsDisplayManager; @@ -86,7 +87,10 @@ public AdminController( S = stringLocalizer; } - public async Task Index([ModelBinder(BinderType = typeof(UserFilterEngineModelBinder), Name = "q")] QueryFilterResult queryFilterResult, PagerParameters pagerParameters) + public async Task Index( + [ModelBinder(BinderType = typeof(UserFilterEngineModelBinder), Name = "q")] QueryFilterResult queryFilterResult, + PagerParameters pagerParameters + ) { // Check a dummy user account to see if the current user has permission to view users. if (!await _authorizationService.AuthorizeAsync(User, CommonPermissions.ListUsers, new User())) @@ -116,10 +120,7 @@ public async Task Index([ModelBinder(BinderType = typeof(UserFilte var count = await users.CountAsync(); - var results = await users - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize) - .ListAsync(); + var results = await users.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync(); dynamic pagerShape = await _shapeFactory.PagerAsync(pager, count, options.RouteValues); @@ -127,18 +128,35 @@ public async Task Index([ModelBinder(BinderType = typeof(UserFilte foreach (var user in results) { - userEntries.Add(new UserEntry - { - UserId = user.UserId, - Shape = await _userDisplayManager.BuildDisplayAsync(user, updater: _updateModelAccessor.ModelUpdater, displayType: "SummaryAdmin") - }); + userEntries.Add( + new UserEntry + { + UserId = user.UserId, + Shape = await _userDisplayManager.BuildDisplayAsync(user, updater: _updateModelAccessor.ModelUpdater, displayType: "SummaryAdmin") + } + ); } options.UserFilters = [ - new SelectListItem() { Text = S["All Users"], Value = nameof(UsersFilter.All), Selected = (options.Filter == UsersFilter.All) }, - new SelectListItem() { Text = S["Enabled Users"], Value = nameof(UsersFilter.Enabled), Selected = (options.Filter == UsersFilter.Enabled) }, - new SelectListItem() { Text = S["Disabled Users"], Value = nameof(UsersFilter.Disabled), Selected = (options.Filter == UsersFilter.Disabled) } + new SelectListItem() + { + Text = S["All Users"], + Value = nameof(UsersFilter.All), + Selected = (options.Filter == UsersFilter.All) + }, + new SelectListItem() + { + Text = S["Enabled Users"], + Value = nameof(UsersFilter.Enabled), + Selected = (options.Filter == UsersFilter.Enabled) + }, + new SelectListItem() + { + Text = S["Disabled Users"], + Value = nameof(UsersFilter.Disabled), + Selected = (options.Filter == UsersFilter.Disabled) + } // new SelectListItem() { Text = S["Approved"], Value = nameof(UsersFilter.Approved) }, // new SelectListItem() { Text = S["Email pending"], Value = nameof(UsersFilter.EmailPending) }, // new SelectListItem() { Text = S["Pending"], Value = nameof(UsersFilter.Pending) } @@ -146,8 +164,18 @@ public async Task Index([ModelBinder(BinderType = typeof(UserFilte options.UserSorts = [ - new SelectListItem() { Text = S["Name"], Value = nameof(UsersOrder.Name), Selected = (options.Order == UsersOrder.Name) }, - new SelectListItem() { Text = S["Email"], Value = nameof(UsersOrder.Email), Selected = (options.Order == UsersOrder.Email) }, + new SelectListItem() + { + Text = S["Name"], + Value = nameof(UsersOrder.Name), + Selected = (options.Order == UsersOrder.Name) + }, + new SelectListItem() + { + Text = S["Email"], + Value = nameof(UsersOrder.Email), + Selected = (options.Order == UsersOrder.Email) + }, // new SelectListItem() { Text = S["Created date"], Value = nameof(UsersOrder.CreatedUtc) }, // new SelectListItem() { Text = S["Last Login date"], Value = nameof(UsersOrder.LastLoginUtc) } ]; @@ -176,8 +204,18 @@ public async Task Index([ModelBinder(BinderType = typeof(UserFilte options.UserRoleFilters = [ - new SelectListItem() { Text = S["Any role"], Value = string.Empty, Selected = options.SelectedRole == string.Empty }, - new SelectListItem() { Text = S["Authenticated (no roles)"], Value = "Authenticated", Selected = string.Equals(options.SelectedRole, "Authenticated", StringComparison.OrdinalIgnoreCase) }, + new SelectListItem() + { + Text = S["Any role"], + Value = string.Empty, + Selected = options.SelectedRole == string.Empty + }, + new SelectListItem() + { + Text = S["Authenticated (no roles)"], + Value = "Authenticated", + Selected = string.Equals(options.SelectedRole, "Authenticated", StringComparison.OrdinalIgnoreCase) + }, // TODO Candidate for dynamic localization. .. roleNames.Select(roleName => new SelectListItem @@ -197,13 +235,16 @@ .. roleNames.Select(roleName => var header = await _userOptionsDisplayManager.BuildEditorAsync(options, _updateModelAccessor.ModelUpdater, false, string.Empty, string.Empty); - var shapeViewModel = await _shapeFactory.CreateAsync("UsersAdminList", viewModel => - { - viewModel.Users = userEntries; - viewModel.Pager = pagerShape; - viewModel.Options = options; - viewModel.Header = header; - }); + var shapeViewModel = await _shapeFactory.CreateAsync( + "UsersAdminList", + viewModel => + { + viewModel.Users = userEntries; + viewModel.Pager = pagerShape; + viewModel.Options = options; + viewModel.Header = header; + } + ); return View(shapeViewModel); } @@ -250,7 +291,8 @@ public async Task IndexPOST(UserIndexOptions options, IEnumerable< switch (options.BulkAction) { - case UsersBulkAction.None: break; + case UsersBulkAction.None: + break; case UsersBulkAction.Approve: if (canEditUser && !await _userManager.IsEmailConfirmedAsync(user)) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AuthenticatorAppController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AuthenticatorAppController.cs index 9acf9a18cb6..268dbcee603 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AuthenticatorAppController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AuthenticatorAppController.cs @@ -40,17 +40,9 @@ public AuthenticatorAppController( IDistributedCache distributedCache, UrlEncoder urlEncoder, ShellSettings shellSettings, - ITwoFactorAuthenticationHandlerCoordinator twoFactorAuthenticationHandlerCoordinator) - : base( - userManager, - distributedCache, - signInManager, - twoFactorAuthenticationHandlerCoordinator, - notifier, - siteService, - htmlLocalizer, - stringLocalizer, - twoFactorOptions) + ITwoFactorAuthenticationHandlerCoordinator twoFactorAuthenticationHandlerCoordinator + ) + : base(userManager, distributedCache, signInManager, twoFactorAuthenticationHandlerCoordinator, notifier, siteService, htmlLocalizer, stringLocalizer, twoFactorOptions) { _urlEncoder = urlEncoder; _shellSettings = shellSettings; @@ -135,12 +127,15 @@ public async Task ResetPost() return UserNotFound(); } - return await RemoveTwoFactorProviderAync(user, async () => - { - await UserManager.ResetAuthenticatorKeyAsync(user); + return await RemoveTwoFactorProviderAync( + user, + async () => + { + await UserManager.ResetAuthenticatorKeyAsync(user); - await Notifier.SuccessAsync(H["Your authenticator app key has been reset."]); - }); + await Notifier.SuccessAsync(H["Your authenticator app key has been reset."]); + } + ); } private async Task LoadSharedKeyAndQrCodeUriAsync(IUser user, AuthenticatorAppLoginSettings settings) @@ -163,8 +158,7 @@ private async Task LoadSharedKeyAndQrCodeUriAsync( }; } - private Task GetUserDisplayNameAsync(IUser user, bool showEmail) - => showEmail ? UserManager.GetEmailAsync(user) : UserManager.GetUserNameAsync(user); + private Task GetUserDisplayNameAsync(IUser user, bool showEmail) => showEmail ? UserManager.GetEmailAsync(user) : UserManager.GetUserNameAsync(user); private static string FormatKey(string unformattedKey) { @@ -189,12 +183,6 @@ private async Task GenerateQrCodeUriAsync(string displayName, string unf var issuer = string.IsNullOrWhiteSpace(site.SiteName) ? _shellSettings.Name : site.SiteName.Trim(); - return string.Format( - CultureInfo.InvariantCulture, - AuthenticatorUriFormat, - _urlEncoder.Encode(issuer), - _urlEncoder.Encode(displayName), - unformattedKey, - tokenLength); + return string.Format(CultureInfo.InvariantCulture, AuthenticatorUriFormat, _urlEncoder.Encode(issuer), _urlEncoder.Encode(displayName), unformattedKey, tokenLength); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ChangeEmailController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ChangeEmailController.cs index 965e620d918..a89359a7914 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ChangeEmailController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ChangeEmailController.cs @@ -20,11 +20,7 @@ public class ChangeEmailController : Controller private readonly ISiteService _siteService; protected readonly IStringLocalizer S; - public ChangeEmailController( - IUserService userService, - UserManager userManager, - ISiteService siteService, - IStringLocalizer stringLocalizer) + public ChangeEmailController(IUserService userService, UserManager userManager, ISiteService siteService, IStringLocalizer stringLocalizer) { _userService = userService; _userManager = userManager; @@ -71,8 +67,7 @@ public async Task Index(ChangeEmailViewModel model) } else { - if (await _userService.ChangeEmailAsync(user, model.Email, - (key, message) => ModelState.AddModelError(key, message))) + if (await _userService.ChangeEmailAsync(user, model.Email, (key, message) => ModelState.AddModelError(key, message))) { return RedirectToLocal(Url.Action("ChangeEmailConfirmation", "ChangeEmail")); } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ControllerExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ControllerExtensions.cs index 871ec7dba5a..9709ff8b3b8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ControllerExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ControllerExtensions.cs @@ -64,11 +64,26 @@ internal static async Task RegisterUser(this Controller controller, Regis if (settings.UsersCanRegister != UserRegistrationType.NoRegistration) { - await registrationEvents.InvokeAsync((e, modelState) => e.RegistrationValidationAsync((key, message) => modelState.AddModelError(key, message)), controller.ModelState, logger); + await registrationEvents.InvokeAsync( + (e, modelState) => e.RegistrationValidationAsync((key, message) => modelState.AddModelError(key, message)), + controller.ModelState, + logger + ); if (controller.ModelState.IsValid) { - var user = await userService.CreateUserAsync(new User { UserName = model.UserName, Email = model.Email, EmailConfirmed = !settings.UsersMustValidateEmail, IsEnabled = !settings.UsersAreModerated }, model.Password, (key, message) => controller.ModelState.AddModelError(key, message)) as User; + var user = + await userService.CreateUserAsync( + new User + { + UserName = model.UserName, + Email = model.Email, + EmailConfirmed = !settings.UsersMustValidateEmail, + IsEnabled = !settings.UsersAreModerated + }, + model.Password, + (key, message) => controller.ModelState.AddModelError(key, message) + ) as User; if (user != null && controller.ModelState.IsValid) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/EmailAuthenticatorController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/EmailAuthenticatorController.cs index 55f56b65a3c..66f8ede864a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/EmailAuthenticatorController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/EmailAuthenticatorController.cs @@ -44,17 +44,9 @@ public EmailAuthenticatorController( ISmtpService smtpService, ILiquidTemplateManager liquidTemplateManager, HtmlEncoder htmlEncoder, - ITwoFactorAuthenticationHandlerCoordinator twoFactorAuthenticationHandlerCoordinator) - : base( - userManager, - distributedCache, - signInManager, - twoFactorAuthenticationHandlerCoordinator, - notifier, - siteService, - htmlLocalizer, - stringLocalizer, - twoFactorOptions) + ITwoFactorAuthenticationHandlerCoordinator twoFactorAuthenticationHandlerCoordinator + ) + : base(userManager, distributedCache, signInManager, twoFactorAuthenticationHandlerCoordinator, notifier, siteService, htmlLocalizer, stringLocalizer, twoFactorOptions) { _userService = userService; _smtpService = smtpService; @@ -160,11 +152,7 @@ public async Task SendCode() if (user == null) { - return BadRequest(new - { - success = false, - message = errorMessage.Value, - }); + return BadRequest(new { success = false, message = errorMessage.Value, }); } var settings = (await SiteService.GetSiteSettingsAsync()).As(); @@ -180,40 +168,37 @@ public async Task SendCode() var result = await _smtpService.SendAsync(message); - return Ok(new - { - success = result.Succeeded, - message = result.Succeeded ? S["A verification code has been sent via email. Please check your email for the code."].Value - : errorMessage.Value, - }); + return Ok( + new + { + success = result.Succeeded, + message = result.Succeeded ? S["A verification code has been sent via email. Please check your email for the code."].Value : errorMessage.Value, + } + ); } private Task GetSubjectAsync(EmailAuthenticatorLoginSettings settings, IUser user, string code) { - var message = string.IsNullOrWhiteSpace(settings.Subject) - ? EmailAuthenticatorLoginSettings.DefaultSubject - : settings.Subject; + var message = string.IsNullOrWhiteSpace(settings.Subject) ? EmailAuthenticatorLoginSettings.DefaultSubject : settings.Subject; return GetContentAsync(message, user, code); } private Task GetBodyAsync(EmailAuthenticatorLoginSettings settings, IUser user, string code) { - var message = string.IsNullOrWhiteSpace(settings.Body) - ? EmailAuthenticatorLoginSettings.DefaultBody - : settings.Body; + var message = string.IsNullOrWhiteSpace(settings.Body) ? EmailAuthenticatorLoginSettings.DefaultBody : settings.Body; return GetContentAsync(message, user, code); } private async Task GetContentAsync(string message, IUser user, string code) { - var result = await _liquidTemplateManager.RenderHtmlContentAsync(message, _htmlEncoder, null, - new Dictionary() - { - ["User"] = new ObjectValue(user), - ["Code"] = new StringValue(code), - }); + var result = await _liquidTemplateManager.RenderHtmlContentAsync( + message, + _htmlEncoder, + null, + new Dictionary() { ["User"] = new ObjectValue(user), ["Code"] = new StringValue(code), } + ); using var writer = new StringWriter(); result.WriteTo(writer, _htmlEncoder); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/RegistrationController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/RegistrationController.cs index fd8aee15ab5..d49389162e2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/RegistrationController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/RegistrationController.cs @@ -32,7 +32,8 @@ public RegistrationController( INotifier notifier, ILogger logger, IHtmlLocalizer htmlLocalizer, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _userManager = userManager; _authorizationService = authorizationService; @@ -138,13 +139,11 @@ public async Task ConfirmEmail(string userId, string code) [HttpGet] [AllowAnonymous] - public IActionResult ConfirmEmailSent(string returnUrl = null) - => View(new { ReturnUrl = returnUrl }); + public IActionResult ConfirmEmailSent(string returnUrl = null) => View(new { ReturnUrl = returnUrl }); [HttpGet] [AllowAnonymous] - public IActionResult RegistrationPending(string returnUrl = null) - => View(new { ReturnUrl = returnUrl }); + public IActionResult RegistrationPending(string returnUrl = null) => View(new { ReturnUrl = returnUrl }); [Authorize] [HttpPost] diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ResetPasswordController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ResetPasswordController.cs index 31cb64985a1..3328507d92e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ResetPasswordController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ResetPasswordController.cs @@ -32,7 +32,8 @@ public ResetPasswordController( ISiteService siteService, IStringLocalizer stringLocalizer, ILogger logger, - IEnumerable passwordRecoveryFormEvents) + IEnumerable passwordRecoveryFormEvents + ) { _userService = userService; _userManager = userManager; @@ -64,15 +65,19 @@ public async Task ForgotPassword(ForgotPasswordViewModel model) return NotFound(); } - await _passwordRecoveryFormEvents.InvokeAsync((e, modelState) => e.RecoveringPasswordAsync((key, message) => modelState.AddModelError(key, message)), ModelState, _logger); + await _passwordRecoveryFormEvents.InvokeAsync( + (e, modelState) => e.RecoveringPasswordAsync((key, message) => modelState.AddModelError(key, message)), + ModelState, + _logger + ); if (TryValidateModel(model) && ModelState.IsValid) { var user = await _userService.GetForgotPasswordUserAsync(model.Email) as User; - if (user == null || ( - (await _siteService.GetSiteSettingsAsync()).As().UsersMustValidateEmail - && !await _userManager.IsEmailConfirmedAsync(user)) - ) + if ( + user == null + || ((await _siteService.GetSiteSettingsAsync()).As().UsersMustValidateEmail && !await _userManager.IsEmailConfirmedAsync(user)) + ) { // returns to confirmation page anyway: we don't want to let scrapers know if a username or an email exist return RedirectToLocal(Url.Action("ForgotPasswordConfirmation", "ResetPassword")); @@ -126,11 +131,22 @@ public async Task ResetPassword(ResetPasswordViewModel model) return NotFound(); } - await _passwordRecoveryFormEvents.InvokeAsync((e, modelState) => e.ResettingPasswordAsync((key, message) => modelState.AddModelError(key, message)), ModelState, _logger); + await _passwordRecoveryFormEvents.InvokeAsync( + (e, modelState) => e.ResettingPasswordAsync((key, message) => modelState.AddModelError(key, message)), + ModelState, + _logger + ); if (TryValidateModel(model) && ModelState.IsValid) { - if (await _userService.ResetPasswordAsync(model.Email, Encoding.UTF8.GetString(Convert.FromBase64String(model.ResetToken)), model.NewPassword, (key, message) => ModelState.AddModelError(key == "Password" ? nameof(ResetPasswordViewModel.NewPassword) : key, message))) + if ( + await _userService.ResetPasswordAsync( + model.Email, + Encoding.UTF8.GetString(Convert.FromBase64String(model.ResetToken)), + model.NewPassword, + (key, message) => ModelState.AddModelError(key == "Password" ? nameof(ResetPasswordViewModel.NewPassword) : key, message) + ) + ) { return RedirectToLocal(Url.Action("ResetPasswordConfirmation", "ResetPassword")); } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/SmsAuthenticatorController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/SmsAuthenticatorController.cs index b1a0fa95f09..ca5faa3c34c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/SmsAuthenticatorController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/SmsAuthenticatorController.cs @@ -48,17 +48,9 @@ public SmsAuthenticatorController( ILiquidTemplateManager liquidTemplateManager, IPhoneFormatValidator phoneFormatValidator, HtmlEncoder htmlEncoder, - ITwoFactorAuthenticationHandlerCoordinator twoFactorAuthenticationHandlerCoordinator) - : base( - userManager, - distributedCache, - signInManager, - twoFactorAuthenticationHandlerCoordinator, - notifier, - siteService, - htmlLocalizer, - stringLocalizer, - twoFactorOptions) + ITwoFactorAuthenticationHandlerCoordinator twoFactorAuthenticationHandlerCoordinator + ) + : base(userManager, distributedCache, signInManager, twoFactorAuthenticationHandlerCoordinator, notifier, siteService, htmlLocalizer, stringLocalizer, twoFactorOptions) { _userService = userService; _smsService = smsService; @@ -83,9 +75,7 @@ public async Task Index() var model = new RequestCodeSmsAuthenticatorViewModel() { PhoneNumber = currentPhoneNumber, - AllowChangingPhoneNumber = settings.AllowChangingPhoneNumber - || string.IsNullOrEmpty(currentPhoneNumber) - || !_phoneFormatValidator.IsValid(currentPhoneNumber), + AllowChangingPhoneNumber = settings.AllowChangingPhoneNumber || string.IsNullOrEmpty(currentPhoneNumber) || !_phoneFormatValidator.IsValid(currentPhoneNumber), }; return View(model); @@ -104,9 +94,7 @@ public async Task IndexPost(RequestCodeSmsAuthenticatorViewModel var currentPhoneNumber = await UserManager.GetPhoneNumberAsync(user); - var canSetNewPhone = settings.AllowChangingPhoneNumber - || string.IsNullOrEmpty(currentPhoneNumber) - || !_phoneFormatValidator.IsValid(currentPhoneNumber); + var canSetNewPhone = settings.AllowChangingPhoneNumber || string.IsNullOrEmpty(currentPhoneNumber) || !_phoneFormatValidator.IsValid(currentPhoneNumber); model.AllowChangingPhoneNumber = canSetNewPhone; @@ -122,11 +110,7 @@ public async Task IndexPost(RequestCodeSmsAuthenticatorViewModel var code = await UserManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber); var smsSettings = (await SiteService.GetSiteSettingsAsync()).As(); - var message = new SmsMessage() - { - To = phoneNumber, - Body = await GetBodyAsync(smsSettings, user, code), - }; + var message = new SmsMessage() { To = phoneNumber, Body = await GetBodyAsync(smsSettings, user, code), }; var result = await _smsService.SendAsync(message); @@ -162,10 +146,7 @@ public async Task ValidateCode() return RedirectToAction(nameof(Index)); } - var model = new EnableSmsAuthenticatorViewModel - { - PhoneNumber = pendingPhoneNumber, - }; + var model = new EnableSmsAuthenticatorViewModel { PhoneNumber = pendingPhoneNumber, }; return View(model); } @@ -212,49 +193,40 @@ public async Task SendCode() if (user == null) { - return BadRequest(new - { - success = false, - message = errorMessage.Value, - }); + return BadRequest(new { success = false, message = errorMessage.Value, }); } var settings = (await SiteService.GetSiteSettingsAsync()).As(); var code = await UserManager.GenerateTwoFactorTokenAsync(user, TokenOptions.DefaultPhoneProvider); - var message = new SmsMessage() - { - To = await UserManager.GetPhoneNumberAsync(user), - Body = await GetBodyAsync(settings, user, code), - }; + var message = new SmsMessage() { To = await UserManager.GetPhoneNumberAsync(user), Body = await GetBodyAsync(settings, user, code), }; var result = await _smsService.SendAsync(message); - return Ok(new - { - success = result.Succeeded, - message = result.Succeeded ? S["A verification code has been sent to your phone number. Please check your device for the code."].Value - : errorMessage.Value, - }); + return Ok( + new + { + success = result.Succeeded, + message = result.Succeeded ? S["A verification code has been sent to your phone number. Please check your device for the code."].Value : errorMessage.Value, + } + ); } private Task GetBodyAsync(SmsAuthenticatorLoginSettings settings, IUser user, string code) { - var message = string.IsNullOrWhiteSpace(settings.Body) - ? EmailAuthenticatorLoginSettings.DefaultBody - : settings.Body; + var message = string.IsNullOrWhiteSpace(settings.Body) ? EmailAuthenticatorLoginSettings.DefaultBody : settings.Body; return GetContentAsync(message, user, code); } private async Task GetContentAsync(string message, IUser user, string code) { - var result = await _liquidTemplateManager.RenderHtmlContentAsync(message, _htmlEncoder, null, - new Dictionary() - { - ["User"] = new ObjectValue(user), - ["Code"] = new StringValue(code), - }); + var result = await _liquidTemplateManager.RenderHtmlContentAsync( + message, + _htmlEncoder, + null, + new Dictionary() { ["User"] = new ObjectValue(user), ["Code"] = new StringValue(code), } + ); using var writer = new StringWriter(); result.WriteTo(writer, _htmlEncoder); @@ -268,11 +240,7 @@ protected async Task SetPendingPhoneNumberAsync(string phoneNumber, string usern var data = Encoding.UTF8.GetBytes(phoneNumber); - await DistributedCache.SetAsync(key, data, - new DistributedCacheEntryOptions() - { - AbsoluteExpirationRelativeToNow = new TimeSpan(0, 10, 0) - }); + await DistributedCache.SetAsync(key, data, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = new TimeSpan(0, 10, 0) }); } private async Task GetPendingPhoneNumberAsync(string username) @@ -289,6 +257,5 @@ private async Task GetPendingPhoneNumberAsync(string username) return null; } - private static string GetPhoneChangeCacheKey(string username) - => $"TwoFactorAuthenticationPhoneNumberChange_{username}"; + private static string GetPhoneChangeCacheKey(string username) => $"TwoFactorAuthenticationPhoneNumberChange_{username}"; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/TwoFactorAuthenticationBaseController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/TwoFactorAuthenticationBaseController.cs index 60883652d3d..59096014d58 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/TwoFactorAuthenticationBaseController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/TwoFactorAuthenticationBaseController.cs @@ -42,7 +42,8 @@ public TwoFactorAuthenticationBaseController( ISiteService siteService, IHtmlLocalizer htmlLocalizer, IStringLocalizer stringLocalizer, - IOptions twoFactorOptions) + IOptions twoFactorOptions + ) { UserManager = userManager; DistributedCache = distributedCache; @@ -59,18 +60,11 @@ protected async Task SetRecoveryCodesAsync(string[] codes, string userId) { var key = GetRecoveryCodesCacheKey(userId); - var model = new ShowRecoveryCodesViewModel() - { - RecoveryCodes = codes ?? [], - }; + var model = new ShowRecoveryCodesViewModel() { RecoveryCodes = codes ?? [], }; var data = JsonSerializer.SerializeToUtf8Bytes(model); - await DistributedCache.SetAsync(key, data, - new DistributedCacheEntryOptions() - { - AbsoluteExpirationRelativeToNow = new TimeSpan(0, 0, 5) - }); + await DistributedCache.SetAsync(key, data, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = new TimeSpan(0, 0, 5) }); } protected async Task RemoveTwoFactorProviderAync(IUser user, Func onSuccessAsync) @@ -124,8 +118,7 @@ protected async Task EnableTwoFactorAuthenticationAsync(IUser user) protected async Task RefreshTwoFactorClaimAsync(IUser user) { - var twoFactorClaim = (await UserManager.GetClaimsAsync(user)) - .FirstOrDefault(claim => claim.Type == UserConstants.TwoFactorAuthenticationClaimType); + var twoFactorClaim = (await UserManager.GetClaimsAsync(user)).FirstOrDefault(claim => claim.Type == UserConstants.TwoFactorAuthenticationClaimType); if (twoFactorClaim != null) { @@ -158,18 +151,13 @@ protected async Task> GetTwoFactorProvidersAsync(IUser user) return providers.Intersect(TwoFactorOptions.Providers).ToList(); } - protected IActionResult RedirectToTwoFactorIndex() - => RedirectToAction(nameof(TwoFactorAuthenticationController.Index), _twoFactorAuthenticationControllerName); + protected IActionResult RedirectToTwoFactorIndex() => RedirectToAction(nameof(TwoFactorAuthenticationController.Index), _twoFactorAuthenticationControllerName); - protected IActionResult RedirectToAccountLogin() - => RedirectToAction(nameof(AccountController.Login), _accountControllerName); + protected IActionResult RedirectToAccountLogin() => RedirectToAction(nameof(AccountController.Login), _accountControllerName); - protected IActionResult UserNotFound() - => NotFound("Unable to load user."); + protected IActionResult UserNotFound() => NotFound("Unable to load user."); - protected static string StripToken(string code) - => code.Replace(" ", string.Empty).Replace("-", string.Empty); + protected static string StripToken(string code) => code.Replace(" ", string.Empty).Replace("-", string.Empty); - protected static string GetRecoveryCodesCacheKey(string userId) - => $"TwoFactorAuthenticationRecoveryCodes_{userId}"; + protected static string GetRecoveryCodesCacheKey(string userId) => $"TwoFactorAuthenticationRecoveryCodes_{userId}"; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/TwoFactorAuthenticationController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/TwoFactorAuthenticationController.cs index a1c62245cde..e0262f78f83 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/TwoFactorAuthenticationController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/TwoFactorAuthenticationController.cs @@ -47,16 +47,9 @@ public TwoFactorAuthenticationController( IOptions identityOptions, ITwoFactorAuthenticationHandlerCoordinator twoFactorHandlerCoordinator, IShapeFactory shapeFactory, - IDisplayManager twoFactorDisplayManager) - : base(userManager, - distributedCache, - signInManager, - twoFactorHandlerCoordinator, - notifier, - siteService, - htmlLocalizer, - stringLocalizer, - twoFactorOptions) + IDisplayManager twoFactorDisplayManager + ) + : base(userManager, distributedCache, signInManager, twoFactorHandlerCoordinator, notifier, siteService, htmlLocalizer, stringLocalizer, twoFactorOptions) { _logger = logger; _accountEvents = accountEvents; @@ -168,10 +161,7 @@ public async Task LoginWithRecoveryCode(string returnUrl = null) return RedirectToAccountLogin(); } - return View(new LoginWithRecoveryCodeViewModel() - { - ReturnUrl = returnUrl, - }); + return View(new LoginWithRecoveryCodeViewModel() { ReturnUrl = returnUrl, }); } [HttpPost, AllowAnonymous] @@ -251,10 +241,7 @@ public async Task Index(TwoFactorAuthenticationViewModel model) { if (user is User u && providers.Contains(model.PreferredProvider)) { - u.Put(new TwoFactorPreference() - { - DefaultProvider = model.PreferredProvider - }); + u.Put(new TwoFactorPreference() { DefaultProvider = model.PreferredProvider }); await UserManager.UpdateAsync(u); @@ -349,10 +336,7 @@ public async Task ShowRecoveryCodes() return RedirectToAction(nameof(Index)); } - return View(new ShowRecoveryCodesViewModel() - { - RecoveryCodes = recoveryCodes, - }); + return View(new ShowRecoveryCodesViewModel() { RecoveryCodes = recoveryCodes, }); } [HttpPost] @@ -490,11 +474,7 @@ private async Task PopulateModelAsync(IUser user, IList providers, TwoFa foreach (var key in TwoFactorOptions.Providers) { - var method = new TwoFactorMethod() - { - Provider = key, - IsEnabled = providers.Contains(key), - }; + var method = new TwoFactorMethod() { Provider = key, IsEnabled = providers.Contains(key), }; var shape = await _twoFactorDisplayManager.BuildDisplayAsync(method, this, "SummaryAdmin"); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/CustomUserSettingsPermissions.cs b/src/OrchardCore.Modules/OrchardCore.Users/CustomUserSettingsPermissions.cs index 34ae7358af1..344d1b80516 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/CustomUserSettingsPermissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/CustomUserSettingsPermissions.cs @@ -10,7 +10,8 @@ namespace OrchardCore.Users; public class CustomUserSettingsPermissions : IPermissionProvider { // This permission is never checked it is only used as a template. - private static readonly Permission _manageOwnCustomUserSettings = new("ManageOwnCustomUserSettings_{0}", "Manage Own Custom User Settings - {0}", new[] { Permissions.ManageUsers }); + private static readonly Permission _manageOwnCustomUserSettings = + new("ManageOwnCustomUserSettings_{0}", "Manage Own Custom User Settings - {0}", new[] { Permissions.ManageUsers }); private readonly IContentDefinitionManager _contentDefinitionManager; @@ -19,13 +20,10 @@ public CustomUserSettingsPermissions(IContentDefinitionManager contentDefinition _contentDefinitionManager = contentDefinitionManager; } - public async Task> GetPermissionsAsync() - => (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(x => x.GetStereotype() == "CustomUserSettings") - .Select(CreatePermissionForType); + public async Task> GetPermissionsAsync() => + (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(x => x.GetStereotype() == "CustomUserSettings").Select(CreatePermissionForType); - public IEnumerable GetDefaultStereotypes() - => []; + public IEnumerable GetDefaultStereotypes() => []; public static Permission CreatePermissionForType(ContentTypeDefinition type) => new( diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Deployment/AllUsersDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Users/Deployment/AllUsersDeploymentSource.cs index 69d3b418593..549122ff953 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Deployment/AllUsersDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Deployment/AllUsersDeploymentSource.cs @@ -27,33 +27,32 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan foreach (var user in allUsers) { - users.Add(JObject.FromObject( - new UsersStepUserModel - { - UserName = user.UserName, - UserId = user.UserId, - Id = user.Id, - Email = user.Email, - EmailConfirmed = user.EmailConfirmed, - PasswordHash = user.PasswordHash, - IsEnabled = user.IsEnabled, - NormalizedEmail = user.NormalizedEmail, - NormalizedUserName = user.NormalizedUserName, - SecurityStamp = user.SecurityStamp, - ResetToken = user.ResetToken, - PhoneNumber = user.PhoneNumber, - PhoneNumberConfirmed = user.PhoneNumberConfirmed, - TwoFactorEnabled = user.TwoFactorEnabled, - IsLockoutEnabled = user.IsLockoutEnabled, - AccessFailedCount = user.AccessFailedCount, - RoleNames = user.RoleNames, - })); + users.Add( + JObject.FromObject( + new UsersStepUserModel + { + UserName = user.UserName, + UserId = user.UserId, + Id = user.Id, + Email = user.Email, + EmailConfirmed = user.EmailConfirmed, + PasswordHash = user.PasswordHash, + IsEnabled = user.IsEnabled, + NormalizedEmail = user.NormalizedEmail, + NormalizedUserName = user.NormalizedUserName, + SecurityStamp = user.SecurityStamp, + ResetToken = user.ResetToken, + PhoneNumber = user.PhoneNumber, + PhoneNumberConfirmed = user.PhoneNumberConfirmed, + TwoFactorEnabled = user.TwoFactorEnabled, + IsLockoutEnabled = user.IsLockoutEnabled, + AccessFailedCount = user.AccessFailedCount, + RoleNames = user.RoleNames, + } + ) + ); } - result.Steps.Add(new JsonObject - { - ["name"] = "Users", - ["Users"] = users, - }); + result.Steps.Add(new JsonObject { ["name"] = "Users", ["Users"] = users, }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Deployment/AllUsersDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Deployment/AllUsersDeploymentStepDriver.cs index 85d7aee4016..b38fda1cb83 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Deployment/AllUsersDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Deployment/AllUsersDeploymentStepDriver.cs @@ -9,8 +9,9 @@ public class AllUsersDeploymentStepDriver : DisplayDriver("CustomUserSettingsDeploymentStep_Fields_Edit", async model => - { - model.IncludeAll = step.IncludeAll; - model.SettingsTypeNames = step.SettingsTypeNames; - model.AllSettingsTypeNames = (await _customUserSettingsService.GetAllSettingsTypeNamesAsync()).ToArray(); - }) - .Location("Content"); + return Initialize( + "CustomUserSettingsDeploymentStep_Fields_Edit", + async model => + { + model.IncludeAll = step.IncludeAll; + model.SettingsTypeNames = step.SettingsTypeNames; + model.AllSettingsTypeNames = (await _customUserSettingsService.GetAllSettingsTypeNamesAsync()).ToArray(); + } + ) + .Location("Content"); } public override async Task UpdateAsync(CustomUserSettingsDeploymentStep step, IUpdateModel updater) diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/AuthenticatorAppLoginSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/AuthenticatorAppLoginSettingsDisplayDriver.cs index 124d73790bf..097ec0c1752 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/AuthenticatorAppLoginSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/AuthenticatorAppLoginSettingsDisplayDriver.cs @@ -15,28 +15,33 @@ public class AuthenticatorAppLoginSettingsDisplayDriver : SectionDisplayDriver("AuthenticatorAppLoginSettings_Edit", model => - { - model.UseEmailAsAuthenticatorDisplayName = settings.UseEmailAsAuthenticatorDisplayName; - model.TokenLength = settings.TokenLength; - }).Location("Content:12#Two-Factor Authentication") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) - .OnGroup(LoginSettingsDisplayDriver.GroupId); + return Initialize( + "AuthenticatorAppLoginSettings_Edit", + model => + { + model.UseEmailAsAuthenticatorDisplayName = settings.UseEmailAsAuthenticatorDisplayName; + model.TokenLength = settings.TokenLength; + } + ) + .Location("Content:12#Two-Factor Authentication") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + .OnGroup(LoginSettingsDisplayDriver.GroupId); } public override async Task UpdateAsync(AuthenticatorAppLoginSettings section, BuildEditorContext context) { - if (!context.GroupId.Equals(LoginSettingsDisplayDriver.GroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + if ( + !context.GroupId.Equals(LoginSettingsDisplayDriver.GroupId, StringComparison.OrdinalIgnoreCase) + || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers) + ) { return null; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/ChangeEmailSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/ChangeEmailSettingsDisplayDriver.cs index 43111693731..3221c9a703b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/ChangeEmailSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/ChangeEmailSettingsDisplayDriver.cs @@ -18,13 +18,12 @@ public class ChangeEmailSettingsDisplayDriver : SectionDisplayDriver EditAsync(ChangeEmailSettings settings, BuildEditorContext context) { var user = _httpContextAccessor.HttpContext?.User; @@ -34,10 +33,15 @@ public override async Task EditAsync(ChangeEmailSettings setting return null; } - return Initialize("ChangeEmailSettings_Edit", model => - { - model.AllowChangeEmail = settings.AllowChangeEmail; - }).Location("Content:5").OnGroup(GroupId); + return Initialize( + "ChangeEmailSettings_Edit", + model => + { + model.AllowChangeEmail = settings.AllowChangeEmail; + } + ) + .Location("Content:5") + .OnGroup(GroupId); } public override async Task UpdateAsync(ChangeEmailSettings section, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/CustomUserSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/CustomUserSettingsDisplayDriver.cs index e0a71092b96..4fcb72950a2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/CustomUserSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/CustomUserSettingsDisplayDriver.cs @@ -29,7 +29,8 @@ public CustomUserSettingsDisplayDriver( IContentDefinitionManager contentDefinitionManager, IContentManager contentManager, IAuthorizationService authorizationService, - IHttpContextAccessor httpContextAccessor) + IHttpContextAccessor httpContextAccessor + ) { _contentItemDisplayManager = contentItemDisplayManager; _contentDefinitionManager = contentDefinitionManager; @@ -51,15 +52,20 @@ public override async Task EditAsync(User user, BuildEditorConte foreach (var contentTypeDefinition in contentTypeDefinitions) { - results.Add(Initialize("CustomUserSettings", async model => - { - var isNew = false; - var contentItem = await GetUserSettingsAsync(user, contentTypeDefinition, () => isNew = true); - model.Editor = await _contentItemDisplayManager.BuildEditorAsync(contentItem, context.Updater, isNew, context.GroupId, Prefix); - }) - .Location($"Content:10#{contentTypeDefinition.DisplayName}") - .Differentiator($"CustomUserSettings-{contentTypeDefinition.Name}") - .RenderWhen(() => _authorizationService.AuthorizeAsync(userClaim, CustomUserSettingsPermissions.CreatePermissionForType(contentTypeDefinition)))); + results.Add( + Initialize( + "CustomUserSettings", + async model => + { + var isNew = false; + var contentItem = await GetUserSettingsAsync(user, contentTypeDefinition, () => isNew = true); + model.Editor = await _contentItemDisplayManager.BuildEditorAsync(contentItem, context.Updater, isNew, context.GroupId, Prefix); + } + ) + .Location($"Content:10#{contentTypeDefinition.DisplayName}") + .Differentiator($"CustomUserSettings-{contentTypeDefinition.Name}") + .RenderWhen(() => _authorizationService.AuthorizeAsync(userClaim, CustomUserSettingsPermissions.CreatePermissionForType(contentTypeDefinition))) + ); } return Combine(results); @@ -86,9 +92,8 @@ public override async Task UpdateAsync(User user, UpdateEditorCo return await EditAsync(user, context); } - private async Task> GetContentTypeDefinitionsAsync() - => (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Where(x => x.GetStereotype() == "CustomUserSettings"); + private async Task> GetContentTypeDefinitionsAsync() => + (await _contentDefinitionManager.ListTypeDefinitionsAsync()).Where(x => x.GetStereotype() == "CustomUserSettings"); private async Task GetUserSettingsAsync(User user, ContentTypeDefinition settingsType, Action isNew = null) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/EmailAuthenticatorLoginSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/EmailAuthenticatorLoginSettingsDisplayDriver.cs index 4e7e366b831..484a0faca4b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/EmailAuthenticatorLoginSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/EmailAuthenticatorLoginSettingsDisplayDriver.cs @@ -22,7 +22,8 @@ public class EmailAuthenticatorLoginSettingsDisplayDriver : SectionDisplayDriver public EmailAuthenticatorLoginSettingsDisplayDriver( IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService, - ILiquidTemplateManager liquidTemplateManager) + ILiquidTemplateManager liquidTemplateManager + ) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -31,19 +32,25 @@ public EmailAuthenticatorLoginSettingsDisplayDriver( public override IDisplayResult Edit(EmailAuthenticatorLoginSettings settings) { - return Initialize("EmailAuthenticatorLoginSettings_Edit", model => - { - model.Subject = string.IsNullOrWhiteSpace(settings.Subject) ? EmailAuthenticatorLoginSettings.DefaultSubject : settings.Subject; - model.Body = string.IsNullOrWhiteSpace(settings.Body) ? EmailAuthenticatorLoginSettings.DefaultBody : settings.Body; - }).Location("Content:10#Two-Factor Authentication") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) - .OnGroup(LoginSettingsDisplayDriver.GroupId); + return Initialize( + "EmailAuthenticatorLoginSettings_Edit", + model => + { + model.Subject = string.IsNullOrWhiteSpace(settings.Subject) ? EmailAuthenticatorLoginSettings.DefaultSubject : settings.Subject; + model.Body = string.IsNullOrWhiteSpace(settings.Body) ? EmailAuthenticatorLoginSettings.DefaultBody : settings.Body; + } + ) + .Location("Content:10#Two-Factor Authentication") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + .OnGroup(LoginSettingsDisplayDriver.GroupId); } public override async Task UpdateAsync(EmailAuthenticatorLoginSettings settings, BuildEditorContext context) { - if (!context.GroupId.Equals(LoginSettingsDisplayDriver.GroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + if ( + !context.GroupId.Equals(LoginSettingsDisplayDriver.GroupId, StringComparison.OrdinalIgnoreCase) + || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers) + ) { return null; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/LoginSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/LoginSettingsDisplayDriver.cs index 2be02b5d23a..287d2563f5b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/LoginSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/LoginSettingsDisplayDriver.cs @@ -17,9 +17,7 @@ public class LoginSettingsDisplayDriver : SectionDisplayDriver("LoginSettings_Edit", model => - { - model.UseSiteTheme = settings.UseSiteTheme; - model.UseExternalProviderIfOnlyOneDefined = settings.UseExternalProviderIfOnlyOneDefined; - model.DisableLocalLogin = settings.DisableLocalLogin; - model.UseScriptToSyncRoles = settings.UseScriptToSyncRoles; - model.SyncRolesScript = settings.SyncRolesScript; - model.AllowChangingEmail = settings.AllowChangingEmail; - model.AllowChangingUsername = settings.AllowChangingUsername; - model.AllowChangingPhoneNumber = settings.AllowChangingPhoneNumber; - }).Location("Content:5#General") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, CommonPermissions.ManageUsers)) - .OnGroup(GroupId); + return Initialize( + "LoginSettings_Edit", + model => + { + model.UseSiteTheme = settings.UseSiteTheme; + model.UseExternalProviderIfOnlyOneDefined = settings.UseExternalProviderIfOnlyOneDefined; + model.DisableLocalLogin = settings.DisableLocalLogin; + model.UseScriptToSyncRoles = settings.UseScriptToSyncRoles; + model.SyncRolesScript = settings.SyncRolesScript; + model.AllowChangingEmail = settings.AllowChangingEmail; + model.AllowChangingUsername = settings.AllowChangingUsername; + model.AllowChangingPhoneNumber = settings.AllowChangingPhoneNumber; + } + ) + .Location("Content:5#General") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, CommonPermissions.ManageUsers)) + .OnGroup(GroupId); } public override async Task UpdateAsync(LoginSettings section, BuildEditorContext context) { - if (!context.GroupId.Equals(GroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + if ( + !context.GroupId.Equals(GroupId, StringComparison.OrdinalIgnoreCase) + || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers) + ) { return null; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/RegistrationSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/RegistrationSettingsDisplayDriver.cs index 8ebd6d903fe..ec9c32f889a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/RegistrationSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/RegistrationSettingsDisplayDriver.cs @@ -18,13 +18,12 @@ public class RegistrationSettingsDisplayDriver : SectionDisplayDriver EditAsync(RegistrationSettings settings, BuildEditorContext context) { var user = _httpContextAccessor.HttpContext?.User; @@ -34,18 +33,23 @@ public override async Task EditAsync(RegistrationSettings settin return null; } - return Initialize("RegistrationSettings_Edit", model => - { - model.UsersCanRegister = settings.UsersCanRegister; - model.UsersMustValidateEmail = settings.UsersMustValidateEmail; - model.UsersAreModerated = settings.UsersAreModerated; - model.UseSiteTheme = settings.UseSiteTheme; - model.NoPasswordForExternalUsers = settings.NoPasswordForExternalUsers; - model.NoUsernameForExternalUsers = settings.NoUsernameForExternalUsers; - model.NoEmailForExternalUsers = settings.NoEmailForExternalUsers; - model.UseScriptToGenerateUsername = settings.UseScriptToGenerateUsername; - model.GenerateUsernameScript = settings.GenerateUsernameScript; - }).Location("Content:5").OnGroup(GroupId); + return Initialize( + "RegistrationSettings_Edit", + model => + { + model.UsersCanRegister = settings.UsersCanRegister; + model.UsersMustValidateEmail = settings.UsersMustValidateEmail; + model.UsersAreModerated = settings.UsersAreModerated; + model.UseSiteTheme = settings.UseSiteTheme; + model.NoPasswordForExternalUsers = settings.NoPasswordForExternalUsers; + model.NoUsernameForExternalUsers = settings.NoUsernameForExternalUsers; + model.NoEmailForExternalUsers = settings.NoEmailForExternalUsers; + model.UseScriptToGenerateUsername = settings.UseScriptToGenerateUsername; + model.GenerateUsernameScript = settings.GenerateUsernameScript; + } + ) + .Location("Content:5") + .OnGroup(GroupId); } public override async Task UpdateAsync(RegistrationSettings section, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/ResetPasswordSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/ResetPasswordSettingsDisplayDriver.cs index 805e3695f68..86d90cc6743 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/ResetPasswordSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/ResetPasswordSettingsDisplayDriver.cs @@ -18,9 +18,7 @@ public class ResetPasswordSettingsDisplayDriver : SectionDisplayDriver EditAsync(ResetPasswordSettings setti return null; } - return Initialize("ResetPasswordSettings_Edit", model => - { - model.AllowResetPassword = settings.AllowResetPassword; - model.UseSiteTheme = settings.UseSiteTheme; - }).Location("Content:5").OnGroup(GroupId); + return Initialize( + "ResetPasswordSettings_Edit", + model => + { + model.AllowResetPassword = settings.AllowResetPassword; + model.UseSiteTheme = settings.UseSiteTheme; + } + ) + .Location("Content:5") + .OnGroup(GroupId); } public override async Task UpdateAsync(ResetPasswordSettings section, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/RoleLoginSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/RoleLoginSettingsDisplayDriver.cs index 24cc8b2ff7f..838ccbd4525 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/RoleLoginSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/RoleLoginSettingsDisplayDriver.cs @@ -27,7 +27,8 @@ public RoleLoginSettingsDisplayDriver( IHttpContextAccessor httpContextAccessor, IAuthorizationService authorizationService, IRoleService roleService, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -37,25 +38,33 @@ public RoleLoginSettingsDisplayDriver( public override IDisplayResult Edit(RoleLoginSettings settings) { - return Initialize("LoginSettingsRoles_Edit", async model => - { - model.RequireTwoFactorAuthenticationForSpecificRoles = settings.RequireTwoFactorAuthenticationForSpecificRoles; - var roles = await _roleService.GetRolesAsync(); - model.Roles = roles.Select(role => new RoleEntry() - { - Role = role.RoleName, - IsSelected = settings.Roles != null && settings.Roles.Contains(role.RoleName, StringComparer.OrdinalIgnoreCase), - }).OrderBy(entry => entry.Role) - .ToArray(); - }).Location("Content:6#Two-Factor Authentication") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) - .OnGroup(LoginSettingsDisplayDriver.GroupId); + return Initialize( + "LoginSettingsRoles_Edit", + async model => + { + model.RequireTwoFactorAuthenticationForSpecificRoles = settings.RequireTwoFactorAuthenticationForSpecificRoles; + var roles = await _roleService.GetRolesAsync(); + model.Roles = roles + .Select(role => new RoleEntry() + { + Role = role.RoleName, + IsSelected = settings.Roles != null && settings.Roles.Contains(role.RoleName, StringComparer.OrdinalIgnoreCase), + }) + .OrderBy(entry => entry.Role) + .ToArray(); + } + ) + .Location("Content:6#Two-Factor Authentication") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + .OnGroup(LoginSettingsDisplayDriver.GroupId); } public override async Task UpdateAsync(RoleLoginSettings settings, BuildEditorContext context) { - if (!context.GroupId.Equals(LoginSettingsDisplayDriver.GroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + if ( + !context.GroupId.Equals(LoginSettingsDisplayDriver.GroupId, StringComparison.OrdinalIgnoreCase) + || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers) + ) { return null; } @@ -68,9 +77,7 @@ public override async Task UpdateAsync(RoleLoginSettings setting { var roles = await _roleService.GetRolesAsync(); - var selectedRoles = model.Roles.Where(x => x.IsSelected) - .Join(roles, e => e.Role, r => r.RoleName, (e, r) => r.RoleName) - .ToArray(); + var selectedRoles = model.Roles.Where(x => x.IsSelected).Join(roles, e => e.Role, r => r.RoleName, (e, r) => r.RoleName).ToArray(); if (selectedRoles.Length == 0) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/SmsAuthenticatorLoginSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/SmsAuthenticatorLoginSettingsDisplayDriver.cs index e614b2acf23..91a6d20a8c4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/SmsAuthenticatorLoginSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/SmsAuthenticatorLoginSettingsDisplayDriver.cs @@ -22,7 +22,8 @@ public class SmsAuthenticatorLoginSettingsDisplayDriver : SectionDisplayDriver("SmsAuthenticatorLoginSettings_Edit", model => - { - model.Body = string.IsNullOrWhiteSpace(settings.Body) - ? EmailAuthenticatorLoginSettings.DefaultBody - : settings.Body; - }).Location("Content:15#Two-Factor Authentication") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) - .OnGroup(LoginSettingsDisplayDriver.GroupId); + return Initialize( + "SmsAuthenticatorLoginSettings_Edit", + model => + { + model.Body = string.IsNullOrWhiteSpace(settings.Body) ? EmailAuthenticatorLoginSettings.DefaultBody : settings.Body; + } + ) + .Location("Content:15#Two-Factor Authentication") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + .OnGroup(LoginSettingsDisplayDriver.GroupId); } public override async Task UpdateAsync(SmsAuthenticatorLoginSettings settings, BuildEditorContext context) { - if (!context.GroupId.Equals(LoginSettingsDisplayDriver.GroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + if ( + !context.GroupId.Equals(LoginSettingsDisplayDriver.GroupId, StringComparison.OrdinalIgnoreCase) + || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers) + ) { return null; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorLoginSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorLoginSettingsDisplayDriver.cs index 27f53a1d4e4..0c06be8667b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorLoginSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorLoginSettingsDisplayDriver.cs @@ -21,7 +21,8 @@ public class TwoFactorLoginSettingsDisplayDriver : SectionDisplayDriver stringLocalizer) + IStringLocalizer stringLocalizer + ) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -30,20 +31,26 @@ public TwoFactorLoginSettingsDisplayDriver( public override IDisplayResult Edit(TwoFactorLoginSettings settings) { - return Initialize("TwoFactorLoginSettings_Edit", model => - { - model.NumberOfRecoveryCodesToGenerate = settings.NumberOfRecoveryCodesToGenerate; - model.RequireTwoFactorAuthentication = settings.RequireTwoFactorAuthentication; - model.AllowRememberClientTwoFactorAuthentication = settings.AllowRememberClientTwoFactorAuthentication; - }).Location("Content:5#Two-Factor Authentication") - .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) - .OnGroup(LoginSettingsDisplayDriver.GroupId); + return Initialize( + "TwoFactorLoginSettings_Edit", + model => + { + model.NumberOfRecoveryCodesToGenerate = settings.NumberOfRecoveryCodesToGenerate; + model.RequireTwoFactorAuthentication = settings.RequireTwoFactorAuthentication; + model.AllowRememberClientTwoFactorAuthentication = settings.AllowRememberClientTwoFactorAuthentication; + } + ) + .Location("Content:5#Two-Factor Authentication") + .RenderWhen(() => _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + .OnGroup(LoginSettingsDisplayDriver.GroupId); } public override async Task UpdateAsync(TwoFactorLoginSettings section, BuildEditorContext context) { - if (!context.GroupId.Equals(LoginSettingsDisplayDriver.GroupId, StringComparison.OrdinalIgnoreCase) - || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers)) + if ( + !context.GroupId.Equals(LoginSettingsDisplayDriver.GroupId, StringComparison.OrdinalIgnoreCase) + || !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, CommonPermissions.ManageUsers) + ) { return null; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodDisplayDriver.cs index 41b727a11d5..8a11fcd4376 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodDisplayDriver.cs @@ -14,23 +14,35 @@ public override Task DisplayAsync(TwoFactorMethod model, BuildDi return Task.FromResult(null); } - var icon = Initialize($"TwoFactorMethod_{model.Provider}_Icon", vm => - { - vm.Provider = model.Provider; - vm.IsEnabled = model.IsEnabled; - }).Location("SummaryAdmin", "Icon"); + var icon = Initialize( + $"TwoFactorMethod_{model.Provider}_Icon", + vm => + { + vm.Provider = model.Provider; + vm.IsEnabled = model.IsEnabled; + } + ) + .Location("SummaryAdmin", "Icon"); - var content = Initialize($"TwoFactorMethod_{model.Provider}_Content", vm => - { - vm.Provider = model.Provider; - vm.IsEnabled = model.IsEnabled; - }).Location("SummaryAdmin", "Content"); + var content = Initialize( + $"TwoFactorMethod_{model.Provider}_Content", + vm => + { + vm.Provider = model.Provider; + vm.IsEnabled = model.IsEnabled; + } + ) + .Location("SummaryAdmin", "Content"); - var actions = Initialize($"TwoFactorMethod_{model.Provider}_Actions", vm => - { - vm.Provider = model.Provider; - vm.IsEnabled = model.IsEnabled; - }).Location("SummaryAdmin", "Actions"); + var actions = Initialize( + $"TwoFactorMethod_{model.Provider}_Actions", + vm => + { + vm.Provider = model.Provider; + vm.IsEnabled = model.IsEnabled; + } + ) + .Location("SummaryAdmin", "Actions"); return Task.FromResult(Combine(icon, content, actions)); } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodLoginAuthenticationAppDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodLoginAuthenticationAppDisplayDriver.cs index ece8681ab8f..2b4b34712d3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodLoginAuthenticationAppDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodLoginAuthenticationAppDisplayDriver.cs @@ -9,8 +9,6 @@ public class TwoFactorMethodLoginAuthenticationAppDisplayDriver : DisplayDriver< { public override IDisplayResult Edit(TwoFactorMethod model) { - return View("AuthenticatorAppValidation", model) - .Location("Content") - .OnGroup(TokenOptions.DefaultAuthenticatorProvider); + return View("AuthenticatorAppValidation", model).Location("Content").OnGroup(TokenOptions.DefaultAuthenticatorProvider); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodLoginEmailDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodLoginEmailDisplayDriver.cs index bcc377d1c28..99aeeba1e3a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodLoginEmailDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/TwoFactorMethodLoginEmailDisplayDriver.cs @@ -9,8 +9,6 @@ public class TwoFactorMethodLoginEmailDisplayDriver : DisplayDriver { public override IDisplayResult Display(UserMenu model) { - return View("UserMenuItems__TwoFactor", model) - .Location("Detail", "Content:15") - .Location("DetailAdmin", "Content:15") - .Differentiator("TwoFactor"); + return View("UserMenuItems__TwoFactor", model).Location("Detail", "Content:15").Location("DetailAdmin", "Content:15").Differentiator("TwoFactor"); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserDisplayDriver.cs index 7180290b2a4..d05caaa5a1c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserDisplayDriver.cs @@ -39,7 +39,8 @@ public UserDisplayDriver( IEnumerable userEventHandlers, IAuthorizationService authorizationService, IHtmlLocalizer htmlLocalizer, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _userManager = userManager; _httpContextAccessor = httpContextAccessor; @@ -67,15 +68,18 @@ public override async Task EditAsync(User user, BuildEditorConte return null; } - return Initialize("UserFields_Edit", model => - { - model.EmailConfirmed = user.EmailConfirmed; - model.IsEnabled = user.IsEnabled; - model.IsNewRequest = context.IsNew; - // The current user cannot disable themselves, nor can a user without permission to manage this user disable them. - model.IsEditingDisabled = IsCurrentUser(user); - }) - .Location("Content:1.5"); + return Initialize( + "UserFields_Edit", + model => + { + model.EmailConfirmed = user.EmailConfirmed; + model.IsEnabled = user.IsEnabled; + model.IsNewRequest = context.IsNew; + // The current user cannot disable themselves, nor can a user without permission to manage this user disable them. + model.IsEditingDisabled = IsCurrentUser(user); + } + ) + .Location("Content:1.5"); } public override async Task UpdateAsync(User user, UpdateEditorContext context) @@ -113,10 +117,7 @@ public override async Task UpdateAsync(User user, UpdateEditorCo if (!isEditingDisabled && !model.IsEnabled && user.IsEnabled) { - var enabledUsersOfAdminRole = (await _userManager.GetUsersInRoleAsync(AdministratorRole)) - .Cast() - .Where(user => user.IsEnabled) - .ToList(); + var enabledUsersOfAdminRole = (await _userManager.GetUsersInRoleAsync(AdministratorRole)).Cast().Where(user => user.IsEnabled).ToList(); if (enabledUsersOfAdminRole.Count == 1 && user.UserId == enabledUsersOfAdminRole.First().UserId) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserInformationDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserInformationDisplayDriver.cs index 5046d74887b..4f280af09ce 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserInformationDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserInformationDisplayDriver.cs @@ -26,7 +26,8 @@ public UserInformationDisplayDriver( IAuthorizationService authorizationService, IPhoneFormatValidator phoneFormatValidator, IStringLocalizer stringLocalizer, - ISiteService siteService) + ISiteService siteService + ) { _httpContextAccessor = httpContextAccessor; _authorizationService = authorizationService; @@ -46,30 +47,37 @@ public override async Task EditAsync(User user, BuildEditorConte var settings = site.As(); var canEditUserInfo = await CanEditUserInfoAsync(user); return Combine( - Initialize("UserName_Edit", model => - { - model.UserName = user.UserName; - - model.AllowEditing = context.IsNew || (settings.AllowChangingUsername && canEditUserInfo); - - }).Location("Content:1"), - - Initialize("UserEmail_Edit", model => - { - model.Email = user.Email; - - model.AllowEditing = context.IsNew || (settings.AllowChangingEmail && canEditUserInfo); - - }).Location("Content:1.3"), + Initialize( + "UserName_Edit", + model => + { + model.UserName = user.UserName; - Initialize("UserPhoneNumber_Edit", model => - { - model.PhoneNumber = user.PhoneNumber; - model.PhoneNumberConfirmed = user.PhoneNumberConfirmed; + model.AllowEditing = context.IsNew || (settings.AllowChangingUsername && canEditUserInfo); + } + ) + .Location("Content:1"), + Initialize( + "UserEmail_Edit", + model => + { + model.Email = user.Email; - model.AllowEditing = context.IsNew || (settings.AllowChangingPhoneNumber && canEditUserInfo); + model.AllowEditing = context.IsNew || (settings.AllowChangingEmail && canEditUserInfo); + } + ) + .Location("Content:1.3"), + Initialize( + "UserPhoneNumber_Edit", + model => + { + model.PhoneNumber = user.PhoneNumber; + model.PhoneNumberConfirmed = user.PhoneNumberConfirmed; - }).Location("Content:1.3") + model.AllowEditing = context.IsNew || (settings.AllowChangingPhoneNumber && canEditUserInfo); + } + ) + .Location("Content:1.3") ); } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserMenuDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserMenuDisplayDriver.cs index 764920a2581..3d7d809d1e2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserMenuDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserMenuDisplayDriver.cs @@ -13,9 +13,7 @@ public class UserMenuDisplayDriver : DisplayDriver private readonly SignInManager _signInManager; private readonly IHttpContextAccessor _httpContextAccessor; - public UserMenuDisplayDriver( - SignInManager signInManager, - IHttpContextAccessor httpContextAccessor) + public UserMenuDisplayDriver(SignInManager signInManager, IHttpContextAccessor httpContextAccessor) { _signInManager = signInManager; _httpContextAccessor = httpContextAccessor; @@ -25,37 +23,20 @@ public override IDisplayResult Display(UserMenu model) { var results = new List { - View("UserMenuItems__Title", model) - .Location("Detail", "Header:5") - .Location("DetailAdmin", "Header:5") - .Differentiator("Title"), - - View("UserMenuItems__SignedUser", model) - .Location("DetailAdmin", "Content:1") - .Differentiator("SignedUser"), - - View("UserMenuItems__Profile", model) - .Location("Detail", "Content:5") - .Location("DetailAdmin", "Content:5") - .Differentiator("Profile"), - + View("UserMenuItems__Title", model).Location("Detail", "Header:5").Location("DetailAdmin", "Header:5").Differentiator("Title"), + View("UserMenuItems__SignedUser", model).Location("DetailAdmin", "Content:1").Differentiator("SignedUser"), + View("UserMenuItems__Profile", model).Location("Detail", "Content:5").Location("DetailAdmin", "Content:5").Differentiator("Profile"), View("UserMenuItems__ExternalLogins", model) - .RenderWhen(async () => (await _signInManager.GetExternalAuthenticationSchemesAsync()).Any()) - .Location("Detail", "Content:10") - .Location("DetailAdmin", "Content:10") - .Differentiator("ExternalLogins"), - - View("UserMenuItems__SignOut", model) - .Location("Detail", "Content:100") - .Location("DetailAdmin", "Content:100") - .Differentiator("SignOut"), + .RenderWhen(async () => (await _signInManager.GetExternalAuthenticationSchemesAsync()).Any()) + .Location("Detail", "Content:10") + .Location("DetailAdmin", "Content:10") + .Differentiator("ExternalLogins"), + View("UserMenuItems__SignOut", model).Location("Detail", "Content:100").Location("DetailAdmin", "Content:100").Differentiator("SignOut"), }; if (_httpContextAccessor.HttpContext.User.HasClaim("Permission", "AccessAdminPanel")) { - results.Add(View("UserMenuItems__Dashboard", model) - .Location("Detail", "Content:1.1") - .Differentiator("Dashboard")); + results.Add(View("UserMenuItems__Dashboard", model).Location("Detail", "Content:1.1").Differentiator("Dashboard")); } return Combine(results); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserMenuNavbarDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserMenuNavbarDisplayDriver.cs index c93a7bcd6ba..9d10a992356 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserMenuNavbarDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserMenuNavbarDisplayDriver.cs @@ -8,8 +8,6 @@ public class UserMenuNavbarDisplayDriver : DisplayDriver { public override IDisplayResult Display(Navbar model) { - return View("NavbarUserMenu", model) - .Location("Detail", "Content:after") - .Location("DetailAdmin", "Content:after"); + return View("NavbarUserMenu", model).Location("Detail", "Content:after").Location("DetailAdmin", "Content:after"); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserRoleDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserRoleDisplayDriver.cs index 982c5036701..e71ec2cd061 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserRoleDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Drivers/UserRoleDisplayDriver.cs @@ -36,7 +36,8 @@ public UserRoleDisplayDriver( IHttpContextAccessor httpContextAccessor, INotifier notifier, IAuthorizationService authorizationService, - IHtmlLocalizer htmlLocalizer) + IHtmlLocalizer htmlLocalizer + ) { _userManager = userManager; _roleService = roleService; @@ -50,55 +51,55 @@ public UserRoleDisplayDriver( public override IDisplayResult Display(User user) { return Combine( - Initialize("UserRolesMeta", model => model.User = user) - .Location("SummaryAdmin", "Description"), - - Initialize("UserRoles", model => model.User = user) - .Location("DetailAdmin", "Content:10") + Initialize("UserRolesMeta", model => model.User = user).Location("SummaryAdmin", "Description"), + Initialize("UserRoles", model => model.User = user).Location("DetailAdmin", "Content:10") ); } public override IDisplayResult Edit(User user) { // This view is always rendered, however there will be no editable roles if the user does not have permission to edit them. - return Initialize("UserRoleFields_Edit", async model => - { - // The current user can only view their roles if they have assign role, to prevent listing roles when managing their own profile. - if (_httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) == user.UserId - && !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, CommonPermissions.AssignRoleToUsers)) - { - return; - } + return Initialize( + "UserRoleFields_Edit", + async model => + { + // The current user can only view their roles if they have assign role, to prevent listing roles when managing their own profile. + if ( + _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) == user.UserId + && !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, CommonPermissions.AssignRoleToUsers) + ) + { + return; + } - var roles = await GetRoleAsync(); + var roles = await GetRoleAsync(); - // When a user is in a role that the current user cannot manage the role is shown but selection is disabled. - var authorizedRoleNames = await GetAccessibleRoleNamesAsync(roles); - var userRoleNames = await _userRoleStore.GetRolesAsync(user, default); + // When a user is in a role that the current user cannot manage the role is shown but selection is disabled. + var authorizedRoleNames = await GetAccessibleRoleNamesAsync(roles); + var userRoleNames = await _userRoleStore.GetRolesAsync(user, default); - var roleEntries = new List(); - foreach (var roleName in authorizedRoleNames) - { - var roleEntry = new RoleEntry - { - Role = roleName, - IsSelected = userRoleNames.Contains(roleName, StringComparer.OrdinalIgnoreCase), - }; + var roleEntries = new List(); + foreach (var roleName in authorizedRoleNames) + { + var roleEntry = new RoleEntry { Role = roleName, IsSelected = userRoleNames.Contains(roleName, StringComparer.OrdinalIgnoreCase), }; - roleEntries.Add(roleEntry); - } + roleEntries.Add(roleEntry); + } - model.Roles = roleEntries.ToArray(); - }) - .Location("Content:1.10") - .RenderWhen(async () => await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, CommonPermissions.EditUsers, user)); + model.Roles = roleEntries.ToArray(); + } + ) + .Location("Content:1.10") + .RenderWhen(async () => await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, CommonPermissions.EditUsers, user)); } public override async Task UpdateAsync(User user, UpdateEditorContext context) { // The current user cannot alter their own roles. This prevents them removing access to the site for themselves. - if (_httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) == user.UserId - && !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, StandardPermissions.SiteOwner)) + if ( + _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) == user.UserId + && !await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, StandardPermissions.SiteOwner) + ) { return null; } @@ -131,8 +132,9 @@ public override async Task UpdateAsync(User user, UpdateEditorCo foreach (var role in currentUserRoleNames) { // When the user has permission to manage the role and it is no longer selected the role can be removed. - if (accessibleRoleNames.Contains(role, StringComparer.OrdinalIgnoreCase) - && !accessibleAndSelectedRoleNames.Contains(role, StringComparer.OrdinalIgnoreCase)) + if ( + accessibleRoleNames.Contains(role, StringComparer.OrdinalIgnoreCase) && !accessibleAndSelectedRoleNames.Contains(role, StringComparer.OrdinalIgnoreCase) + ) { rolesToRemove.Add(role); } @@ -142,10 +144,7 @@ public override async Task UpdateAsync(User user, UpdateEditorCo { if (string.Equals(role, AdministratorRole, StringComparison.OrdinalIgnoreCase)) { - var enabledUsersOfAdminRole = (await _userManager.GetUsersInRoleAsync(AdministratorRole)) - .Cast() - .Where(user => user.IsEnabled) - .ToList(); + var enabledUsersOfAdminRole = (await _userManager.GetUsersInRoleAsync(AdministratorRole)).Cast().Where(user => user.IsEnabled).ToList(); // Make sure we always have at least one enabled administrator account. if (enabledUsersOfAdminRole.Count == 1 && user.UserId == enabledUsersOfAdminRole.First().UserId) diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Filters/TwoFactorAuthenticationAuthorizationFilter.cs b/src/OrchardCore.Modules/OrchardCore.Users/Filters/TwoFactorAuthenticationAuthorizationFilter.cs index 89c447af2fe..b2c0dcb8fe4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Filters/TwoFactorAuthenticationAuthorizationFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Filters/TwoFactorAuthenticationAuthorizationFilter.cs @@ -21,7 +21,8 @@ public class TwoFactorAuthenticationAuthorizationFilter : IAsyncAuthorizationFil public TwoFactorAuthenticationAuthorizationFilter( IOptions userOptions, IOptions adminOptions, - ITwoFactorAuthenticationHandlerCoordinator twoFactorHandlerCoordinator) + ITwoFactorAuthenticationHandlerCoordinator twoFactorHandlerCoordinator + ) { _userOptions = userOptions.Value; _twoFactorHandlerCoordinator = twoFactorHandlerCoordinator; @@ -32,12 +33,13 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { ArgumentNullException.ThrowIfNull(context); - if (!(context.HttpContext?.User?.Identity?.IsAuthenticated ?? false) + if ( + !(context.HttpContext?.User?.Identity?.IsAuthenticated ?? false) || context.HttpContext.Request.Path.Equals("/" + _userOptions.LogoffPath, StringComparison.OrdinalIgnoreCase) || context.HttpContext.Request.Path.Equals("/" + _userOptions.TwoFactorAuthenticationPath, StringComparison.OrdinalIgnoreCase) || context.HttpContext.Request.Path.StartsWithSegments("/" + _adminOptions.AdminUrlPrefix + "/Authenticator/Configure", StringComparison.OrdinalIgnoreCase) || context.HttpContext.Request.Path.Equals("/" + _adminOptions.AdminUrlPrefix + "/ShowRecoveryCodes", StringComparison.OrdinalIgnoreCase) - ) + ) { return; } @@ -49,8 +51,7 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext context) return; } - if (await _twoFactorHandlerCoordinator.IsRequiredAsync() - && context.HttpContext.User.HasClaim(claim => claim.Type == UserConstants.TwoFactorAuthenticationClaimType)) + if (await _twoFactorHandlerCoordinator.IsRequiredAsync() && context.HttpContext.User.HasClaim(claim => claim.Type == UserConstants.TwoFactorAuthenticationClaimType)) { context.Result = new RedirectResult("~/" + _userOptions.TwoFactorAuthenticationPath); } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/GraphQL/CurrentUserQuery.cs b/src/OrchardCore.Modules/OrchardCore.Users/GraphQL/CurrentUserQuery.cs index 2852fed8f0e..b0d388cfdb9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/GraphQL/CurrentUserQuery.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/GraphQL/CurrentUserQuery.cs @@ -24,10 +24,7 @@ internal class CurrentUserQuery : ISchemaBuilder private readonly IOptions _contentOptionsAccessor; protected readonly IStringLocalizer S; - public CurrentUserQuery( - IHttpContextAccessor httpContextAccessor, - IOptions contentOptionsAccessor, - IStringLocalizer localizer) + public CurrentUserQuery(IHttpContextAccessor httpContextAccessor, IOptions contentOptionsAccessor, IStringLocalizer localizer) { _httpContextAccessor = httpContextAccessor; _contentOptionsAccessor = contentOptionsAccessor; diff --git a/src/OrchardCore.Modules/OrchardCore.Users/GraphQL/UserType.cs b/src/OrchardCore.Modules/OrchardCore.Users/GraphQL/UserType.cs index f5d1818a94a..e052c500d4a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/GraphQL/UserType.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/GraphQL/UserType.cs @@ -30,7 +30,7 @@ public UserType(IStringLocalizer localizer) internal void AddField(ISchema schema, ContentTypeDefinition typeDefinition) { var contentItemType = schema.AdditionalTypeInstances.SingleOrDefault(t => t.Name == typeDefinition.Name); - + if (contentItemType == null) { // This error would indicate that this graph type is build too early. @@ -39,10 +39,10 @@ internal void AddField(ISchema schema, ContentTypeDefinition typeDefinition) var field = Field(typeDefinition.Name, contentItemType.GetType()) .Description(S["Custom user settings of {0}.", typeDefinition.DisplayName]) - .ResolveAsync(static async context => { + .ResolveAsync(static async context => + { // We don't want to create an empty content item if it does not exist. - if (context.Source is User user && - user.Properties.ContainsKey(context.FieldDefinition.ResolvedType.Name)) + if (context.Source is User user && user.Properties.ContainsKey(context.FieldDefinition.ResolvedType.Name)) { var customUserSettingsService = context.RequestServices!.GetRequiredService(); var settingsType = await customUserSettingsService.GetSettingsTypeAsync(context.FieldDefinition.ResolvedType.Name); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Handlers/ScriptExternalLoginEventHandler.cs b/src/OrchardCore.Modules/OrchardCore.Users/Handlers/ScriptExternalLoginEventHandler.cs index 14a3cdf45f2..b1920199e86 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Handlers/ScriptExternalLoginEventHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Handlers/ScriptExternalLoginEventHandler.cs @@ -15,11 +15,7 @@ public class ScriptExternalLoginEventHandler : IExternalLoginEventHandler private readonly IScriptingManager _scriptingManager; private readonly ISiteService _siteService; - public ScriptExternalLoginEventHandler( - ISiteService siteService, - IScriptingManager scriptingManager, - ILogger logger - ) + public ScriptExternalLoginEventHandler(ISiteService siteService, IScriptingManager scriptingManager, ILogger logger) { _siteService = siteService; _scriptingManager = scriptingManager; @@ -32,9 +28,15 @@ public async Task GenerateUserName(string provider, IEnumerable(); if (loginSettings.UseScriptToSyncRoles) { - var script = $"js: function syncRoles(context) {{\n{loginSettings.SyncRolesScript}\n}}\nvar context={JConvert.SerializeObject(context, JOptions.CamelCase)};\nsyncRoles(context);\nreturn context;"; + var script = + $"js: function syncRoles(context) {{\n{loginSettings.SyncRolesScript}\n}}\nvar context={JConvert.SerializeObject(context, JOptions.CamelCase)};\nsyncRoles(context);\nreturn context;"; dynamic evaluationResult = _scriptingManager.Evaluate(script, null, null, null); context.RolesToAdd.AddRange((evaluationResult.rolesToAdd as object[]).Select(i => i.ToString())); context.RolesToRemove.AddRange((evaluationResult.rolesToRemove as object[]).Select(i => i.ToString())); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Liquid/HasPermissionFilter.cs b/src/OrchardCore.Modules/OrchardCore.Users/Liquid/HasPermissionFilter.cs index 7f22f0f001a..e42d7c54a9f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Liquid/HasPermissionFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Liquid/HasPermissionFilter.cs @@ -29,8 +29,7 @@ public async ValueTask ProcessAsync(FluidValue input, FilterArgument var permissionName = arguments["permission"].Or(arguments.At(0)).ToStringValue(); var resource = arguments["resource"].Or(arguments.At(1)).ToObjectValue(); - if (!string.IsNullOrEmpty(permissionName) && - await _authorizationService.AuthorizeAsync(user, new Permission(permissionName), resource)) + if (!string.IsNullOrEmpty(permissionName) && await _authorizationService.AuthorizeAsync(user, new Permission(permissionName), resource)) { return BooleanValue.True; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Liquid/LiquidUserAccessor.cs b/src/OrchardCore.Modules/OrchardCore.Users/Liquid/LiquidUserAccessor.cs index abb09ca36f9..73152eab2a8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Liquid/LiquidUserAccessor.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Liquid/LiquidUserAccessor.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Liquid /// /// This is a placeholder class that allows modules to extend the `User` property in the current Liquid scope. /// - public class LiquidUserAccessor - { - } + public class LiquidUserAccessor { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Localization/Drivers/UserLocalizationDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Localization/Drivers/UserLocalizationDisplayDriver.cs index 3f849bdf7cc..e72b0995188 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Localization/Drivers/UserLocalizationDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Localization/Drivers/UserLocalizationDisplayDriver.cs @@ -19,9 +19,7 @@ public class UserLocalizationDisplayDriver : SectionDisplayDriver localizer) + public UserLocalizationDisplayDriver(ILocalizationService localizationService, IStringLocalizer localizer) { _localizationService = localizationService; S = localizer; @@ -29,29 +27,32 @@ public UserLocalizationDisplayDriver( public override Task EditAsync(UserLocalizationSettings section, BuildEditorContext context) { - return Task.FromResult(Initialize("UserCulture_Edit", async model => - { - var supportedCultures = await _localizationService.GetSupportedCulturesAsync(); + return Task.FromResult( + Initialize( + "UserCulture_Edit", + async model => + { + var supportedCultures = await _localizationService.GetSupportedCulturesAsync(); - var cultureList = supportedCultures.Select(culture => - new SelectListItem - { - Text = CultureInfo.GetCultureInfo(culture).DisplayName + " (" + culture + ")", - Value = culture - }).ToList(); + var cultureList = supportedCultures + .Select(culture => new SelectListItem { Text = CultureInfo.GetCultureInfo(culture).DisplayName + " (" + culture + ")", Value = culture }) + .ToList(); - cultureList.Insert(0, new SelectListItem() { Text = S["Use site's culture"], Value = "none" }); + cultureList.Insert(0, new SelectListItem() { Text = S["Use site's culture"], Value = "none" }); - // If Invariant Culture is installed as a supported culture we bind it to a different culture code than String.Empty. - var emptyCulture = cultureList.FirstOrDefault(c => c.Value == ""); - if (emptyCulture != null) - { - emptyCulture.Value = UserLocalizationConstants.Invariant; - } + // If Invariant Culture is installed as a supported culture we bind it to a different culture code than String.Empty. + var emptyCulture = cultureList.FirstOrDefault(c => c.Value == ""); + if (emptyCulture != null) + { + emptyCulture.Value = UserLocalizationConstants.Invariant; + } - model.SelectedCulture = section.Culture; - model.CultureList = cultureList; - }).Location("Content:2")); + model.SelectedCulture = section.Culture; + model.CultureList = cultureList; + } + ) + .Location("Content:2") + ); } public override async Task UpdateAsync(User model, UserLocalizationSettings section, IUpdateModel updater, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Localization/Extensions/ClaimsPrincipleExtensions.cs b/src/OrchardCore.Modules/OrchardCore.Users/Localization/Extensions/ClaimsPrincipleExtensions.cs index 0282cf17e44..2b9b1101593 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Localization/Extensions/ClaimsPrincipleExtensions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Localization/Extensions/ClaimsPrincipleExtensions.cs @@ -4,6 +4,5 @@ namespace System.Security.Claims; public static class ClaimsPrincipleExtensions { - public static string GetCulture(this ClaimsPrincipal principal) - => principal.FindFirstValue(UserLocalizationClaimsProvider.CultureClaimType); + public static string GetCulture(this ClaimsPrincipal principal) => principal.FindFirstValue(UserLocalizationClaimsProvider.CultureClaimType); } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Localization/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Users/Localization/Startup.cs index c04a2a09d0d..4853f1a651c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Localization/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Localization/Startup.cs @@ -17,7 +17,6 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped, UserLocalizationDisplayDriver>(); services.AddScoped(); - services.Configure(options => - options.AddInitialRequestCultureProvider(new UserLocalizationRequestCultureProvider())); + services.Configure(options => options.AddInitialRequestCultureProvider(new UserLocalizationRequestCultureProvider())); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Users/Manifest.cs index 331b37e6455..f66d899bb39 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Manifest.cs @@ -1,12 +1,7 @@ using OrchardCore.Modules.Manifest; using OrchardCore.Users; -[assembly: Module( - Name = "Users", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Users", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = UserConstants.Features.Users, @@ -28,11 +23,7 @@ Id = "OrchardCore.Users.Registration", Name = "Users Registration", Description = "The registration feature allows external users to sign up to the site and ask to confirm their email.", - Dependencies = - [ - UserConstants.Features.Users, - "OrchardCore.Email", - ], + Dependencies = [UserConstants.Features.Users, "OrchardCore.Email",], Category = "Security" )] @@ -40,11 +31,7 @@ Id = "OrchardCore.Users.ResetPassword", Name = "Users Reset Password", Description = "The reset password feature allows users to reset their password.", - Dependencies = - [ - UserConstants.Features.Users, - "OrchardCore.Email", - ], + Dependencies = [UserConstants.Features.Users, "OrchardCore.Email",], Category = "Security" )] @@ -69,11 +56,7 @@ Id = "OrchardCore.Users.CustomUserSettings", Name = "Custom User Settings", Description = "The custom user settings feature allows content types to become custom user settings.", - Dependencies = - [ - UserConstants.Features.Users, - "OrchardCore.Contents", - ], + Dependencies = [UserConstants.Features.Users, "OrchardCore.Contents",], Category = "Settings" )] @@ -81,11 +64,7 @@ Id = "OrchardCore.Users.AuditTrail", Name = "Users Audit Trail", Description = "The users audit trail feature allows logging of user events.", - Dependencies = - [ - UserConstants.Features.Users, - "OrchardCore.AuditTrail", - ], + Dependencies = [UserConstants.Features.Users, "OrchardCore.AuditTrail",], Category = "Security" )] @@ -110,11 +89,7 @@ Id = UserConstants.Features.AuthenticatorApp, Name = "Two-Factor Authenticator App Method", Description = "Provides users a two-factor authentication method through any Authentication App.", - Dependencies = - [ - UserConstants.Features.Users, - UserConstants.Features.TwoFactorAuthentication, - ], + Dependencies = [UserConstants.Features.Users, UserConstants.Features.TwoFactorAuthentication,], Category = "Security" )] @@ -122,13 +97,7 @@ Id = UserConstants.Features.EmailAuthenticator, Name = "Two-Factor Email Method", Description = "Provides users a two-factor authentication method through an Email service.", - Dependencies = - [ - UserConstants.Features.Users, - UserConstants.Features.TwoFactorAuthentication, - "OrchardCore.Liquid", - "OrchardCore.Email", - ], + Dependencies = [UserConstants.Features.Users, UserConstants.Features.TwoFactorAuthentication, "OrchardCore.Liquid", "OrchardCore.Email",], Category = "Security" )] @@ -136,12 +105,6 @@ Id = UserConstants.Features.SmsAuthenticator, Name = "Two-Factor SMS Method", Description = "Provides users a two-factor authentication method through an SMS service.", - Dependencies = - [ - UserConstants.Features.Users, - UserConstants.Features.TwoFactorAuthentication, - "OrchardCore.Liquid", - "OrchardCore.Sms", - ], + Dependencies = [UserConstants.Features.Users, UserConstants.Features.TwoFactorAuthentication, "OrchardCore.Liquid", "OrchardCore.Sms",], Category = "Security" )] diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Users/Migrations.cs index 6e8f182a55f..29779c54d89 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Migrations.cs @@ -17,67 +17,38 @@ public class Migrations : DataMigration { public async Task CreateAsync() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("NormalizedUserName") // TODO These should have defaults. on SQL Server they will fall at 255. Exceptions are currently thrown if you go over that. - .Column("NormalizedEmail") - .Column("IsEnabled", c => c.NotNull().WithDefault(true)) - .Column("IsLockoutEnabled", c => c.NotNull().WithDefault(false)) - .Column("LockoutEndUtc", c => c.Nullable()) - .Column("AccessFailedCount", c => c.NotNull().WithDefault(0)) - .Column("UserId") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("NormalizedUserName") // TODO These should have defaults. on SQL Server they will fall at 255. Exceptions are currently thrown if you go over that. + .Column("NormalizedEmail") + .Column("IsEnabled", c => c.NotNull().WithDefault(true)) + .Column("IsLockoutEnabled", c => c.NotNull().WithDefault(false)) + .Column("LockoutEndUtc", c => c.Nullable()) + .Column("AccessFailedCount", c => c.NotNull().WithDefault(0)) + .Column("UserId") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserIndex_DocumentId", - "DocumentId", - "UserId", - "NormalizedUserName", - "NormalizedEmail", - "IsEnabled" - ) + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_UserIndex_DocumentId", "DocumentId", "UserId", "NormalizedUserName", "NormalizedEmail", "IsEnabled") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserIndex_Lockout", - "DocumentId", - "IsLockoutEnabled", - "LockoutEndUtc", - "AccessFailedCount" - ) + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_UserIndex_Lockout", "DocumentId", "IsLockoutEnabled", "LockoutEndUtc", "AccessFailedCount") ); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("RoleName") - .Column("Count") - ); + await SchemaBuilder.CreateReduceIndexTableAsync(table => table.Column("RoleName").Column("Count")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserByRoleNameIndex_RoleName", - "RoleName") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_UserByRoleNameIndex_RoleName", "RoleName")); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("LoginProvider") - .Column("ProviderKey")); + await SchemaBuilder.CreateMapIndexTableAsync(table => table.Column("LoginProvider").Column("ProviderKey")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserByLoginInfoIndex_DocumentId", - "DocumentId", - "LoginProvider", - "ProviderKey") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_UserByLoginInfoIndex_DocumentId", "DocumentId", "LoginProvider", "ProviderKey") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ClaimType") - .Column("ClaimValue"), - null); + await SchemaBuilder.CreateMapIndexTableAsync(table => table.Column("ClaimType").Column("ClaimValue"), null); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserByClaimIndex_DocumentId", - "DocumentId", - "ClaimType", - "ClaimValue") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_UserByClaimIndex_DocumentId", "DocumentId", "ClaimType", "ClaimValue")); // Shortcut other migration steps on new content definition schemas. return 13; @@ -86,9 +57,7 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom1Async() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("LoginProvider") - .Column("ProviderKey")); + await SchemaBuilder.CreateMapIndexTableAsync(table => table.Column("LoginProvider").Column("ProviderKey")); return 2; } @@ -96,10 +65,7 @@ await SchemaBuilder.CreateMapIndexTableAsync(table => tabl // This code can be removed in a later version. public async Task UpdateFrom2Async() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ClaimType") - .Column("ClaimValue"), - null); + await SchemaBuilder.CreateMapIndexTableAsync(table => table.Column("ClaimType").Column("ClaimValue"), null); return 3; } @@ -107,8 +73,7 @@ await SchemaBuilder.CreateMapIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom3Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("IsEnabled", c => c.NotNull().WithDefault(true))); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("IsEnabled", c => c.NotNull().WithDefault(true))); return 4; } @@ -117,8 +82,7 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom4Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("UserId")); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("UserId")); return 5; } @@ -180,28 +144,15 @@ public int UpdateFrom7() // This code can be removed in a later version. public async Task UpdateFrom8Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserIndex_DocumentId", - "DocumentId", - "UserId", - "NormalizedUserName", - "NormalizedEmail", - "IsEnabled") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_UserIndex_DocumentId", "DocumentId", "UserId", "NormalizedUserName", "NormalizedEmail", "IsEnabled") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserByLoginInfoIndex_DocumentId", - "DocumentId", - "LoginProvider", - "ProviderKey") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_UserByLoginInfoIndex_DocumentId", "DocumentId", "LoginProvider", "ProviderKey") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserByClaimIndex_DocumentId", - "DocumentId", - "ClaimType", - "ClaimValue") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_UserByClaimIndex_DocumentId", "DocumentId", "ClaimType", "ClaimValue")); return 9; } @@ -209,37 +160,26 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom9Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserByRoleNameIndex_RoleName", - "RoleName") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_UserByRoleNameIndex_RoleName", "RoleName")); return 10; } public async Task UpdateFrom10Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("IsLockoutEnabled", c => c.NotNull().WithDefault(false))); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("IsLockoutEnabled", c => c.NotNull().WithDefault(false))); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("LockoutEndUtc", c => c.Nullable())); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("LockoutEndUtc", c => c.Nullable())); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("AccessFailedCount", c => c.NotNull().WithDefault(0))); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("AccessFailedCount", c => c.NotNull().WithDefault(0))); return 11; } public async Task UpdateFrom11Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_UserIndex_Lockout", - "DocumentId", - "IsLockoutEnabled", - "LockoutEndUtc", - "AccessFailedCount" - ) + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_UserIndex_Lockout", "DocumentId", "IsLockoutEnabled", "LockoutEndUtc", "AccessFailedCount") ); return 12; @@ -271,7 +211,8 @@ public int UpdateFrom12() var quotedContentColumnName = dialect.QuoteForColumnName("Content"); var quotedTypeColumnName = dialect.QuoteForColumnName("Type"); - var updateCmd = $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, 'OrchardCore.Users.Models.LoginSettings, OrchardCore.Users', 'OrchardCore.Users.Models.LoginSettings, OrchardCore.Users.Core') WHERE {quotedTypeColumnName} = 'OrchardCore.Deployment.DeploymentPlan, OrchardCore.Deployment.Abstractions'"; + var updateCmd = + $"UPDATE {quotedTableName} SET {quotedContentColumnName} = REPLACE({quotedContentColumnName}, 'OrchardCore.Users.Models.LoginSettings, OrchardCore.Users', 'OrchardCore.Users.Models.LoginSettings, OrchardCore.Users.Core') WHERE {quotedTypeColumnName} = 'OrchardCore.Deployment.DeploymentPlan, OrchardCore.Deployment.Abstractions'"; await transaction.Connection.ExecuteAsync(updateCmd, null, transaction); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Users/Permissions.cs index 8f17b9304ad..787aa3ef919 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Permissions.cs @@ -14,50 +14,18 @@ public class Permissions : IPermissionProvider public static readonly Permission EditUsers = CommonPermissions.EditUsers; public static readonly Permission DeleteUsers = CommonPermissions.DeleteUsers; - private readonly IEnumerable _allPermissions = - [ - ManageUsers, - ViewUsers, - EditOwnUser, - ListUsers, - EditUsers, - DeleteUsers, - ]; + private readonly IEnumerable _allPermissions = [ManageUsers, ViewUsers, EditOwnUser, ListUsers, EditUsers, DeleteUsers,]; - private readonly IEnumerable _generalPermissions = - [ - EditOwnUser, - ]; + private readonly IEnumerable _generalPermissions = [EditOwnUser,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Moderator", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Contributor", - Permissions = _generalPermissions, - }, - new PermissionStereotype - { - Name = "Author", - Permissions = _generalPermissions, - } - ]; + [ + new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, }, + new PermissionStereotype { Name = "Editor", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Moderator", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Contributor", Permissions = _generalPermissions, }, + new PermissionStereotype { Name = "Author", Permissions = _generalPermissions, } + ]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Recipes/CustomUserSettingsStep.cs b/src/OrchardCore.Modules/OrchardCore.Users/Recipes/CustomUserSettingsStep.cs index 39f4d76b580..16ce3a937de 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Recipes/CustomUserSettingsStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Recipes/CustomUserSettingsStep.cs @@ -31,11 +31,7 @@ public async Task ExecuteAsync(RecipeExecutionContext context) var model = context.Step; - var customUserSettingsList = (JsonArray)model - .AsEnumerable() - .Where(p => p.Key != "name") - .Select(p => p.Value) - .FirstOrDefault(); + var customUserSettingsList = (JsonArray)model.AsEnumerable().Where(p => p.Key != "name").Select(p => p.Value).FirstOrDefault(); var allUsers = await _session.Query().ListAsync(); @@ -54,8 +50,7 @@ public async Task ExecuteAsync(RecipeExecutionContext context) continue; } - if (!userCustomUserSettings.TryGetPropertyValue("user-custom-user-settings", out jsonNode) || - jsonNode is not JsonArray userSettings) + if (!userCustomUserSettings.TryGetPropertyValue("user-custom-user-settings", out jsonNode) || jsonNode is not JsonArray userSettings) { continue; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Recipes/UsersStep.cs b/src/OrchardCore.Modules/OrchardCore.Users/Recipes/UsersStep.cs index a52a8cae6e8..94e668cdc4c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Recipes/UsersStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Recipes/UsersStep.cs @@ -14,9 +14,7 @@ public class UsersStep : IRecipeStepHandler private readonly UserManager _userManager; private readonly ISession _session; - public UsersStep( - UserManager userManager, - ISession session) + public UsersStep(UserManager userManager, ISession session) { _userManager = userManager; _session = session; diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/CustomUserSettingsService.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/CustomUserSettingsService.cs index c9ada8479ed..e6d0be171eb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/CustomUserSettingsService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/CustomUserSettingsService.cs @@ -18,10 +18,7 @@ public class CustomUserSettingsService private readonly Lazy>> _settingsTypes; private readonly ISession _session; - public CustomUserSettingsService( - IContentManager contentManager, - IContentDefinitionManager contentDefinitionManager, - ISession session) + public CustomUserSettingsService(IContentManager contentManager, IContentDefinitionManager contentDefinitionManager, ISession session) { _contentManager = contentManager; _contentDefinitionManager = contentDefinitionManager; @@ -30,26 +27,20 @@ public CustomUserSettingsService( } [Obsolete($"Instead, utilize the {nameof(GetAllSettingsTypeNamesAsync)} method. This current method is slated for removal in upcoming releases.")] - public IEnumerable GetAllSettingsTypeNames() - => _settingsTypes.Value.GetAwaiter().GetResult().Keys; + public IEnumerable GetAllSettingsTypeNames() => _settingsTypes.Value.GetAwaiter().GetResult().Keys; [Obsolete($"Instead, utilize the {nameof(GetAllSettingsTypesAsync)} method. This current method is slated for removal in upcoming releases.")] - public IEnumerable GetAllSettingsTypes() - => _settingsTypes.Value.GetAwaiter().GetResult().Values; + public IEnumerable GetAllSettingsTypes() => _settingsTypes.Value.GetAwaiter().GetResult().Values; [Obsolete($"Instead, utilize the {nameof(GetSettingsTypesAsync)} method. This current method is slated for removal in upcoming releases.")] - public IEnumerable GetSettingsTypes(params string[] settingsTypeNames) - => GetSettingsTypesAsync(settingsTypeNames).GetAwaiter().GetResult(); + public IEnumerable GetSettingsTypes(params string[] settingsTypeNames) => GetSettingsTypesAsync(settingsTypeNames).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(GetSettingsTypeAsync)} method. This current method is slated for removal in upcoming releases.")] - public ContentTypeDefinition GetSettingsType(string settingsTypeName) - => GetSettingsTypeAsync(settingsTypeName).GetAwaiter().GetResult(); + public ContentTypeDefinition GetSettingsType(string settingsTypeName) => GetSettingsTypeAsync(settingsTypeName).GetAwaiter().GetResult(); - public async Task> GetAllSettingsTypeNamesAsync() - => (await _settingsTypes.Value).Keys; + public async Task> GetAllSettingsTypeNamesAsync() => (await _settingsTypes.Value).Keys; - public async Task> GetAllSettingsTypesAsync() - => (await _settingsTypes.Value).Values; + public async Task> GetAllSettingsTypesAsync() => (await _settingsTypes.Value).Values; public async Task> GetSettingsTypesAsync(params string[] settingsTypeNames) { @@ -127,8 +118,7 @@ private async Task> GetContentTypeAsy { var contentTypes = await _contentDefinitionManager.ListTypeDefinitionsAsync(); - var result = contentTypes.Where(x => x.StereotypeEquals("CustomUserSettings")) - .ToDictionary(x => x.Name); + var result = contentTypes.Where(x => x.StereotypeEquals("CustomUserSettings")).ToDictionary(x => x.Name); return result; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListFilterParser.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListFilterParser.cs index f18fee3b7f8..130e4600a03 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListFilterParser.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListFilterParser.cs @@ -12,7 +12,6 @@ public DefaultUsersAdminListFilterParser(IQueryParser parser) _parser = parser; } - public QueryFilterResult Parse(string text) - => _parser.Parse(text); + public QueryFilterResult Parse(string text) => _parser.Parse(text); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListFilterProvider.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListFilterProvider.cs index 05f3ead7488..3116fc1cc77 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListFilterProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListFilterProvider.cs @@ -16,139 +16,166 @@ public class DefaultUsersAdminListFilterProvider : IUsersAdminListFilterProvider public void Build(QueryEngineBuilder builder) { builder - .WithNamedTerm("status", builder => builder - .OneCondition((val, query) => - { - if (Enum.TryParse(val, true, out var usersStatus)) - { - switch (usersStatus) - { - case UsersFilter.Enabled: - query.With(u => u.IsEnabled); - break; - case UsersFilter.Disabled: - query.With(u => !u.IsEnabled); - break; - } - } + .WithNamedTerm( + "status", + builder => + builder + .OneCondition( + (val, query) => + { + if (Enum.TryParse(val, true, out var usersStatus)) + { + switch (usersStatus) + { + case UsersFilter.Enabled: + query.With(u => u.IsEnabled); + break; + case UsersFilter.Disabled: + query.With(u => !u.IsEnabled); + break; + } + } - return query; - }) - .MapTo((val, model) => - { - if (Enum.TryParse(val, true, out var usersFilter)) - { - model.Filter = usersFilter; - } - }) - .MapFrom((model) => - { - return model.Filter switch - { - UsersFilter.Enabled => (true, model.Filter.ToString()), - UsersFilter.Disabled => (true, model.Filter.ToString()), - _ => (false, string.Empty) - }; - }) + return query; + } + ) + .MapTo( + (val, model) => + { + if (Enum.TryParse(val, true, out var usersFilter)) + { + model.Filter = usersFilter; + } + } + ) + .MapFrom( + (model) => + { + return model.Filter switch + { + UsersFilter.Enabled => (true, model.Filter.ToString()), + UsersFilter.Disabled => (true, model.Filter.ToString()), + _ => (false, string.Empty) + }; + } + ) ) - .WithNamedTerm("sort", builder => builder - .OneCondition((val, query) => - { - if (Enum.TryParse(val, true, out var usersOrder)) - { - switch (usersOrder) - { - case UsersOrder.Name: - query.With().OrderBy(u => u.NormalizedUserName); - break; - case UsersOrder.Email: - query.With().OrderBy(u => u.NormalizedEmail); - break; - }; - } - else - { - query.With().OrderBy(u => u.NormalizedUserName); - } + .WithNamedTerm( + "sort", + builder => + builder + .OneCondition( + (val, query) => + { + if (Enum.TryParse(val, true, out var usersOrder)) + { + switch (usersOrder) + { + case UsersOrder.Name: + query.With().OrderBy(u => u.NormalizedUserName); + break; + case UsersOrder.Email: + query.With().OrderBy(u => u.NormalizedEmail); + break; + } + ; + } + else + { + query.With().OrderBy(u => u.NormalizedUserName); + } - return query; - }) - .MapTo((val, model) => - { - if (Enum.TryParse(val, true, out var order)) - { - model.Order = order; - } - }) - .MapFrom((model) => - { - if (model.Order != UsersOrder.Name) - { - return (true, model.Order.ToString()); - } + return query; + } + ) + .MapTo( + (val, model) => + { + if (Enum.TryParse(val, true, out var order)) + { + model.Order = order; + } + } + ) + .MapFrom( + (model) => + { + if (model.Order != UsersOrder.Name) + { + return (true, model.Order.ToString()); + } - return (false, string.Empty); - }) - .AlwaysRun() + return (false, string.Empty); + } + ) + .AlwaysRun() ) - .WithNamedTerm("role", builder => builder - .OneCondition((val, query, ctx) => - { - var context = (UserQueryContext)ctx; - var userManager = context.ServiceProvider.GetRequiredService>(); - var normalizedRoleName = userManager.NormalizeName(val); - query.With(x => x.RoleName == normalizedRoleName); + .WithNamedTerm( + "role", + builder => + builder + .OneCondition( + (val, query, ctx) => + { + var context = (UserQueryContext)ctx; + var userManager = context.ServiceProvider.GetRequiredService>(); + var normalizedRoleName = userManager.NormalizeName(val); + query.With(x => x.RoleName == normalizedRoleName); - return new ValueTask>(query); - }) - .MapTo((val, model) => model.SelectedRole = val) - .MapFrom((model) => (!string.IsNullOrEmpty(model.SelectedRole), model.SelectedRole)) + return new ValueTask>(query); + } + ) + .MapTo((val, model) => model.SelectedRole = val) + .MapFrom((model) => (!string.IsNullOrEmpty(model.SelectedRole), model.SelectedRole)) ) - .WithDefaultTerm(UsersAdminListFilterOptions.DefaultTermName, builder => builder - .ManyCondition( - (val, query, ctx) => - { - var context = (UserQueryContext)ctx; - var userManager = context.ServiceProvider.GetRequiredService>(); - var normalizedUserName = userManager.NormalizeName(val); - query.With(x => x.NormalizedUserName.Contains(normalizedUserName)); + .WithDefaultTerm( + UsersAdminListFilterOptions.DefaultTermName, + builder => + builder.ManyCondition( + (val, query, ctx) => + { + var context = (UserQueryContext)ctx; + var userManager = context.ServiceProvider.GetRequiredService>(); + var normalizedUserName = userManager.NormalizeName(val); + query.With(x => x.NormalizedUserName.Contains(normalizedUserName)); - return new ValueTask>(query); - }, - (val, query, ctx) => - { - var context = (UserQueryContext)ctx; - var userManager = context.ServiceProvider.GetRequiredService>(); - var normalizedUserName = userManager.NormalizeName(val); - query.With(x => x.NormalizedUserName.NotContains(normalizedUserName)); + return new ValueTask>(query); + }, + (val, query, ctx) => + { + var context = (UserQueryContext)ctx; + var userManager = context.ServiceProvider.GetRequiredService>(); + var normalizedUserName = userManager.NormalizeName(val); + query.With(x => x.NormalizedUserName.NotContains(normalizedUserName)); - return new ValueTask>(query); - } - ) + return new ValueTask>(query); + } + ) ) - .WithNamedTerm("email", builder => builder - .ManyCondition( - (val, query, ctx) => - { - var context = (UserQueryContext)ctx; - var userManager = context.ServiceProvider.GetRequiredService>(); - var normalizedEmail = userManager.NormalizeEmail(val); - query.With(x => x.NormalizedEmail.Contains(normalizedEmail)); + .WithNamedTerm( + "email", + builder => + builder.ManyCondition( + (val, query, ctx) => + { + var context = (UserQueryContext)ctx; + var userManager = context.ServiceProvider.GetRequiredService>(); + var normalizedEmail = userManager.NormalizeEmail(val); + query.With(x => x.NormalizedEmail.Contains(normalizedEmail)); - return new ValueTask>(query); - }, - (val, query, ctx) => - { - var context = (UserQueryContext)ctx; - var userManager = context.ServiceProvider.GetRequiredService>(); - var normalizedEmail = userManager.NormalizeEmail(val); - query.With(x => x.NormalizedEmail.NotContains(normalizedEmail)); + return new ValueTask>(query); + }, + (val, query, ctx) => + { + var context = (UserQueryContext)ctx; + var userManager = context.ServiceProvider.GetRequiredService>(); + var normalizedEmail = userManager.NormalizeEmail(val); + query.With(x => x.NormalizedEmail.NotContains(normalizedEmail)); - return new ValueTask>(query); - } - ) + return new ValueTask>(query); + } + ) ); - } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListQueryService.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListQueryService.cs index 94594a6a436..ebebcf597f1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListQueryService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/DefaultUsersAdminListQueryService.cs @@ -15,7 +15,7 @@ namespace OrchardCore.Users.Services; public class DefaultUsersAdminListQueryService : IUsersAdminListQueryService { - private readonly static string[] _operators = ["OR", "AND", "||", "&&"]; + private static readonly string[] _operators = ["OR", "AND", "||", "&&"]; private readonly ISession _session; private readonly IServiceProvider _serviceProvider; @@ -28,7 +28,8 @@ public DefaultUsersAdminListQueryService( IServiceProvider serviceProvider, ILogger logger, IOptions userAdminListFilterOptions, - IEnumerable usersAdminListFilters) + IEnumerable usersAdminListFilters + ) { _session = session; _serviceProvider = serviceProvider; @@ -41,15 +42,12 @@ public async Task> QueryAsync(UserIndexOptions options, IUpdateMode { var defaultTermNode = options.FilterResult.OfType().FirstOrDefault(); var defaultOperator = defaultTermNode?.Operation; - var defaultTermName = string.IsNullOrEmpty(_userAdminListFilterOptions.TermName) - ? UsersAdminListFilterOptions.DefaultTermName - : _userAdminListFilterOptions.TermName; + var defaultTermName = string.IsNullOrEmpty(_userAdminListFilterOptions.TermName) ? UsersAdminListFilterOptions.DefaultTermName : _userAdminListFilterOptions.TermName; if (defaultTermNode is not null) { var value = defaultTermNode.ToString(); - if (_userAdminListFilterOptions.UseExactMatch - && !_operators.Any(op => value.Contains(op, StringComparison.Ordinal))) + if (_userAdminListFilterOptions.UseExactMatch && !_operators.Any(op => value.Contains(op, StringComparison.Ordinal))) { // Use an unary operator based on a full quoted string. defaultOperator = new UnaryNode(value.Trim('"'), OperateNodeQuotes.Double); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/MembershipService.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/MembershipService.cs index 45400e671f0..378cd1264e3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/MembershipService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/MembershipService.cs @@ -10,9 +10,7 @@ public class MembershipService : IMembershipService private readonly UserManager _userManager; private readonly IUserClaimsPrincipalFactory _claimsPrincipalFactory; - public MembershipService( - IUserClaimsPrincipalFactory claimsPrincipalFactory, - UserManager userManager) + public MembershipService(IUserClaimsPrincipalFactory claimsPrincipalFactory, UserManager userManager) { _claimsPrincipalFactory = claimsPrincipalFactory; _userManager = userManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/RecipeEnvironmentSuperUserProvider.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/RecipeEnvironmentSuperUserProvider.cs index f247b50a062..b2882e95084 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/RecipeEnvironmentSuperUserProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/RecipeEnvironmentSuperUserProvider.cs @@ -15,10 +15,7 @@ public class RecipeEnvironmentSuperUserProvider : IRecipeEnvironmentProvider private IUserService _userService; private readonly ILogger _logger; - public RecipeEnvironmentSuperUserProvider( - ISiteService siteService, - IServiceProvider serviceProvider, - ILogger logger) + public RecipeEnvironmentSuperUserProvider(ISiteService siteService, IServiceProvider serviceProvider, ILogger logger) { _siteService = siteService; _serviceProvider = serviceProvider; diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/RoleAuthorizationHandler.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/RoleAuthorizationHandler.cs index c78da5d3bec..0e3b106512b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/RoleAuthorizationHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/RoleAuthorizationHandler.cs @@ -56,9 +56,11 @@ protected override async Task HandleRequirementAsync(AuthorizationHandlerContext { var currentUserId = context.User.FindFirstValue(ClaimTypes.NameIdentifier); - if (requirement.Permission.Name == CommonPermissions.EditUsers.Name + if ( + requirement.Permission.Name == CommonPermissions.EditUsers.Name && user.UserId == currentUserId - && await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.EditOwnUser)) + && await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.EditOwnUser) + ) { context.Succeed(requirement); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/RoleTwoFactorAuthenticationHandler.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/RoleTwoFactorAuthenticationHandler.cs index e415ef8fd23..34685f44ea7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/RoleTwoFactorAuthenticationHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/RoleTwoFactorAuthenticationHandler.cs @@ -13,10 +13,7 @@ public class RoleTwoFactorAuthenticationHandler : ITwoFactorAuthenticationHandle private readonly UserManager _userManager; private readonly ISiteService _siteService; - public RoleTwoFactorAuthenticationHandler( - IHttpContextAccessor httpContextAccessor, - UserManager userManager, - ISiteService siteService) + public RoleTwoFactorAuthenticationHandler(IHttpContextAccessor httpContextAccessor, UserManager userManager, ISiteService siteService) { _httpContextAccessor = httpContextAccessor; _userManager = userManager; diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/RolesAdminListFilterProvider.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/RolesAdminListFilterProvider.cs index 39548fe9ab3..e15341bbabf 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/RolesAdminListFilterProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/RolesAdminListFilterProvider.cs @@ -13,28 +13,33 @@ public class RolesAdminListFilterProvider : IUsersAdminListFilterProvider { public void Build(QueryEngineBuilder builder) { - builder.WithNamedTerm("role-restriction", builder => builder - .OneCondition(async (contentType, query, ctx) => - { - var context = (UserQueryContext)ctx; + builder.WithNamedTerm( + "role-restriction", + builder => + builder + .OneCondition( + async (contentType, query, ctx) => + { + var context = (UserQueryContext)ctx; - var httpContextAccessor = context.ServiceProvider.GetRequiredService(); - var authorizationService = context.ServiceProvider.GetRequiredService(); - var roleService = context.ServiceProvider.GetRequiredService(); + var httpContextAccessor = context.ServiceProvider.GetRequiredService(); + var authorizationService = context.ServiceProvider.GetRequiredService(); + var roleService = context.ServiceProvider.GetRequiredService(); - var user = httpContextAccessor.HttpContext?.User; + var user = httpContextAccessor.HttpContext?.User; - if (user != null && !await authorizationService.AuthorizeAsync(user, CommonPermissions.ListUsers)) - { - // At this point the user cannot see all users, so lets see what role does he have access too and filter by them. - var accessibleRoles = await roleService.GetAccessibleRoleNamesAsync(authorizationService, user, CommonPermissions.ListUsers); + if (user != null && !await authorizationService.AuthorizeAsync(user, CommonPermissions.ListUsers)) + { + // At this point the user cannot see all users, so lets see what role does he have access too and filter by them. + var accessibleRoles = await roleService.GetAccessibleRoleNamesAsync(authorizationService, user, CommonPermissions.ListUsers); - query.With(index => index.RoleName.IsIn(accessibleRoles)); - } + query.With(index => index.RoleName.IsIn(accessibleRoles)); + } - return query; - }) + return query; + } + ) .AlwaysRun() - ); + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/SetupEventHandler.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/SetupEventHandler.cs index aa390b27af9..24f49dc59ad 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/SetupEventHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/SetupEventHandler.cs @@ -30,10 +30,14 @@ public Task SetupAsync(SetupContext context) user.RoleNames.Add("Administrator"); - return _userService.CreateUserAsync(user, context.Properties[SetupConstants.AdminPassword]?.ToString(), (key, message) => - { - context.Errors[key] = message; - }); + return _userService.CreateUserAsync( + user, + context.Properties[SetupConstants.AdminPassword]?.ToString(), + (key, message) => + { + context.Errors[key] = message; + } + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/TwoFactorAuthenticationClaimsProvider.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/TwoFactorAuthenticationClaimsProvider.cs index 3d31a6ba5e1..f4fdea9d61f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/TwoFactorAuthenticationClaimsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/TwoFactorAuthenticationClaimsProvider.cs @@ -11,9 +11,7 @@ public class TwoFactorAuthenticationClaimsProvider : IUserClaimsProvider private readonly UserManager _userManager; private readonly ITwoFactorAuthenticationHandlerCoordinator _twoFactorHandlerCoordinator; - public TwoFactorAuthenticationClaimsProvider( - UserManager userManager, - ITwoFactorAuthenticationHandlerCoordinator twoFactorHandlerCoordinator) + public TwoFactorAuthenticationClaimsProvider(UserManager userManager, ITwoFactorAuthenticationHandlerCoordinator twoFactorHandlerCoordinator) { _userManager = userManager; _twoFactorHandlerCoordinator = twoFactorHandlerCoordinator; @@ -25,8 +23,7 @@ public async Task GenerateAsync(IUser user, ClaimsIdentity claims) ArgumentNullException.ThrowIfNull(claims); - if (await _twoFactorHandlerCoordinator.IsRequiredAsync() - && !await _userManager.GetTwoFactorEnabledAsync(user)) + if (await _twoFactorHandlerCoordinator.IsRequiredAsync() && !await _userManager.GetTwoFactorEnabledAsync(user)) { // At this point, we know that the user must enable two-factor authentication. claims.AddClaim(new Claim(UserConstants.TwoFactorAuthenticationClaimType, "required")); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Services/UsersThemeSelector.cs b/src/OrchardCore.Modules/OrchardCore.Users/Services/UsersThemeSelector.cs index 999e0f6896a..7d4aaa15ec4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Services/UsersThemeSelector.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Services/UsersThemeSelector.cs @@ -21,10 +21,7 @@ public class UsersThemeSelector : IThemeSelector private readonly IAdminThemeService _adminThemeService; private readonly IHttpContextAccessor _httpContextAccessor; - public UsersThemeSelector( - ISiteService siteService, - IAdminThemeService adminThemeService, - IHttpContextAccessor httpContextAccessor) + public UsersThemeSelector(ISiteService siteService, IAdminThemeService adminThemeService, IHttpContextAccessor httpContextAccessor) { _siteService = siteService; _adminThemeService = adminThemeService; @@ -45,7 +42,8 @@ public async Task GetThemeAsync() useSiteTheme = (await _siteService.GetSiteSettingsAsync()).As().UseSiteTheme; break; case "TwoFactorAuthentication": - useSiteTheme = routeValues["action"] != null + useSiteTheme = + routeValues["action"] != null && routeValues["action"].ToString().StartsWith("LoginWith", StringComparison.OrdinalIgnoreCase) && (await _siteService.GetSiteSettingsAsync()).As().UseSiteTheme; break; @@ -66,11 +64,7 @@ public async Task GetThemeAsync() return null; } - return new ThemeSelectorResult - { - Priority = useSiteTheme ? -100 : 100, - ThemeName = adminThemeName - }; + return new ThemeSelectorResult { Priority = useSiteTheme ? -100 : 100, ThemeName = adminThemeName }; } return null; diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Users/Startup.cs index d406e0555bb..6d74e99ac92 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Startup.cs @@ -234,51 +234,56 @@ public class LiquidStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.Configure(o => - { - o.Filters.AddFilter("has_claim", UserFilters.HasClaim); - o.Filters.AddFilter("user_id", UserFilters.UserId); - - o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register(); - - o.Scope.SetValue("User", new ObjectValue(new LiquidUserAccessor())); - o.MemberAccessStrategy.Register((obj, name, ctx) => + services + .Configure(o => { - var user = ((LiquidTemplateContext)ctx).Services.GetRequiredService().HttpContext?.User; - if (user != null) - { - return name switch - { - nameof(ClaimsPrincipal.Identity) => new ObjectValue(user.Identity), - _ => NilValue.Instance - }; - } + o.Filters.AddFilter("has_claim", UserFilters.HasClaim); + o.Filters.AddFilter("user_id", UserFilters.UserId); - return NilValue.Instance; - }); + o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register((user, name, context) => - { - return name switch - { - nameof(User.UserId) => new StringValue(user.UserId), - nameof(User.UserName) => new StringValue(user.UserName), - nameof(User.NormalizedUserName) => new StringValue(user.NormalizedUserName), - nameof(User.Email) => new StringValue(user.Email), - nameof(User.NormalizedEmail) => new StringValue(user.NormalizedEmail), - nameof(User.EmailConfirmed) => user.EmailConfirmed ? BooleanValue.True : BooleanValue.False, - nameof(User.IsEnabled) => user.IsEnabled ? BooleanValue.True : BooleanValue.False, - nameof(User.RoleNames) => new ArrayValue(user.RoleNames.Select(x => new StringValue(x))), - nameof(User.Properties) => new ObjectValue(user.Properties), - _ => NilValue.Instance - }; - }); - }) - .AddLiquidFilter("users_by_id") - .AddLiquidFilter("has_permission") - .AddLiquidFilter("is_in_role") - .AddLiquidFilter("user_email"); + o.Scope.SetValue("User", new ObjectValue(new LiquidUserAccessor())); + o.MemberAccessStrategy.Register( + (obj, name, ctx) => + { + var user = ((LiquidTemplateContext)ctx).Services.GetRequiredService().HttpContext?.User; + if (user != null) + { + return name switch + { + nameof(ClaimsPrincipal.Identity) => new ObjectValue(user.Identity), + _ => NilValue.Instance + }; + } + + return NilValue.Instance; + } + ); + + o.MemberAccessStrategy.Register( + (user, name, context) => + { + return name switch + { + nameof(User.UserId) => new StringValue(user.UserId), + nameof(User.UserName) => new StringValue(user.UserName), + nameof(User.NormalizedUserName) => new StringValue(user.NormalizedUserName), + nameof(User.Email) => new StringValue(user.Email), + nameof(User.NormalizedEmail) => new StringValue(user.NormalizedEmail), + nameof(User.EmailConfirmed) => user.EmailConfirmed ? BooleanValue.True : BooleanValue.False, + nameof(User.IsEnabled) => user.IsEnabled ? BooleanValue.True : BooleanValue.False, + nameof(User.RoleNames) => new ArrayValue(user.RoleNames.Select(x => new StringValue(x))), + nameof(User.Properties) => new ObjectValue(user.Properties), + _ => NilValue.Instance + }; + } + ); + }) + .AddLiquidFilter("users_by_id") + .AddLiquidFilter("has_permission") + .AddLiquidFilter("is_in_role") + .AddLiquidFilter("user_email"); } } @@ -334,7 +339,10 @@ public class ChangeEmailDeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddSiteSettingsPropertyDeploymentStep(S => S["Change Email settings"], S => S["Exports the Change Email settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Change Email settings"], + S => S["Exports the Change Email settings."] + ); } } @@ -388,7 +396,10 @@ public class RegistrationDeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddSiteSettingsPropertyDeploymentStep(S => S["Registration settings"], S => S["Exports the Registration settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Registration settings"], + S => S["Exports the Registration settings."] + ); } } @@ -401,7 +412,6 @@ public class ResetPasswordStartup : StartupBase private const string ResetPasswordConfirmationPath = "ResetPasswordConfirmation"; private const string ResetPasswordControllerName = "ResetPassword"; - public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { routes.MapAreaControllerRoute( @@ -448,7 +458,10 @@ public class ResetPasswordDeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { - services.AddSiteSettingsPropertyDeploymentStep(S => S["Reset Password settings"], S => S["Exports the Reset Password settings."]); + services.AddSiteSettingsPropertyDeploymentStep( + S => S["Reset Password settings"], + S => S["Exports the Reset Password settings."] + ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Drivers/UserTimeZoneDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Drivers/UserTimeZoneDisplayDriver.cs index f4a0436697c..3f1e0187fb4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Drivers/UserTimeZoneDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Drivers/UserTimeZoneDisplayDriver.cs @@ -31,12 +31,7 @@ public override IDisplayResult Edit(UserTimeZone userTimeZone, BuildEditorContex .Location("Content:2"); } - public override async Task UpdateAsync( - User user, - UserTimeZone userTimeZone, - IUpdateModel updater, - BuildEditorContext context - ) + public override async Task UpdateAsync(User user, UserTimeZone userTimeZone, IUpdateModel updater, BuildEditorContext context) { var model = new UserTimeZoneViewModel(); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Services/UserTimeZoneSelector.cs b/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Services/UserTimeZoneSelector.cs index 8ecd82d21b7..52be615f8be 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Services/UserTimeZoneSelector.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Services/UserTimeZoneSelector.cs @@ -17,13 +17,6 @@ public UserTimeZoneSelector(UserTimeZoneService userTimeZoneService) public Task GetTimeZoneAsync() { - return Task.FromResult( - new TimeZoneSelectorResult - { - Priority = 100, - TimeZoneId = async () => - (await _userTimeZoneService.GetUserTimeZoneAsync())?.TimeZoneId - } - ); + return Task.FromResult(new TimeZoneSelectorResult { Priority = 100, TimeZoneId = async () => (await _userTimeZoneService.GetUserTimeZoneAsync())?.TimeZoneId }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Services/UserTimeZoneService.cs b/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Services/UserTimeZoneService.cs index e792807792f..ef2f835670c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Services/UserTimeZoneService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Services/UserTimeZoneService.cs @@ -21,11 +21,7 @@ public class UserTimeZoneService private readonly IDistributedCache _distributedCache; private readonly IHttpContextAccessor _httpContextAccessor; - public UserTimeZoneService( - IClock clock, - IDistributedCache distributedCache, - IHttpContextAccessor httpContextAccessor - ) + public UserTimeZoneService(IClock clock, IDistributedCache distributedCache, IHttpContextAccessor httpContextAccessor) { _clock = clock; _distributedCache = distributedCache; @@ -83,11 +79,7 @@ public async ValueTask GetCurrentUserTimeZoneIdAsync() timeZoneId = EmptyTimeZone; } - await _distributedCache.SetStringAsync( - key, - timeZoneId, - _slidingExpiration - ); + await _distributedCache.SetStringAsync(key, timeZoneId, _slidingExpiration); } // Do we know this user doesn't have a configured value? diff --git a/src/OrchardCore.Modules/OrchardCore.Users/TwoFactorAuthenticationStartup.cs b/src/OrchardCore.Modules/OrchardCore.Users/TwoFactorAuthenticationStartup.cs index 26de0d6b210..6c88617f953 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/TwoFactorAuthenticationStartup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/TwoFactorAuthenticationStartup.cs @@ -1,3 +1,4 @@ +using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; @@ -14,7 +15,6 @@ using OrchardCore.Users.Filters; using OrchardCore.Users.Models; using OrchardCore.Users.Services; -using System; namespace OrchardCore.Users; diff --git a/src/OrchardCore.Modules/OrchardCore.Users/UserMenuShapeTableProvider.cs b/src/OrchardCore.Modules/OrchardCore.Users/UserMenuShapeTableProvider.cs index d2874b33f52..10549e8ae55 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/UserMenuShapeTableProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/UserMenuShapeTableProvider.cs @@ -15,7 +15,8 @@ public class UserMenuShapeTableProvider : ShapeTableProvider public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { // Describe any shape-type that starts with 'UserMenuItems__'. - builder.Describe($"{ShapeTypePrefix}*") + builder + .Describe($"{ShapeTypePrefix}*") .OnDisplaying(context => { if (string.IsNullOrEmpty(context.Shape.Metadata.DisplayType) || context.Shape.Metadata.DisplayType == "Detail") diff --git a/src/OrchardCore.Modules/OrchardCore.Users/UserOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Users/UserOptionsConfiguration.cs index dfeffe4108e..97ab290f84f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/UserOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/UserOptionsConfiguration.cs @@ -16,10 +16,7 @@ static UserOptionsConfiguration() .SetUrl("~/OrchardCore.Users/Scripts/password-generator.min.js", "~/OrchardCore.Users/Scripts/password-generator.js") .SetVersion("1.0.0"); - _manifest - .DefineScript("qrcode") - .SetUrl("~/OrchardCore.Users/Scripts/qrcode.min.js", "~/OrchardCore.Users/Scripts/qrcode.js") - .SetVersion("1.0.0"); + _manifest.DefineScript("qrcode").SetUrl("~/OrchardCore.Users/Scripts/qrcode.min.js", "~/OrchardCore.Users/Scripts/qrcode.js").SetVersion("1.0.0"); } public void Configure(ResourceManagementOptions options) diff --git a/src/OrchardCore.Modules/OrchardCore.Users/UserRolePermissions.cs b/src/OrchardCore.Modules/OrchardCore.Users/UserRolePermissions.cs index 4340c5bdd46..c4c808612f8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/UserRolePermissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/UserRolePermissions.cs @@ -19,14 +19,9 @@ public UserRolePermissions(IRoleService roleService) public async Task> GetPermissionsAsync() { - var permissions = new List() - { - AssignRoleToUsers, - }; + var permissions = new List() { AssignRoleToUsers, }; - var roleNames = (await _roleService.GetRoleNamesAsync()) - .Where(roleName => !RoleHelper.SystemRoleNames.Contains(roleName)) - .OrderBy(roleName => roleName); + var roleNames = (await _roleService.GetRoleNamesAsync()).Where(roleName => !RoleHelper.SystemRoleNames.Contains(roleName)).OrderBy(roleName => roleName); foreach (var roleName in roleNames) { @@ -40,15 +35,5 @@ public async Task> GetPermissionsAsync() return permissions; } - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = - [ - AssignRoleToUsers, - ], - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = [AssignRoleToUsers,], },]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/ConfirmEmailViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/ConfirmEmailViewModel.cs index 26ab1eb46dd..9ec0981f118 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/ConfirmEmailViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/ConfirmEmailViewModel.cs @@ -5,9 +5,7 @@ namespace OrchardCore.Users.ViewModels public class ConfirmEmailViewModel : ShapeViewModel { public ConfirmEmailViewModel() - : base("TemplateUserConfirmEmail") - { - } + : base("TemplateUserConfirmEmail") { } public IUser User { get; set; } public string ConfirmEmailUrl { get; set; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserEmailViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserEmailViewModel.cs index a23fd853b8d..eb318b3d294 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserEmailViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserEmailViewModel.cs @@ -12,4 +12,3 @@ public class EditUserEmailViewModel [BindNever] public bool AllowEditing { get; set; } } - diff --git a/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserPhoneNumberViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserPhoneNumberViewModel.cs index 96b9ddcc047..17ec21fed0d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserPhoneNumberViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserPhoneNumberViewModel.cs @@ -12,4 +12,3 @@ public class EditUserPhoneNumberViewModel [BindNever] public bool AllowEditing { get; set; } } - diff --git a/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserViewModel.cs index a5701b3300b..b8cf3f4a03b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/EditUserViewModel.cs @@ -20,6 +20,5 @@ public class EditUserViewModel [BindNever] public bool IsNewRequest { get; set; } - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/LostPasswordViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/LostPasswordViewModel.cs index 132a746689e..468a574c233 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/LostPasswordViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/ViewModels/LostPasswordViewModel.cs @@ -6,9 +6,7 @@ namespace OrchardCore.Users.ViewModels public class LostPasswordViewModel : ShapeViewModel { public LostPasswordViewModel() - : base("TemplateUserLostPassword") - { - } + : base("TemplateUserLostPassword") { } public User User { get; set; } public string LostPasswordUrl { get; set; } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/AssignUserRoleTask.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/AssignUserRoleTask.cs index ff0fa28221d..210aa196d93 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/AssignUserRoleTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/AssignUserRoleTask.cs @@ -22,7 +22,8 @@ public AssignUserRoleTask( UserManager userManager, IUserService userService, IWorkflowExpressionEvaluator expressionEvaluator, - IStringLocalizer localizer) + IStringLocalizer localizer + ) { _userManager = userManager; _userService = userService; diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/RegisterUserTask.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/RegisterUserTask.cs index 16054124fbf..4af89d10f21 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/RegisterUserTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/RegisterUserTask.cs @@ -36,7 +36,8 @@ public RegisterUserTask( IHttpContextAccessor httpContextAccessor, IUpdateModelAccessor updateModelAccessor, IStringLocalizer localizer, - HtmlEncoder htmlEncoder) + HtmlEncoder htmlEncoder + ) { _userService = userService; _userManager = userManager; @@ -107,7 +108,17 @@ public override async Task ExecuteAsync(WorkflowExecuti } var errors = new Dictionary(); - var user = (User)await _userService.CreateUserAsync(new User() { UserName = userName, Email = email, IsEnabled = !RequireModeration }, null, (key, message) => errors.Add(key, message)); + var user = (User) + await _userService.CreateUserAsync( + new User() + { + UserName = userName, + Email = email, + IsEnabled = !RequireModeration + }, + null, + (key, message) => errors.Add(key, message) + ); if (errors.Count > 0) { var updater = _updateModelAccessor.ModelUpdater; @@ -124,8 +135,17 @@ public override async Task ExecuteAsync(WorkflowExecuti { var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); - var uri = _linkGenerator.GetUriByAction(_httpContextAccessor.HttpContext, "ConfirmEmail", - "Registration", new { area = "OrchardCore.Users", userId = user.UserId, code }); + var uri = _linkGenerator.GetUriByAction( + _httpContextAccessor.HttpContext, + "ConfirmEmail", + "Registration", + new + { + area = "OrchardCore.Users", + userId = user.UserId, + code + } + ); workflowContext.Properties["EmailConfirmationUrl"] = uri; diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserCreatedEvent.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserCreatedEvent.cs index a9210add2b9..7b9ef1dd09c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserCreatedEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserCreatedEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Users.Workflows.Activities { public class UserCreatedEvent : UserEvent { - public UserCreatedEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(userService, scriptEvaluator, localizer) - { - } + public UserCreatedEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(userService, scriptEvaluator, localizer) { } public override string Name => nameof(UserCreatedEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserDeletedEvent.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserDeletedEvent.cs index 0e7e45ea691..dac17597be9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserDeletedEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserDeletedEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Users.Workflows.Activities { public class UserDeletedEvent : UserEvent { - public UserDeletedEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(userService, scriptEvaluator, localizer) - { - } + public UserDeletedEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(userService, scriptEvaluator, localizer) { } public override string Name => nameof(UserDeletedEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserDisabledEvent.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserDisabledEvent.cs index c46a9712baa..b46221295a8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserDisabledEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserDisabledEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Users.Workflows.Activities { public class UserDisabledEvent : UserEvent { - public UserDisabledEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(userService, scriptEvaluator, localizer) - { - } + public UserDisabledEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(userService, scriptEvaluator, localizer) { } public override string Name => nameof(UserDisabledEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserEnabledEvent.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserEnabledEvent.cs index 695d869459c..6f6c1beeedb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserEnabledEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserEnabledEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Users.Workflows.Activities { public class UserEnabledEvent : UserEvent { - public UserEnabledEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(userService, scriptEvaluator, localizer) - { - } + public UserEnabledEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(userService, scriptEvaluator, localizer) { } public override string Name => nameof(UserEnabledEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserEvent.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserEvent.cs index 87ee9952da7..fa5e54f008d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserEvent.cs @@ -8,9 +8,8 @@ namespace OrchardCore.Users.Workflows.Activities { public abstract class UserEvent : UserActivity, IEvent { - public UserEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(userService, scriptEvaluator, localizer) - { - } + public UserEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(userService, scriptEvaluator, localizer) { } public override ActivityExecutionResult Execute(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserLoggedInEvent.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserLoggedInEvent.cs index 9079a39a4e1..fe86d2b7ee8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserLoggedInEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserLoggedInEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Users.Workflows.Activities { public class UserLoggedInEvent : UserEvent { - public UserLoggedInEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(userService, scriptEvaluator, localizer) - { - } + public UserLoggedInEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(userService, scriptEvaluator, localizer) { } public override string Name => nameof(UserLoggedInEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserUpdatedEvent.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserUpdatedEvent.cs index 304f966a6ec..ff0d5fc057f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserUpdatedEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/UserUpdatedEvent.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Users.Workflows.Activities { public class UserUpdatedEvent : UserEvent { - public UserUpdatedEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) : base(userService, scriptEvaluator, localizer) - { - } + public UserUpdatedEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer localizer) + : base(userService, scriptEvaluator, localizer) { } public override string Name => nameof(UserUpdatedEvent); diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/ValidateUserTask.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/ValidateUserTask.cs index c3e66bda050..c891fa4f956 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/ValidateUserTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Activities/ValidateUserTask.cs @@ -58,10 +58,7 @@ public override ActivityExecutionResult Execute(WorkflowExecutionContext workflo if (Roles.Any()) { - var userRoleNames = user - .FindAll(c => c.Type == _roleClaimType) - .Select(c => c.Value) - .ToList(); + var userRoleNames = user.FindAll(c => c.Type == _roleClaimType).Select(c => c.Value).ToList(); foreach (var role in Roles) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/RegisterUserTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/RegisterUserTaskDisplayDriver.cs index c8122f1d794..2ec77cf6042 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/RegisterUserTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/RegisterUserTaskDisplayDriver.cs @@ -27,7 +27,7 @@ protected override void EditActivity(RegisterUserTask activity, RegisterUserTask model.RequireModeration = activity.RequireModeration; } - public async override Task UpdateAsync(RegisterUserTask model, IUpdateModel updater) + public override async Task UpdateAsync(RegisterUserTask model, IUpdateModel updater) { var viewModel = new RegisterUserTaskViewModel(); if (await updater.TryUpdateModelAsync(viewModel, Prefix)) @@ -41,12 +41,20 @@ public async override Task UpdateAsync(RegisterUserTask model, I { if (string.IsNullOrWhiteSpace(viewModel.ConfirmationEmailSubject)) { - updater.ModelState.AddModelError(Prefix, nameof(viewModel.ConfirmationEmailSubject), S["A value is required for {0}.", nameof(viewModel.ConfirmationEmailSubject)]); + updater.ModelState.AddModelError( + Prefix, + nameof(viewModel.ConfirmationEmailSubject), + S["A value is required for {0}.", nameof(viewModel.ConfirmationEmailSubject)] + ); } if (string.IsNullOrWhiteSpace(viewModel.ConfirmationEmailTemplate)) { - updater.ModelState.AddModelError(Prefix, nameof(viewModel.ConfirmationEmailTemplate), S["A value is required for {0}.", nameof(viewModel.ConfirmationEmailTemplate)]); + updater.ModelState.AddModelError( + Prefix, + nameof(viewModel.ConfirmationEmailTemplate), + S["A value is required for {0}.", nameof(viewModel.ConfirmationEmailTemplate)] + ); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserCreatedEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserCreatedEventDisplayDriver.cs index 6295207d109..5f61418ad5c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserCreatedEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserCreatedEventDisplayDriver.cs @@ -15,23 +15,22 @@ public UserCreatedEventDisplayDriver(IUserService userService) protected IUserService UserService { get; } - protected override void EditActivity(UserCreatedEvent source, UserCreatedEventViewModel target) - { - } + protected override void EditActivity(UserCreatedEvent source, UserCreatedEventViewModel target) { } public override IDisplayResult Display(UserCreatedEvent activity) { return Combine( Shape("UserCreatedEvent_Fields_Thumbnail", new UserCreatedEventViewModel(activity)).Location("Thumbnail", "Content"), - Factory("UserCreatedEvent_Fields_Design", ctx => - { - var shape = new UserCreatedEventViewModel - { - Activity = activity, - }; + Factory( + "UserCreatedEvent_Fields_Design", + ctx => + { + var shape = new UserCreatedEventViewModel { Activity = activity, }; - return shape; - }).Location("Design", "Content") + return shape; + } + ) + .Location("Design", "Content") ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserDeletedEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserDeletedEventDisplayDriver.cs index 700468be182..4cd218b2e2c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserDeletedEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserDeletedEventDisplayDriver.cs @@ -15,23 +15,22 @@ public UserDeletedEventDisplayDriver(IUserService userService) protected IUserService UserService { get; } - protected override void EditActivity(UserDeletedEvent source, UserDeletedEventViewModel target) - { - } + protected override void EditActivity(UserDeletedEvent source, UserDeletedEventViewModel target) { } public override IDisplayResult Display(UserDeletedEvent activity) { return Combine( Shape("UserDeletedEvent_Fields_Thumbnail", new UserDeletedEventViewModel(activity)).Location("Thumbnail", "Content"), - Factory("UserDeletedEvent_Fields_Design", ctx => - { - var shape = new UserDeletedEventViewModel - { - Activity = activity, - }; + Factory( + "UserDeletedEvent_Fields_Design", + ctx => + { + var shape = new UserDeletedEventViewModel { Activity = activity, }; - return shape; - }).Location("Design", "Content") + return shape; + } + ) + .Location("Design", "Content") ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserDisabledEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserDisabledEventDisplayDriver.cs index dbb5fd1e45d..f1f6bcc7aca 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserDisabledEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserDisabledEventDisplayDriver.cs @@ -15,23 +15,22 @@ public UserDisabledEventDisplayDriver(IUserService userService) protected IUserService UserService { get; } - protected override void EditActivity(UserDisabledEvent source, UserDisabledEventViewModel target) - { - } + protected override void EditActivity(UserDisabledEvent source, UserDisabledEventViewModel target) { } public override IDisplayResult Display(UserDisabledEvent activity) { return Combine( Shape("UserDisabledEvent_Fields_Thumbnail", new UserDisabledEventViewModel(activity)).Location("Thumbnail", "Content"), - Factory("UserDisabledEvent_Fields_Design", ctx => - { - var shape = new UserDisabledEventViewModel - { - Activity = activity, - }; + Factory( + "UserDisabledEvent_Fields_Design", + ctx => + { + var shape = new UserDisabledEventViewModel { Activity = activity, }; - return shape; - }).Location("Design", "Content") + return shape; + } + ) + .Location("Design", "Content") ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserEnabledEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserEnabledEventDisplayDriver.cs index 0fc0dcb3907..ce26dc3bf57 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserEnabledEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserEnabledEventDisplayDriver.cs @@ -15,23 +15,22 @@ public UserEnabledEventDisplayDriver(IUserService userService) protected IUserService UserService { get; } - protected override void EditActivity(UserEnabledEvent source, UserEnabledEventViewModel target) - { - } + protected override void EditActivity(UserEnabledEvent source, UserEnabledEventViewModel target) { } public override IDisplayResult Display(UserEnabledEvent activity) { return Combine( Shape("UserEnabledEvent_Fields_Thumbnail", new UserEnabledEventViewModel(activity)).Location("Thumbnail", "Content"), - Factory("UserEnabledEvent_Fields_Design", ctx => - { - var shape = new UserEnabledEventViewModel - { - Activity = activity, - }; + Factory( + "UserEnabledEvent_Fields_Design", + ctx => + { + var shape = new UserEnabledEventViewModel { Activity = activity, }; - return shape; - }).Location("Design", "Content") + return shape; + } + ) + .Location("Design", "Content") ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserLoggedInEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserLoggedInEventDisplayDriver.cs index 33c1ee62d34..b69cfd7a00e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserLoggedInEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserLoggedInEventDisplayDriver.cs @@ -15,23 +15,22 @@ public UserLoggedInEventDisplayDriver(IUserService userService) protected IUserService UserService { get; } - protected override void EditActivity(UserLoggedInEvent source, UserLoggedInEventViewModel target) - { - } + protected override void EditActivity(UserLoggedInEvent source, UserLoggedInEventViewModel target) { } public override IDisplayResult Display(UserLoggedInEvent activity) { return Combine( Shape("UserLoggedInEvent_Fields_Thumbnail", new UserLoggedInEventViewModel(activity)).Location("Thumbnail", "Content"), - Factory("UserLoggedInEvent_Fields_Design", ctx => - { - var shape = new UserLoggedInEventViewModel - { - Activity = activity, - }; + Factory( + "UserLoggedInEvent_Fields_Design", + ctx => + { + var shape = new UserLoggedInEventViewModel { Activity = activity, }; - return shape; - }).Location("Design", "Content") + return shape; + } + ) + .Location("Design", "Content") ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserUpdatedEventDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserUpdatedEventDisplayDriver.cs index 7ce74af6b21..b615db761c1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserUpdatedEventDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Drivers/UserUpdatedEventDisplayDriver.cs @@ -15,23 +15,22 @@ public UserUpdatedEventDisplayDriver(IUserService userService) protected IUserService UserService { get; } - protected override void EditActivity(UserUpdatedEvent source, UserUpdatedEventViewModel target) - { - } + protected override void EditActivity(UserUpdatedEvent source, UserUpdatedEventViewModel target) { } public override IDisplayResult Display(UserUpdatedEvent activity) { return Combine( Shape("UserUpdatedEvent_Fields_Thumbnail", new UserUpdatedEventViewModel(activity)).Location("Thumbnail", "Content"), - Factory("UserUpdatedEvent_Fields_Design", ctx => - { - var shape = new UserUpdatedEventViewModel - { - Activity = activity, - }; + Factory( + "UserUpdatedEvent_Fields_Design", + ctx => + { + var shape = new UserUpdatedEventViewModel { Activity = activity, }; - return shape; - }).Location("Design", "Content") + return shape; + } + ) + .Location("Design", "Content") ); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Handlers/UserEventHandler.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Handlers/UserEventHandler.cs index 1f5adc6cdc6..52a26872045 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Handlers/UserEventHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/Handlers/UserEventHandler.cs @@ -44,10 +44,7 @@ public override Task UpdatedAsync(UserUpdateContext context) private Task> TriggerWorkflowEventAsync(string name, User user) { - return _workflowManager.TriggerEventAsync(name, - input: new { User = user }, - correlationId: user.UserId - ); + return _workflowManager.TriggerEventAsync(name, input: new { User = user }, correlationId: user.UserId); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserCreatedEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserCreatedEventViewModel.cs index 1855a7fcea3..0fce68cc92b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserCreatedEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserCreatedEventViewModel.cs @@ -4,9 +4,7 @@ namespace OrchardCore.Users.Workflows.ViewModels { public class UserCreatedEventViewModel : UserEventViewModel { - public UserCreatedEventViewModel() - { - } + public UserCreatedEventViewModel() { } public UserCreatedEventViewModel(UserCreatedEvent activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserDeletedEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserDeletedEventViewModel.cs index 423cba9a38b..fcb67f9a38b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserDeletedEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserDeletedEventViewModel.cs @@ -4,9 +4,7 @@ namespace OrchardCore.Users.Workflows.ViewModels { public class UserDeletedEventViewModel : UserEventViewModel { - public UserDeletedEventViewModel() - { - } + public UserDeletedEventViewModel() { } public UserDeletedEventViewModel(UserDeletedEvent activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserDisabledEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserDisabledEventViewModel.cs index a29f2138dd4..a5e63926548 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserDisabledEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserDisabledEventViewModel.cs @@ -4,9 +4,7 @@ namespace OrchardCore.Users.Workflows.ViewModels { public class UserDisabledEventViewModel : UserEventViewModel { - public UserDisabledEventViewModel() - { - } + public UserDisabledEventViewModel() { } public UserDisabledEventViewModel(UserDisabledEvent activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserEnabledEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserEnabledEventViewModel.cs index c427fdca2fb..b47fa2cab1b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserEnabledEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserEnabledEventViewModel.cs @@ -4,9 +4,7 @@ namespace OrchardCore.Users.Workflows.ViewModels { public class UserEnabledEventViewModel : UserEventViewModel { - public UserEnabledEventViewModel() - { - } + public UserEnabledEventViewModel() { } public UserEnabledEventViewModel(UserEnabledEvent activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserEventViewModel.cs index bb9e8193f8e..7a865e18ad7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserEventViewModel.cs @@ -3,11 +3,10 @@ namespace OrchardCore.Users.Workflows.ViewModels { - public class UserEventViewModel : ActivityViewModel where T : UserEvent + public class UserEventViewModel : ActivityViewModel + where T : UserEvent { - public UserEventViewModel() - { - } + public UserEventViewModel() { } public UserEventViewModel(T activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserLoggedInEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserLoggedInEventViewModel.cs index 8fbdee9aff8..a5a7d11fa2e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserLoggedInEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserLoggedInEventViewModel.cs @@ -4,9 +4,7 @@ namespace OrchardCore.Users.Workflows.ViewModels { public class UserLoggedInEventViewModel : UserEventViewModel { - public UserLoggedInEventViewModel() - { - } + public UserLoggedInEventViewModel() { } public UserLoggedInEventViewModel(UserLoggedInEvent activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserUpdatedEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserUpdatedEventViewModel.cs index 3ef3005a35c..68803217f7b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserUpdatedEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Workflows/ViewModels/UserUpdatedEventViewModel.cs @@ -4,9 +4,7 @@ namespace OrchardCore.Users.Workflows.ViewModels { public class UserUpdatedEventViewModel : UserEventViewModel { - public UserUpdatedEventViewModel() - { - } + public UserUpdatedEventViewModel() { } public UserUpdatedEventViewModel(UserUpdatedEvent activity) { diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/ContentCardShapes.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/ContentCardShapes.cs index e52feb0c7dd..6e153ccb6c7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/ContentCardShapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/ContentCardShapes.cs @@ -16,7 +16,8 @@ public class ContentCardShapes : ShapeTableProvider public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe(ContentCardEdit) + builder + .Describe(ContentCardEdit) .OnDisplaying(context => { // Defines Edit Alternates for the Content Item being edited. @@ -75,7 +76,8 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe(ContentCardFrame) + builder + .Describe(ContentCardFrame) .OnDisplaying(context => { // Alternates for Outer Frame of ContentCard @@ -132,13 +134,14 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) } }); - builder.Describe(ContentCardFieldsEdit) - .OnDisplaying(context => - { - dynamic contentCardEditorFields = context.Shape; - var collectionType = contentCardEditorFields.CardShape.CollectionShapeType as string; - contentCardEditorFields.Metadata.Alternates.Add($"{collectionType}_Fields_Edit"); - }); + builder + .Describe(ContentCardFieldsEdit) + .OnDisplaying(context => + { + dynamic contentCardEditorFields = context.Shape; + var collectionType = contentCardEditorFields.CardShape.CollectionShapeType as string; + contentCardEditorFields.Metadata.Alternates.Add($"{collectionType}_Fields_Edit"); + }); return ValueTask.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/Controllers/AdminController.cs index 588be470081..f428824f4b9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/Controllers/AdminController.cs @@ -1,3 +1,4 @@ +using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using OrchardCore.Admin; using OrchardCore.ContentManagement; @@ -6,7 +7,6 @@ using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.Widgets.Models; using OrchardCore.Widgets.ViewModels; -using System.Threading.Tasks; namespace OrchardCore.Widgets.Controllers { @@ -22,7 +22,8 @@ public AdminController( IContentManager contentManager, IContentItemDisplayManager contentItemDisplayManager, IShapeFactory shapeFactory, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _contentItemDisplayManager = contentItemDisplayManager; _contentManager = contentManager; @@ -30,7 +31,18 @@ public AdminController( _updateModelAccessor = updateModelAccessor; } - public async Task BuildEditor(string id, string prefix, string prefixesName, string contentTypesName, string contentItemsName, string zonesName, string zone, string targetId, string parentContentType, string partName) + public async Task BuildEditor( + string id, + string prefix, + string prefixesName, + string contentTypesName, + string contentItemsName, + string zonesName, + string zone, + string targetId, + string parentContentType, + string partName + ) { if (string.IsNullOrWhiteSpace(id)) { @@ -76,10 +88,7 @@ public async Task BuildEditor(string id, string prefix, string pr ZonesName: zonesName ); - var model = new BuildEditorViewModel - { - EditorShape = contentCard - }; + var model = new BuildEditorViewModel { EditorShape = contentCard }; return View("Display", model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/Drivers/WidgetsListPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/Drivers/WidgetsListPartDisplayDriver.cs index bc36bbe9e50..4510326c5c4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/Drivers/WidgetsListPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/Drivers/WidgetsListPartDisplayDriver.cs @@ -22,11 +22,7 @@ public class WidgetsListPartDisplayDriver : ContentPartDisplayDriver DisplayAsync(WidgetsListPart part, Bu public override IDisplayResult Edit(WidgetsListPart widgetPart, BuildPartEditorContext context) { - return Initialize(GetEditorShapeType(context), async m => - { - var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(widgetPart.ContentItem.ContentType); - var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(p => p.PartDefinition.Name == nameof(WidgetsListPart)); - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + GetEditorShapeType(context), + async m => + { + var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(widgetPart.ContentItem.ContentType); + var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(p => p.PartDefinition.Name == nameof(WidgetsListPart)); + var settings = contentTypePartDefinition.GetSettings(); - m.AvailableZones = settings.Zones; + m.AvailableZones = settings.Zones; - m.WidgetsListPart = widgetPart; - m.Updater = context.Updater; - }); + m.WidgetsListPart = widgetPart; + m.Updater = context.Updater; + } + ); } public override async Task UpdateAsync(WidgetsListPart part, UpdatePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/Manifest.cs index 785bb131bf4..d65cc6e8b7e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/Manifest.cs @@ -1,11 +1,6 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "Widgets", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "Widgets", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.Widgets", diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/Migrations.cs index 0ff22328dc8..4a1276191e5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/Migrations.cs @@ -16,10 +16,10 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await _contentDefinitionManager.AlterPartDefinitionAsync("WidgetsListPart", builder => builder - .Attachable() - .WithDescription("Provides a way to add widgets to Layout zones for your content item.") - ); + await _contentDefinitionManager.AlterPartDefinitionAsync( + "WidgetsListPart", + builder => builder.Attachable().WithDescription("Provides a way to add widgets to Layout zones for your content item.") + ); return 1; } diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/Settings/WidgetsListPartSettingsDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/Settings/WidgetsListPartSettingsDisplayDriver.cs index 98e9c6539c6..431b4753d66 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/Settings/WidgetsListPartSettingsDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/Settings/WidgetsListPartSettingsDisplayDriver.cs @@ -14,13 +14,17 @@ public class WidgetsListPartSettingsDisplayDriver : ContentTypePartDefinitionDis public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater) { - return Initialize("WidgetsPartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + "WidgetsPartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); - model.Zones = string.Join(", ", settings.Zones); - model.WidgetsListPartSettings = settings; - }).Location("Content"); + model.Zones = string.Join(", ", settings.Zones); + model.WidgetsListPartSettings = settings; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/Startup.cs index 70f3ea8dc5d..adf121ea170 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/Startup.cs @@ -18,8 +18,7 @@ public override void ConfigureServices(IServiceCollection services) // Add Widget Card Shapes services.AddScoped(); // Widgets List Part - services.AddContentPart() - .UseDisplayDriver(); + services.AddContentPart().UseDisplayDriver(); services.AddScoped(); services.AddContentPart(); diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/CommitTransactionTask.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/CommitTransactionTask.cs index 3630c278dc2..d7a1be933a0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/CommitTransactionTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/CommitTransactionTask.cs @@ -14,10 +14,7 @@ public class CommitTransactionTask : TaskActivity private readonly IUpdateModelAccessor _updateModelAccessor; protected readonly IStringLocalizer S; - public CommitTransactionTask( - ISession session, - IUpdateModelAccessor updateModelAccessor, - IStringLocalizer localizer) + public CommitTransactionTask(ISession session, IUpdateModelAccessor updateModelAccessor, IStringLocalizer localizer) { _session = session; _updateModelAccessor = updateModelAccessor; diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/JoinTask.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/JoinTask.cs index 9c4d6be0f98..978d0baddb0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/JoinTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/JoinTask.cs @@ -78,6 +78,7 @@ public override ActivityExecutionResult Execute(WorkflowExecutionContext workflo return Noop(); } + public override Task OnActivityExecutedAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { // Get outbound transitions of the executing activity. diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/MissingActivity.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/MissingActivity.cs index 4d4155afadf..2eb9cd9aad6 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/MissingActivity.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/MissingActivity.cs @@ -36,7 +36,11 @@ public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContex public override ActivityExecutionResult Execute(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - _logger.LogWarning("Activity '{ActivityName}' is no longer available. This can happen if the feature providing the activity is no longer enabled. Either enable the feature, or remove this activity from workflow definition with ID {WorkflowTypeId}", MissingActivityRecord.Name, workflowContext.WorkflowType.Id); + _logger.LogWarning( + "Activity '{ActivityName}' is no longer available. This can happen if the feature providing the activity is no longer enabled. Either enable the feature, or remove this activity from workflow definition with ID {WorkflowTypeId}", + MissingActivityRecord.Name, + workflowContext.WorkflowType.Id + ); return Noop(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/NotifyTask.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/NotifyTask.cs index dfa40247cc9..c5484526ec4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/NotifyTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Activities/NotifyTask.cs @@ -17,11 +17,7 @@ public class NotifyTask : TaskActivity protected readonly IStringLocalizer S; private readonly HtmlEncoder _htmlEncoder; - public NotifyTask( - INotifier notifier, - IWorkflowExpressionEvaluator expressionEvaluator, - IStringLocalizer localizer, - HtmlEncoder htmlEncoder) + public NotifyTask(INotifier notifier, IWorkflowExpressionEvaluator expressionEvaluator, IStringLocalizer localizer, HtmlEncoder htmlEncoder) { _notifier = notifier; _expressionEvaluator = expressionEvaluator; diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/AdminMenu.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/AdminMenu.cs index 3d9534cbf08..c338beb7dec 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/AdminMenu.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/AdminMenu.cs @@ -20,14 +20,12 @@ public Task BuildNavigationAsync(string name, NavigationBuilder builder) return Task.CompletedTask; } - builder - .Add(S["Workflows"], NavigationConstants.AdminMenuWorkflowsPosition, workflow => workflow - .AddClass("workflows") - .Id("workflows") - .Action("Index", "WorkflowType", "OrchardCore.Workflows") - .Permission(Permissions.ManageWorkflows) - .LocalNav() - ); + builder.Add( + S["Workflows"], + NavigationConstants.AdminMenuWorkflowsPosition, + workflow => + workflow.AddClass("workflows").Id("workflows").Action("Index", "WorkflowType", "OrchardCore.Workflows").Permission(Permissions.ManageWorkflows).LocalNav() + ); return Task.CompletedTask; } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/ActivityController.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/ActivityController.cs index 7624fe8362c..bb7986af58f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/ActivityController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/ActivityController.cs @@ -26,8 +26,7 @@ public class ActivityController : Controller private readonly IUpdateModelAccessor _updateModelAccessor; protected readonly IHtmlLocalizer H; - public ActivityController - ( + public ActivityController( ISession session, IActivityLibrary activityLibrary, IWorkflowManager workflowManager, @@ -36,7 +35,8 @@ public ActivityController IActivityDisplayManager activityDisplayManager, INotifier notifier, IHtmlLocalizer h, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _session = session; _activityLibrary = activityLibrary; @@ -112,7 +112,9 @@ public async Task Create(string activityName, ActivityEditViewMod await _session.SaveAsync(workflowType); await _notifier.SuccessAsync(H["Activity added successfully."]); - return Url.IsLocalUrl(model.ReturnUrl) ? (IActionResult)this.Redirect(model.ReturnUrl, true) : RedirectToAction(nameof(Edit), "WorkflowType", new { id = model.WorkflowTypeId }); + return Url.IsLocalUrl(model.ReturnUrl) + ? (IActionResult)this.Redirect(model.ReturnUrl, true) + : RedirectToAction(nameof(Edit), "WorkflowType", new { id = model.WorkflowTypeId }); } [Admin("Workflows/Types/{workflowTypeId}/Activity/{activityId}/Edit", "EditActivity")] diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/WorkflowController.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/WorkflowController.cs index bdc6037d46d..4bf484d9cab 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/WorkflowController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/WorkflowController.cs @@ -59,7 +59,8 @@ public WorkflowController( IHtmlLocalizer htmlLocalizer, IDistributedLock distributedLock, IStringLocalizer stringLocalizer, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _pagerOptions = pagerOptions.Value; _session = session; @@ -91,8 +92,7 @@ public async Task Index(long workflowTypeId, WorkflowIndexViewMod var workflowType = await _workflowTypeStore.GetAsync(workflowTypeId); - var query = _session.QueryIndex() - .Where(x => x.WorkflowTypeId == workflowType.WorkflowTypeId); + var query = _session.QueryIndex().Where(x => x.WorkflowTypeId == workflowType.WorkflowTypeId); query = model.Options.Filter switch { @@ -149,22 +149,15 @@ public async Task Index(long workflowTypeId, WorkflowIndexViewMod new SelectListItem(S["Finished"], nameof(WorkflowFilter.Finished)), ]; - viewModel.Options.WorkflowsBulkAction = - [ - new SelectListItem(S["Delete"], nameof(WorkflowBulkAction.Delete)), - ]; + viewModel.Options.WorkflowsBulkAction = [new SelectListItem(S["Delete"], nameof(WorkflowBulkAction.Delete)),]; return View(viewModel); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(WorkflowIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { "Options.Filter", model.Options.Filter }, - { "Options.OrderBy", model.Options.OrderBy }, - }); + public ActionResult IndexFilterPOST(WorkflowIndexViewModel model) => + RedirectToAction(nameof(Index), new RouteValueDictionary { { "Options.Filter", model.Options.Filter }, { "Options.OrderBy", model.Options.OrderBy }, }); public async Task Details(long id) { @@ -189,7 +182,9 @@ public async Task Details(long id) foreach (var activityContext in activityContexts) { - activityDesignShapes.Add(await BuildActivityDisplayAsync(activityContext, workflowType.Id, blockingActivities.ContainsKey(activityContext.ActivityRecord.ActivityId), "Design")); + activityDesignShapes.Add( + await BuildActivityDisplayAsync(activityContext, workflowType.Id, blockingActivities.ContainsKey(activityContext.ActivityRecord.ActivityId), "Design") + ); } var activitiesDataQuery = activityContexts.Select(x => new @@ -327,7 +322,15 @@ public async Task BulkEdit(long workflowTypeId, WorkflowIndexOpti return BadRequest(); } } - return RedirectToAction(nameof(Index), new { workflowTypeId, pagenum = pagerParameters.Page, pagesize = pagerParameters.PageSize }); + return RedirectToAction( + nameof(Index), + new + { + workflowTypeId, + pagenum = pagerParameters.Page, + pagesize = pagerParameters.PageSize + } + ); } private async Task BuildActivityDisplayAsync(ActivityContext activityContext, long workflowTypeId, bool isBlocking, string displayType) diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/WorkflowTypeController.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/WorkflowTypeController.cs index f557944af70..08ff3388867 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/WorkflowTypeController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Controllers/WorkflowTypeController.cs @@ -48,8 +48,7 @@ public class WorkflowTypeController : Controller protected readonly IStringLocalizer S; protected readonly IHtmlLocalizer H; - public WorkflowTypeController - ( + public WorkflowTypeController( IOptions pagerOptions, ISession session, IActivityLibrary activityLibrary, @@ -63,7 +62,8 @@ public WorkflowTypeController ISecurityTokenService securityTokenService, IStringLocalizer stringLocalizer, IHtmlLocalizer htmlLocalizer, - IUpdateModelAccessor updateModelAccessor) + IUpdateModelAccessor updateModelAccessor + ) { _pagerOptions = pagerOptions.Value; _session = session; @@ -116,10 +116,7 @@ public async Task Index(WorkflowTypeIndexOptions options, PagerPa var count = await query.CountAsync(); - var workflowTypes = await query - .Skip(pager.GetStartIndex()) - .Take(pager.PageSize) - .ListAsync(); + var workflowTypes = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync(); using var connection = await _session.CreateConnectionAsync(); @@ -157,21 +154,15 @@ public async Task Index(WorkflowTypeIndexOptions options, PagerPa Pager = pagerShape, }; - model.Options.WorkflowTypesBulkAction = - [ - new SelectListItem(S["Delete"], nameof(WorkflowTypeBulkAction.Delete)), - ]; + model.Options.WorkflowTypesBulkAction = [new SelectListItem(S["Delete"], nameof(WorkflowTypeBulkAction.Delete)),]; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] - public ActionResult IndexFilterPOST(WorkflowTypeIndexViewModel model) - => RedirectToAction(nameof(Index), new RouteValueDictionary - { - { "Options.Search", model.Options.Search }, - }); + public ActionResult IndexFilterPOST(WorkflowTypeIndexViewModel model) => + RedirectToAction(nameof(Index), new RouteValueDictionary { { "Options.Search", model.Options.Search }, }); [HttpPost] [ActionName(nameof(Index))] @@ -185,8 +176,7 @@ public async Task BulkEdit(WorkflowTypeIndexOptions options, IEnu if (itemIds?.Count() > 0) { - var checkedEntries = await _session.Query() - .Where(x => x.DocumentId.IsIn(itemIds)).ListAsync(); + var checkedEntries = await _session.Query().Where(x => x.DocumentId.IsIn(itemIds)).ListAsync(); switch (options.BulkAction) { case WorkflowTypeBulkAction.None: @@ -221,27 +211,25 @@ public async Task EditProperties(long? id, string returnUrl = nul if (id == null) { - return View(new WorkflowTypePropertiesViewModel - { - IsEnabled = true, - ReturnUrl = returnUrl, - }); + return View(new WorkflowTypePropertiesViewModel { IsEnabled = true, ReturnUrl = returnUrl, }); } else { var workflowType = await _session.GetAsync(id.Value); - return View(new WorkflowTypePropertiesViewModel - { - Id = workflowType.Id, - Name = workflowType.Name, - IsEnabled = workflowType.IsEnabled, - IsSingleton = workflowType.IsSingleton, - LockTimeout = workflowType.LockTimeout, - LockExpiration = workflowType.LockExpiration, - DeleteFinishedWorkflows = workflowType.DeleteFinishedWorkflows, - ReturnUrl = returnUrl, - }); + return View( + new WorkflowTypePropertiesViewModel + { + Id = workflowType.Id, + Name = workflowType.Name, + IsEnabled = workflowType.IsEnabled, + IsSingleton = workflowType.IsSingleton, + LockTimeout = workflowType.LockTimeout, + LockExpiration = workflowType.LockExpiration, + DeleteFinishedWorkflows = workflowType.DeleteFinishedWorkflows, + ReturnUrl = returnUrl, + } + ); } } @@ -286,10 +274,7 @@ public async Task EditProperties(WorkflowTypePropertiesViewModel await _workflowTypeStore.SaveAsync(workflowType); return isNew - ? RedirectToAction(nameof(Edit), new - { - workflowType.Id, - }) + ? RedirectToAction(nameof(Edit), new { workflowType.Id, }) : Url.IsLocalUrl(viewModel.ReturnUrl) ? (IActionResult)this.Redirect(viewModel.ReturnUrl, true) : RedirectToAction(nameof(Index)); @@ -309,16 +294,18 @@ public async Task Duplicate(long id, string returnUrl = null) return NotFound(); } - return View(new WorkflowTypePropertiesViewModel - { - Id = id, - IsSingleton = workflowType.IsSingleton, - LockTimeout = workflowType.LockTimeout, - LockExpiration = workflowType.LockExpiration, - Name = "Copy-" + workflowType.Name, - IsEnabled = workflowType.IsEnabled, - ReturnUrl = returnUrl, - }); + return View( + new WorkflowTypePropertiesViewModel + { + Id = id, + IsSingleton = workflowType.IsSingleton, + LockTimeout = workflowType.LockTimeout, + LockExpiration = workflowType.LockExpiration, + Name = "Copy-" + workflowType.Name, + IsEnabled = workflowType.IsEnabled, + ReturnUrl = returnUrl, + } + ); } [HttpPost] @@ -349,10 +336,7 @@ public async Task Duplicate(WorkflowTypePropertiesViewModel viewM await _workflowTypeStore.SaveAsync(workflowType); - return RedirectToAction(nameof(Edit), new - { - workflowType.Id, - }); + return RedirectToAction(nameof(Edit), new { workflowType.Id, }); } public async Task Edit(long id, string localId) @@ -373,10 +357,8 @@ public async Task Edit(long id, string localId) var workflow = _workflowManager.NewWorkflow(workflowType); var workflowContext = await _workflowManager.CreateWorkflowExecutionContextAsync(workflowType, workflow); - var activityContexts = await Task.WhenAll(workflowType.Activities.Select(x => - _workflowManager.CreateActivityExecutionContextAsync(x, x.Properties))); - var workflowCount = await _session - .QueryIndex(x => x.WorkflowTypeId == workflowType.WorkflowTypeId).CountAsync(); + var activityContexts = await Task.WhenAll(workflowType.Activities.Select(x => _workflowManager.CreateActivityExecutionContextAsync(x, x.Properties))); + var workflowCount = await _session.QueryIndex(x => x.WorkflowTypeId == workflowType.WorkflowTypeId).CountAsync(); var activityThumbnailShapes = new List(); var index = 0; @@ -443,10 +425,7 @@ public async Task Edit(WorkflowTypeUpdateModel model) var activities = state["activities"] as JsonArray; var postedActivities = JArray.FromObject(activities).ToDictionary(x => x["id"]?.ToString()); - var removedActivityIdsQuery = - from activityId in currentActivities.Keys - where !postedActivities.ContainsKey(activityId) - select activityId; + var removedActivityIdsQuery = from activityId in currentActivities.Keys where !postedActivities.ContainsKey(activityId) select activityId; var removedActivityIds = removedActivityIdsQuery.ToList(); // Remove any orphans (activities deleted on the client). @@ -473,21 +452,20 @@ from activityId in currentActivities.Keys foreach (var transitionState in transitions) { - workflowType.Transitions.Add(new Transition - { - SourceActivityId = transitionState["sourceActivityId"]?.ToString(), - DestinationActivityId = transitionState["destinationActivityId"]?.ToString(), - SourceOutcomeName = transitionState["sourceOutcomeName"]?.ToString(), - }); + workflowType.Transitions.Add( + new Transition + { + SourceActivityId = transitionState["sourceActivityId"]?.ToString(), + DestinationActivityId = transitionState["destinationActivityId"]?.ToString(), + SourceOutcomeName = transitionState["sourceOutcomeName"]?.ToString(), + } + ); } await _workflowTypeStore.SaveAsync(workflowType); await _notifier.SuccessAsync(H["Workflow has been saved."]); - return RedirectToAction(nameof(Edit), new - { - id = model.Id, - }); + return RedirectToAction(nameof(Edit), new { id = model.Id, }); } [HttpPost] @@ -511,40 +489,27 @@ public async Task Delete(long id) return RedirectToAction(nameof(Index)); } - private async Task BuildActivityDisplay(IActivity activity, int index, long workflowTypeId, - string localId, string displayType) + private async Task BuildActivityDisplay(IActivity activity, int index, long workflowTypeId, string localId, string displayType) { - dynamic activityShape = - await _activityDisplayManager.BuildDisplayAsync(activity, _updateModelAccessor.ModelUpdater, - displayType); + dynamic activityShape = await _activityDisplayManager.BuildDisplayAsync(activity, _updateModelAccessor.ModelUpdater, displayType); activityShape.Metadata.Type = $"Activity_{displayType}"; activityShape.Activity = activity; activityShape.WorkflowTypeId = workflowTypeId; activityShape.Index = index; - activityShape.ReturnUrl = Url.Action(nameof(Edit), new - { - id = workflowTypeId, - localId, - }); + activityShape.ReturnUrl = Url.Action(nameof(Edit), new { id = workflowTypeId, localId, }); return activityShape; } - private async Task BuildActivityDisplay(ActivityContext activityContext, int index, long workflowTypeId, - string localId, string displayType) + private async Task BuildActivityDisplay(ActivityContext activityContext, int index, long workflowTypeId, string localId, string displayType) { - dynamic activityShape = await _activityDisplayManager.BuildDisplayAsync(activityContext.Activity, - _updateModelAccessor.ModelUpdater, displayType); + dynamic activityShape = await _activityDisplayManager.BuildDisplayAsync(activityContext.Activity, _updateModelAccessor.ModelUpdater, displayType); activityShape.Metadata.Type = $"Activity_{displayType}"; activityShape.Activity = activityContext.Activity; activityShape.ActivityRecord = activityContext.ActivityRecord; activityShape.WorkflowTypeId = workflowTypeId; activityShape.Index = index; - activityShape.ReturnUrl = Url.Action(nameof(Edit), new - { - id = workflowTypeId, - localId, - }); + activityShape.ReturnUrl = Url.Action(nameof(Edit), new { id = workflowTypeId, localId, }); return activityShape; } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Deployment/AllWorkflowTypeDeploymentSource.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Deployment/AllWorkflowTypeDeploymentSource.cs index 40e1bf881a5..a4ef75a3a41 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Deployment/AllWorkflowTypeDeploymentSource.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Deployment/AllWorkflowTypeDeploymentSource.cs @@ -24,11 +24,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan } var data = new JsonArray(); - result.Steps.Add(new JsonObject - { - ["name"] = "WorkflowType", - ["data"] = data, - }); + result.Steps.Add(new JsonObject { ["name"] = "WorkflowType", ["data"] = data, }); foreach (var workflow in await _workflowTypeStore.ListAsync()) { diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Deployment/AllWorkflowTypeDeploymentStepDriver.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Deployment/AllWorkflowTypeDeploymentStepDriver.cs index 272329f139f..2936bbebafe 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Deployment/AllWorkflowTypeDeploymentStepDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Deployment/AllWorkflowTypeDeploymentStepDriver.cs @@ -8,11 +8,10 @@ public class AllWorkflowTypeDeploymentStepDriver : DisplayDriver("ActivityMetadata_Edit", viewModel => - { - viewModel.Title = section.Title; - }).Location("Content:before"); + return Initialize( + "ActivityMetadata_Edit", + viewModel => + { + viewModel.Title = section.Title; + } + ) + .Location("Content:before"); } public override async Task UpdateAsync(ActivityMetadata section, IUpdateModel updater, BuildEditorContext context) diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Drivers/CommitTransactionTaskDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Drivers/CommitTransactionTaskDisplayDriver.cs index cbc61e242b9..d7c38e6d0dd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Drivers/CommitTransactionTaskDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Drivers/CommitTransactionTaskDisplayDriver.cs @@ -6,12 +6,8 @@ namespace OrchardCore.Workflows.Drivers { public class CommitTransactionTaskDisplayDriver : ActivityDisplayDriver { - protected override void EditActivity(CommitTransactionTask activity, CommitTransactionTaskViewModel model) - { - } + protected override void EditActivity(CommitTransactionTask activity, CommitTransactionTaskViewModel model) { } - protected override void UpdateActivity(CommitTransactionTaskViewModel model, CommitTransactionTask activity) - { - } + protected override void UpdateActivity(CommitTransactionTaskViewModel model, CommitTransactionTask activity) { } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Events/WorkflowFaultEvent.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Events/WorkflowFaultEvent.cs index 3278d98b4cc..00e282f54fc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Events/WorkflowFaultEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Events/WorkflowFaultEvent.cs @@ -13,9 +13,7 @@ public class WorkflowFaultEvent : EventActivity protected readonly IStringLocalizer S; private readonly IWorkflowScriptEvaluator _scriptEvaluator; - public WorkflowFaultEvent( - IStringLocalizer stringLocalizer, - IWorkflowScriptEvaluator scriptEvaluator) + public WorkflowFaultEvent(IStringLocalizer stringLocalizer, IWorkflowScriptEvaluator scriptEvaluator) { S = stringLocalizer; _scriptEvaluator = scriptEvaluator; @@ -56,7 +54,8 @@ public override async Task CanExecuteAsync(WorkflowExecutionContext workfl private static string GetDefaultValue() { - var sample = $@"//sample code + var sample = + $@"//sample code var errorInfo= input('{WorkflowFaultModel.WorkflowFaultInputKey}'); // This is where you define the workflow to intercept or specify the exception information var result= errorInfo.{nameof(WorkflowFaultModel.WorkflowName)}== 'WorkflowName' || diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Expressions/LiquidWorkflowExpressionEvaluator.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Expressions/LiquidWorkflowExpressionEvaluator.cs index 44112b3bedb..123620600a8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Expressions/LiquidWorkflowExpressionEvaluator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Expressions/LiquidWorkflowExpressionEvaluator.cs @@ -45,7 +45,7 @@ public async Task EvaluateAsync(WorkflowExpression expression, Workflow expression.Expression, encoder ?? NullEncoder.Default, new Dictionary() { ["Workflow"] = new ObjectValue(workflowContext) } - ); + ); return string.IsNullOrWhiteSpace(result) ? default : (T)Convert.ChangeType(result, typeof(T)); } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Handlers/DefaultWorkflowFaultHandler.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Handlers/DefaultWorkflowFaultHandler.cs index e854b9c0ae1..e7041cda6f7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Handlers/DefaultWorkflowFaultHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Handlers/DefaultWorkflowFaultHandler.cs @@ -9,11 +9,7 @@ namespace OrchardCore.Workflows.Handlers { public class DefaultWorkflowFaultHandler : IWorkflowFaultHandler { - public async Task OnWorkflowFaultAsync( - IWorkflowManager workflowManager, - WorkflowExecutionContext workflowContext, - ActivityContext activityContext, - Exception exception) + public async Task OnWorkflowFaultAsync(IWorkflowManager workflowManager, WorkflowExecutionContext workflowContext, ActivityContext activityContext, Exception exception) { var name = nameof(WorkflowFaultEvent); var faultContext = new WorkflowFaultModel() @@ -29,10 +25,7 @@ public async Task OnWorkflowFaultAsync( ErrorMessage = exception.Message, }; - var input = new Dictionary - { - { WorkflowFaultModel.WorkflowFaultInputKey, faultContext }, - }; + var input = new Dictionary { { WorkflowFaultModel.WorkflowFaultInputKey, faultContext }, }; await workflowManager.TriggerEventAsync(name, input); } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRedirectTask.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRedirectTask.cs index 6852ff62e73..8768d3cec0b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRedirectTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRedirectTask.cs @@ -17,11 +17,7 @@ public class HttpRedirectTask : TaskActivity private readonly IWorkflowExpressionEvaluator _expressionEvaluator; protected readonly IStringLocalizer S; - public HttpRedirectTask( - IStringLocalizer localizer, - IHttpContextAccessor httpContextAccessor, - IWorkflowExpressionEvaluator expressionEvaluator - ) + public HttpRedirectTask(IStringLocalizer localizer, IHttpContextAccessor httpContextAccessor, IWorkflowExpressionEvaluator expressionEvaluator) { S = localizer; _httpContextAccessor = httpContextAccessor; diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRequestEvent.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRequestEvent.cs index a1fdcec43cf..d97b4f07e9d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRequestEvent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRequestEvent.cs @@ -16,10 +16,7 @@ public class HttpRequestEvent : EventActivity private readonly IHttpContextAccessor _httpContextAccessor; protected readonly IStringLocalizer S; - public HttpRequestEvent( - IStringLocalizer localizer, - IHttpContextAccessor httpContextAccessor - ) + public HttpRequestEvent(IStringLocalizer localizer, IHttpContextAccessor httpContextAccessor) { S = localizer; _httpContextAccessor = httpContextAccessor; @@ -70,12 +67,13 @@ public override bool CanExecute(WorkflowExecutionContext workflowContext, Activi public override Task ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { - if (_httpContextAccessor.HttpContext.Request.HasFormContentType - && _httpContextAccessor.HttpContext.Request.Form.TryGetValue(WorkflowConstants.FormLocationKeyInputName, out var value) - && !string.IsNullOrWhiteSpace(value)) + if ( + _httpContextAccessor.HttpContext.Request.HasFormContentType + && _httpContextAccessor.HttpContext.Request.Form.TryGetValue(WorkflowConstants.FormLocationKeyInputName, out var value) + && !string.IsNullOrWhiteSpace(value) + ) { - if (!workflowContext.Output.TryGetValue(WorkflowConstants.HttpFormLocationOutputKeyName, out var obj) - || obj is not Dictionary formLocation) + if (!workflowContext.Output.TryGetValue(WorkflowConstants.HttpFormLocationOutputKeyName, out var obj) || obj is not Dictionary formLocation) { formLocation = []; } @@ -88,11 +86,9 @@ public override Task ExecuteAsync(WorkflowExecutionCont return Task.FromResult(Outcomes("Done")); } - public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) - => Outcomes(S["Done"]); + public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) => Outcomes(S["Done"]); - public override ActivityExecutionResult Resume(WorkflowExecutionContext workflowContext, ActivityContext activityContext) - => Outcomes("Done"); + public override ActivityExecutionResult Resume(WorkflowExecutionContext workflowContext, ActivityContext activityContext) => Outcomes("Done"); private static string GetLocationUrl(string value) { diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRequestTask.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRequestTask.cs index 8c52a8793cc..bcf2d693915 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRequestTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRequestTask.cs @@ -18,72 +18,73 @@ public class HttpRequestTask : TaskActivity { private static readonly string[] _separator = ["\r\n", "\n", "\r"]; - private static readonly Dictionary _httpStatusCodeDictionary = new() - { - { 100, "Continue" }, - { 101, "Switching Protocols" }, - { 102, "Processing" }, - { 200, "OK" }, - { 201, "Created" }, - { 202, "Accepted" }, - { 203, "Non-authoritative Information" }, - { 204, "No Content" }, - { 205, "Reset Content" }, - { 206, "Partial Content" }, - { 207, "Multi-Status" }, - { 208, "Already Reported" }, - { 226, "IM Used" }, - { 300, "Multiple Choices" }, - { 301, "Moved Permanently" }, - { 302, "Found" }, - { 303, "See Other" }, - { 304, "Not Modified" }, - { 305, "Use Proxy" }, - { 307, "Temporary Redirect" }, - { 308, "Permanent Redirect" }, - { 400, "Bad Request" }, - { 401, "Unauthorized" }, - { 402, "Payment Required" }, - { 403, "Forbidden" }, - { 404, "Not Found" }, - { 405, "Method Not Allowed" }, - { 406, "Not Acceptable" }, - { 407, "Proxy Authentication Required" }, - { 408, "Request Timeout" }, - { 409, "Conflict" }, - { 410, "Gone" }, - { 411, "Length Required" }, - { 412, "Precondition Failed" }, - { 413, "Payload Too Large" }, - { 414, "Request-URI Too Long" }, - { 415, "Unsupported Media Type" }, - { 416, "Requested Range Not Satisfiable" }, - { 417, "Expectation Failed" }, - { 418, "I'm a teapot" }, - { 421, "Misdirected Request" }, - { 422, "Unprocessable Entity" }, - { 423, "Locked" }, - { 424, "Failed Dependency" }, - { 426, "Upgrade Required" }, - { 428, "Precondition Required" }, - { 429, "Too Many Requests" }, - { 431, "Request Header Fields Too Large" }, - { 444, "Connection Closed Without Response" }, - { 451, "Unavailable For Legal Reasons" }, - { 499, "Client Closed Request" }, - { 500, "Internal Server Error" }, - { 501, "Not Implemented" }, - { 502, "Bad Gateway" }, - { 503, "Service Unavailable" }, - { 504, "Gateway Timeout" }, - { 505, "HTTP Version Not Supported" }, - { 506, "Variant Also Negotiates" }, - { 507, "Insufficient Storage" }, - { 508, "Loop Detected" }, - { 510, "Not Extended" }, - { 511, "Network Authentication Required" }, - { 599, "Network Connect Timeout Error" } - }; + private static readonly Dictionary _httpStatusCodeDictionary = + new() + { + { 100, "Continue" }, + { 101, "Switching Protocols" }, + { 102, "Processing" }, + { 200, "OK" }, + { 201, "Created" }, + { 202, "Accepted" }, + { 203, "Non-authoritative Information" }, + { 204, "No Content" }, + { 205, "Reset Content" }, + { 206, "Partial Content" }, + { 207, "Multi-Status" }, + { 208, "Already Reported" }, + { 226, "IM Used" }, + { 300, "Multiple Choices" }, + { 301, "Moved Permanently" }, + { 302, "Found" }, + { 303, "See Other" }, + { 304, "Not Modified" }, + { 305, "Use Proxy" }, + { 307, "Temporary Redirect" }, + { 308, "Permanent Redirect" }, + { 400, "Bad Request" }, + { 401, "Unauthorized" }, + { 402, "Payment Required" }, + { 403, "Forbidden" }, + { 404, "Not Found" }, + { 405, "Method Not Allowed" }, + { 406, "Not Acceptable" }, + { 407, "Proxy Authentication Required" }, + { 408, "Request Timeout" }, + { 409, "Conflict" }, + { 410, "Gone" }, + { 411, "Length Required" }, + { 412, "Precondition Failed" }, + { 413, "Payload Too Large" }, + { 414, "Request-URI Too Long" }, + { 415, "Unsupported Media Type" }, + { 416, "Requested Range Not Satisfiable" }, + { 417, "Expectation Failed" }, + { 418, "I'm a teapot" }, + { 421, "Misdirected Request" }, + { 422, "Unprocessable Entity" }, + { 423, "Locked" }, + { 424, "Failed Dependency" }, + { 426, "Upgrade Required" }, + { 428, "Precondition Required" }, + { 429, "Too Many Requests" }, + { 431, "Request Header Fields Too Large" }, + { 444, "Connection Closed Without Response" }, + { 451, "Unavailable For Legal Reasons" }, + { 499, "Client Closed Request" }, + { 500, "Internal Server Error" }, + { 501, "Not Implemented" }, + { 502, "Bad Gateway" }, + { 503, "Service Unavailable" }, + { 504, "Gateway Timeout" }, + { 505, "HTTP Version Not Supported" }, + { 506, "Variant Also Negotiates" }, + { 507, "Insufficient Storage" }, + { 508, "Loop Detected" }, + { 510, "Not Extended" }, + { 511, "Network Authentication Required" }, + { 599, "Network Connect Timeout Error" } + }; private readonly IWorkflowExpressionEvaluator _expressionEvaluator; private readonly IHttpClientFactory _httpClientFactory; @@ -147,17 +148,17 @@ public string HttpResponseCodes public override IEnumerable GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { var outcomes = !string.IsNullOrWhiteSpace(HttpResponseCodes) - ? HttpResponseCodes.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => - { - var status = int.Parse(x.Trim()); + ? HttpResponseCodes + .Split(',', StringSplitOptions.RemoveEmptyEntries) + .Select(x => + { + var status = int.Parse(x.Trim()); - var description = _httpStatusCodeDictionary.TryGetValue(status, out var text) - ? $"{status} {text}" - : status.ToString() - ; + var description = _httpStatusCodeDictionary.TryGetValue(status, out var text) ? $"{status} {text}" : status.ToString(); - return new Outcome(status.ToString(), new LocalizedString(description, description)); - }).ToList() + return new Outcome(status.ToString(), new LocalizedString(description, description)); + }) + .ToList() : []; outcomes.Add(new Outcome("UnhandledHttpStatus", S["Unhandled Http Status"])); @@ -211,8 +212,7 @@ private static IEnumerable> ParseHeaders(string tex return []; } - return - from header in text.Split(_separator, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()) + return from header in text.Split(_separator, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()) let pair = header.Split(':', 2) where pair.Length == 2 select new KeyValuePair(pair[0], pair[1]); @@ -220,9 +220,7 @@ from header in text.Split(_separator, StringSplitOptions.RemoveEmptyEntries).Sel private static IEnumerable ParseResponseCodes(string text) { - return - from code in text.Split(',', StringSplitOptions.RemoveEmptyEntries) - select int.Parse(code); + return from code in text.Split(',', StringSplitOptions.RemoveEmptyEntries) select int.Parse(code); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpResponseTask.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpResponseTask.cs index 272dcbd8aee..9a00a3e884d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpResponseTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpResponseTask.cs @@ -104,8 +104,7 @@ private static IEnumerable> ParseHeaders(stri return []; } - return - from header in text.Split(_separator, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()) + return from header in text.Split(_separator, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()) let pair = header.Split(':') where pair.Length == 2 select new KeyValuePair(pair[0], pair[1]); diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Controllers/HttpWorkflowController.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Controllers/HttpWorkflowController.cs index b0810114202..f0b88b44fa4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Controllers/HttpWorkflowController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Controllers/HttpWorkflowController.cs @@ -67,7 +67,10 @@ public async Task GenerateUrl(long workflowTypeId, string activit return NotFound(); } - var token = _securityTokenService.CreateToken(new WorkflowPayload(workflowType.WorkflowTypeId, activityId), TimeSpan.FromDays(tokenLifeSpan == 0 ? NoExpiryTokenLifespan : tokenLifeSpan)); + var token = _securityTokenService.CreateToken( + new WorkflowPayload(workflowType.WorkflowTypeId, activityId), + TimeSpan.FromDays(tokenLifeSpan == 0 ? NoExpiryTokenLifespan : tokenLifeSpan) + ); var url = Url.Action("Invoke", "HttpWorkflow", new { token }); return Ok(url); @@ -153,7 +156,11 @@ public async Task Invoke(string token) { if (_logger.IsEnabled(LogLevel.Debug)) { - _logger.LogDebug("Invoking new workflow of type '{WorkflowTypeId}' with start activity '{ActivityId}'", workflowType.WorkflowTypeId, startActivity.ActivityId); + _logger.LogDebug( + "Invoking new workflow of type '{WorkflowTypeId}' with start activity '{ActivityId}'", + workflowType.WorkflowTypeId, + startActivity.ActivityId + ); } await _workflowManager.StartWorkflowAsync(workflowType, startActivity); diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Filters/WorkflowActionFilter.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Filters/WorkflowActionFilter.cs index b6b5bbf71bb..f45bc1b1464 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Filters/WorkflowActionFilter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Filters/WorkflowActionFilter.cs @@ -84,9 +84,7 @@ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionE foreach (var entry in workflowEntries) { - if (workflows.TryGetValue(entry.WorkflowId, out var workflow) && - (string.IsNullOrWhiteSpace(correlationId) || - workflow.CorrelationId == correlationId)) + if (workflows.TryGetValue(entry.WorkflowId, out var workflow) && (string.IsNullOrWhiteSpace(correlationId) || workflow.CorrelationId == correlationId)) { // If atomic, try to acquire a lock per workflow instance. (var locker, var locked) = await _distributedLock.TryAcquireWorkflowLockAsync(workflow); diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Handlers/WorkflowRoutesHandler.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Handlers/WorkflowRoutesHandler.cs index c3bbce71893..e1fea623e0e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Handlers/WorkflowRoutesHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Handlers/WorkflowRoutesHandler.cs @@ -11,11 +11,7 @@ internal class WorkflowRoutesHandler : WorkflowHandlerBase private readonly IWorkflowTypeStore _workflowTypeStore; private readonly IActivityLibrary _activityLibrary; - public WorkflowRoutesHandler( - IWorkflowInstanceRouteEntries workflowRouteEntries, - IWorkflowTypeStore workflowTypeStore, - IActivityLibrary activityLibrary - ) + public WorkflowRoutesHandler(IWorkflowInstanceRouteEntries workflowRouteEntries, IWorkflowTypeStore workflowTypeStore, IActivityLibrary activityLibrary) { _workflowRouteEntries = workflowRouteEntries; _workflowTypeStore = workflowTypeStore; diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Models/WorkflowTypeRouteDocument.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Models/WorkflowTypeRouteDocument.cs index d4c7c1bb638..75e4d26aa8a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Models/WorkflowTypeRouteDocument.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Models/WorkflowTypeRouteDocument.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Workflows.Http.Models { - public class WorkflowTypeRouteDocument : WorkflowRouteDocument - { - } + public class WorkflowTypeRouteDocument : WorkflowRouteDocument { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Scripting/HttpMethodsProvider.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Scripting/HttpMethodsProvider.cs index 5362619ca97..b9b062f1a89 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Scripting/HttpMethodsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Scripting/HttpMethodsProvider.cs @@ -30,43 +30,42 @@ public class HttpMethodsProvider : IGlobalMethodProvider public HttpMethodsProvider(IHttpContextAccessor httpContextAccessor) { - _httpContextMethod = new GlobalMethod - { - Name = "httpContext", - Method = serviceProvider => (Func)(() => httpContextAccessor.HttpContext), - }; + _httpContextMethod = new GlobalMethod { Name = "httpContext", Method = serviceProvider => (Func)(() => httpContextAccessor.HttpContext), }; _queryStringMethod = new GlobalMethod { Name = "queryString", - Method = serviceProvider => (Func)(name => - { - if (name == null) - { - return httpContextAccessor.HttpContext.Request.QueryString.ToString(); - } - object result; - if (httpContextAccessor.HttpContext.Request.Query.TryGetValue(name, out var values)) - { - if (values.Count == 0) + Method = serviceProvider => + (Func)( + name => { - result = null; - } - else if (values.Count == 1) - { - result = values[0]; - } - else - { - result = values.ToArray(); + if (name == null) + { + return httpContextAccessor.HttpContext.Request.QueryString.ToString(); + } + object result; + if (httpContextAccessor.HttpContext.Request.Query.TryGetValue(name, out var values)) + { + if (values.Count == 0) + { + result = null; + } + else if (values.Count == 1) + { + result = values[0]; + } + else + { + result = values.ToArray(); + } + } + else + { + result = null; + } + return result; } - } - else - { - result = null; - } - return result; - }), + ), }; _responseWriteMethod = new GlobalMethod @@ -78,143 +77,151 @@ public HttpMethodsProvider(IHttpContextAccessor httpContextAccessor) _absoluteUrlMethod = new GlobalMethod { Name = "absoluteUrl", - Method = serviceProvider => (Func)(relativePath => - { - var urlHelperFactory = serviceProvider.GetRequiredService(); - var urlHelper = urlHelperFactory.GetUrlHelper(new ActionContext(httpContextAccessor.HttpContext, new RouteData(), new ActionDescriptor())); - return urlHelper.ToAbsoluteUrl(relativePath); - }), + Method = serviceProvider => + (Func)( + relativePath => + { + var urlHelperFactory = serviceProvider.GetRequiredService(); + var urlHelper = urlHelperFactory.GetUrlHelper(new ActionContext(httpContextAccessor.HttpContext, new RouteData(), new ActionDescriptor())); + return urlHelper.ToAbsoluteUrl(relativePath); + } + ), }; _readBodyMethod = new GlobalMethod { Name = "readBody", - Method = serviceProvider => (Func)(() => - { - using var sr = new StreamReader(httpContextAccessor.HttpContext.Request.Body); + Method = serviceProvider => + (Func)( + () => + { + using var sr = new StreamReader(httpContextAccessor.HttpContext.Request.Body); - // Async read of the request body is mandatory. - return sr.ReadToEndAsync().GetAwaiter().GetResult(); - }), + // Async read of the request body is mandatory. + return sr.ReadToEndAsync().GetAwaiter().GetResult(); + } + ), }; _requestFormMethod = new GlobalMethod { Name = "requestForm", - Method = serviceProvider => (Func)(field => - { - object result; - if (httpContextAccessor.HttpContext.Request.Form.TryGetValue(field, out var values)) - { - if (values.Count == 0) - { - result = null; - } - else if (values.Count == 1) - { - result = values[0]; - } - else + Method = serviceProvider => + (Func)( + field => { - result = values.ToArray(); + object result; + if (httpContextAccessor.HttpContext.Request.Form.TryGetValue(field, out var values)) + { + if (values.Count == 0) + { + result = null; + } + else if (values.Count == 1) + { + result = values[0]; + } + else + { + result = values.ToArray(); + } + } + else + { + result = null; + } + return result; } - } - else - { - result = null; - } - return result; - }), + ), }; // This should be deprecated - _queryStringAsJsonMethod = new GlobalMethod - { - Name = "queryStringAsJson", - Method = serviceProvider => _deserializeRequestDataMethod.Method.Invoke(serviceProvider), - }; + _queryStringAsJsonMethod = new GlobalMethod { Name = "queryStringAsJson", Method = serviceProvider => _deserializeRequestDataMethod.Method.Invoke(serviceProvider), }; // This should be deprecated - _requestFormAsJsonMethod = new GlobalMethod - { - Name = "requestFormAsJson", - Method = serviceProvider => _deserializeRequestDataMethod.Method.Invoke(serviceProvider), - }; + _requestFormAsJsonMethod = new GlobalMethod { Name = "requestFormAsJson", Method = serviceProvider => _deserializeRequestDataMethod.Method.Invoke(serviceProvider), }; _deserializeRequestDataMethod = new GlobalMethod { Name = "deserializeRequestData", - Method = serviceProvider => (Func>)(() => - { - Dictionary result = null; - - if (httpContextAccessor.HttpContext != null) - { - var method = httpContextAccessor.HttpContext.Request.Method; - if (method.Equals("POST", StringComparison.OrdinalIgnoreCase) || method.Equals("PUT", StringComparison.OrdinalIgnoreCase) || method.Equals("PATCH", StringComparison.OrdinalIgnoreCase)) + Method = serviceProvider => + (Func>)( + () => { - if (httpContextAccessor.HttpContext.Request.HasFormContentType) - { - var formData = httpContextAccessor.HttpContext.Request.Form; + Dictionary result = null; - // If we can parse first request form element key as JSON then we throw - if (isValidJSON(formData.First().Key.ToString())) + if (httpContextAccessor.HttpContext != null) + { + var method = httpContextAccessor.HttpContext.Request.Method; + if ( + method.Equals("POST", StringComparison.OrdinalIgnoreCase) + || method.Equals("PUT", StringComparison.OrdinalIgnoreCase) + || method.Equals("PATCH", StringComparison.OrdinalIgnoreCase) + ) { - throw new Exception("Invalid form data passed in the request. The data passed was JSON while it should be form data."); - } + if (httpContextAccessor.HttpContext.Request.HasFormContentType) + { + var formData = httpContextAccessor.HttpContext.Request.Form; - try - { - result = formData.ToDictionary(x => x.Key, x => (object)x.Value); - } - catch - { - throw new Exception("Invalid form data passed in the request."); + // If we can parse first request form element key as JSON then we throw + if (isValidJSON(formData.First().Key.ToString())) + { + throw new Exception("Invalid form data passed in the request. The data passed was JSON while it should be form data."); + } + + try + { + result = formData.ToDictionary(x => x.Key, x => (object)x.Value); + } + catch + { + throw new Exception("Invalid form data passed in the request."); + } + } + else if (httpContextAccessor.HttpContext.Request.HasJsonContentType()) + { + string json; + using (var sr = new StreamReader(httpContextAccessor.HttpContext.Request.Body)) + { + // Async read of the request body is mandatory. + json = sr.ReadToEndAsync().GetAwaiter().GetResult(); + } + + try + { + result = JConvert.DeserializeObject>(json); + } + catch + { + throw new Exception("Invalid JSON passed in the request."); + } + } } - } - else if (httpContextAccessor.HttpContext.Request.HasJsonContentType()) - { - string json; - using (var sr = new StreamReader(httpContextAccessor.HttpContext.Request.Body)) + else if (httpContextAccessor.HttpContext.Request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase)) { - // Async read of the request body is mandatory. - json = sr.ReadToEndAsync().GetAwaiter().GetResult(); - } + var queryData = httpContextAccessor.HttpContext.Request.Query; - try - { - result = JConvert.DeserializeObject>(json); + try + { + result = queryData.ToDictionary(x => x.Key, x => (object)x.Value); + + // We never need to keep the Workflow token + result.Remove("token"); + } + catch + { + throw new Exception("Invalid query string data passed in the request."); + } } - catch + else { - throw new Exception("Invalid JSON passed in the request."); + throw new Exception("The request method is not supported"); } } - } - else if (httpContextAccessor.HttpContext.Request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase)) - { - var queryData = httpContextAccessor.HttpContext.Request.Query; - - try - { - result = queryData.ToDictionary(x => x.Key, x => (object)x.Value); - // We never need to keep the Workflow token - result.Remove("token"); - } - catch - { - throw new Exception("Invalid query string data passed in the request."); - } - } - else - { - throw new Exception("The request method is not supported"); + return result; } - } - - return result; - }), + ), }; } @@ -233,7 +240,18 @@ private static bool isValidJSON(string json) public IEnumerable GetMethods() { - return new[] { _httpContextMethod, _queryStringMethod, _responseWriteMethod, _absoluteUrlMethod, _readBodyMethod, _requestFormMethod, _queryStringAsJsonMethod, _requestFormAsJsonMethod, _deserializeRequestDataMethod }; + return new[] + { + _httpContextMethod, + _queryStringMethod, + _responseWriteMethod, + _absoluteUrlMethod, + _readBodyMethod, + _requestFormMethod, + _queryStringAsJsonMethod, + _requestFormAsJsonMethod, + _deserializeRequestDataMethod + }; } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Scripting/SignalMethodProvider.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Scripting/SignalMethodProvider.cs index 4c4312c5046..8f0d2dd74d9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Scripting/SignalMethodProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Scripting/SignalMethodProvider.cs @@ -20,15 +20,20 @@ public SignalMethodProvider(WorkflowExecutionContext workflowContext, ISecurityT _signalUrlMethod = new GlobalMethod { Name = "signalUrl", - Method = serviceProvider => (Func)((signal) => - { - var payload = !string.IsNullOrWhiteSpace(workflowContext.CorrelationId) ? SignalPayload.ForCorrelation(signal, workflowContext.CorrelationId) : SignalPayload.ForWorkflow(signal, workflowContext.WorkflowId); - var token = securityTokenService.CreateToken(payload, TimeSpan.FromDays(7)); - var httpContextAccessor = serviceProvider.GetRequiredService(); - var linkGenerator = serviceProvider.GetRequiredService(); + Method = serviceProvider => + (Func)( + (signal) => + { + var payload = !string.IsNullOrWhiteSpace(workflowContext.CorrelationId) + ? SignalPayload.ForCorrelation(signal, workflowContext.CorrelationId) + : SignalPayload.ForWorkflow(signal, workflowContext.WorkflowId); + var token = securityTokenService.CreateToken(payload, TimeSpan.FromDays(7)); + var httpContextAccessor = serviceProvider.GetRequiredService(); + var linkGenerator = serviceProvider.GetRequiredService(); - return linkGenerator.GetPathByAction(httpContextAccessor.HttpContext, "Trigger", "HttpWorkflow", new { area = "OrchardCore.Workflows", token }); - }), + return linkGenerator.GetPathByAction(httpContextAccessor.HttpContext, "Trigger", "HttpWorkflow", new { area = "OrchardCore.Workflows", token }); + } + ), }; } @@ -47,19 +52,22 @@ public TokenMethodProvider() _createWorkflowToken = new GlobalMethod { Name = "createWorkflowToken", - Method = serviceProvider => (Func)((workflowTypeId, activityId, days) => - { - var securityTokenService = serviceProvider.GetRequiredService(); + Method = serviceProvider => + (Func)( + (workflowTypeId, activityId, days) => + { + var securityTokenService = serviceProvider.GetRequiredService(); - var payload = new WorkflowPayload(workflowTypeId, activityId); + var payload = new WorkflowPayload(workflowTypeId, activityId); - if (days == 0) - { - days = HttpWorkflowController.NoExpiryTokenLifespan; - } + if (days == 0) + { + days = HttpWorkflowController.NoExpiryTokenLifespan; + } - return securityTokenService.CreateToken(payload, TimeSpan.FromDays(days)); - }) + return securityTokenService.CreateToken(payload, TimeSpan.FromDays(days)); + } + ) }; } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/IWorkflowInstanceRouteEntries.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/IWorkflowInstanceRouteEntries.cs index 340891794ad..5e87e45655f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/IWorkflowInstanceRouteEntries.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/IWorkflowInstanceRouteEntries.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Workflows.Http.Services { - internal interface IWorkflowInstanceRouteEntries : IWorkflowRouteEntries - { - } + internal interface IWorkflowInstanceRouteEntries : IWorkflowRouteEntries { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/IWorkflowTypeRouteEntries.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/IWorkflowTypeRouteEntries.cs index 3bc9be03043..d6273f70e30 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/IWorkflowTypeRouteEntries.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/IWorkflowTypeRouteEntries.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Workflows.Http.Services { - internal interface IWorkflowTypeRouteEntries : IWorkflowRouteEntries - { - } + internal interface IWorkflowTypeRouteEntries : IWorkflowRouteEntries { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowInstanceRouteEntries.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowInstanceRouteEntries.cs index 448a9973786..cac19c622b9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowInstanceRouteEntries.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowInstanceRouteEntries.cs @@ -13,7 +13,8 @@ namespace OrchardCore.Workflows.Http.Services { internal class WorkflowInstanceRouteEntries : WorkflowRouteEntries, IWorkflowInstanceRouteEntries { - public WorkflowInstanceRouteEntries(IVolatileDocumentManager documentManager) : base(documentManager) { } + public WorkflowInstanceRouteEntries(IVolatileDocumentManager documentManager) + : base(documentManager) { } protected override async Task CreateDocumentAsync() { @@ -26,8 +27,7 @@ protected override async Task CreateDocumentAsync() while (true) { var pendingWorkflows = await Session - .Query(index => - index.ActivityName == HttpRequestFilterEvent.EventName) + .Query(index => index.ActivityName == HttpRequestFilterEvent.EventName) .Skip(skip) .Take(pageSize) .ListAsync(); @@ -58,19 +58,21 @@ from entry in GetWorkflowRoutesEntries(workflowTypeDictionary[workflow.WorkflowT internal static IEnumerable GetWorkflowRoutesEntries(WorkflowType workflowType, Workflow workflow, IActivityLibrary activityLibrary) { var awaitingActivityIds = workflow.BlockingActivities.Select(x => x.ActivityId).ToDictionary(x => x); - return workflowType.Activities.Where(x => x.Name == HttpRequestFilterEvent.EventName && awaitingActivityIds.ContainsKey(x.ActivityId)).Select(x => - { - var activity = activityLibrary.InstantiateActivity(x); - var entry = new WorkflowRoutesEntry + return workflowType + .Activities.Where(x => x.Name == HttpRequestFilterEvent.EventName && awaitingActivityIds.ContainsKey(x.ActivityId)) + .Select(x => { - WorkflowId = workflow.WorkflowId, - ActivityId = x.ActivityId, - HttpMethod = activity.HttpMethod, - RouteValues = activity.RouteValues, - }; + var activity = activityLibrary.InstantiateActivity(x); + var entry = new WorkflowRoutesEntry + { + WorkflowId = workflow.WorkflowId, + ActivityId = x.ActivityId, + HttpMethod = activity.HttpMethod, + RouteValues = activity.RouteValues, + }; - return entry; - }); + return entry; + }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowRouteEntriesOfT.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowRouteEntriesOfT.cs index 87eab3f38f6..6de894442cb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowRouteEntriesOfT.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowRouteEntriesOfT.cs @@ -12,7 +12,8 @@ namespace OrchardCore.Workflows.Http.Services { - internal class WorkflowRouteEntries : IWorkflowRouteEntries where TWorkflowRouteDocument : WorkflowRouteDocument, new() + internal class WorkflowRouteEntries : IWorkflowRouteEntries + where TWorkflowRouteDocument : WorkflowRouteDocument, new() { private readonly IVolatileDocumentManager _documentManager; @@ -47,11 +48,14 @@ protected virtual IEnumerable GetWorkflowRoutesEntries(Work var actionName = routeValues.GetValue("action"); var areaName = routeValues.GetValue("area"); - return document.Entries.Values.SelectMany(x => x).Where(x => - x.HttpMethod == httpMethod && - (x.ControllerName == controllerName || string.IsNullOrWhiteSpace(x.ControllerName)) && - (x.ActionName == actionName || string.IsNullOrWhiteSpace(x.ActionName)) && - (x.AreaName == areaName || string.IsNullOrWhiteSpace(x.AreaName))) + return document + .Entries.Values.SelectMany(x => x) + .Where(x => + x.HttpMethod == httpMethod + && (x.ControllerName == controllerName || string.IsNullOrWhiteSpace(x.ControllerName)) + && (x.ActionName == actionName || string.IsNullOrWhiteSpace(x.ActionName)) + && (x.AreaName == areaName || string.IsNullOrWhiteSpace(x.AreaName)) + ) .ToArray(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowTypeRouteEntries.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowTypeRouteEntries.cs index 411be37c280..74bdcf4a4bc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowTypeRouteEntries.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Services/WorkflowTypeRouteEntries.cs @@ -13,7 +13,8 @@ namespace OrchardCore.Workflows.Http.Services { internal class WorkflowTypeRouteEntries : WorkflowRouteEntries, IWorkflowTypeRouteEntries { - public WorkflowTypeRouteEntries(IVolatileDocumentManager documentManager) : base(documentManager) { } + public WorkflowTypeRouteEntries(IVolatileDocumentManager documentManager) + : base(documentManager) { } protected override async Task CreateDocumentAsync() { @@ -32,19 +33,21 @@ from entry in GetWorkflowTypeRoutesEntries(workflowType, ActivityLibrary) internal static IEnumerable GetWorkflowTypeRoutesEntries(WorkflowType workflowType, IActivityLibrary activityLibrary) { - return workflowType.Activities.Where(x => x.IsStart && x.Name == HttpRequestFilterEvent.EventName).Select(x => - { - var activity = activityLibrary.InstantiateActivity(x); - var entry = new WorkflowRoutesEntry + return workflowType + .Activities.Where(x => x.IsStart && x.Name == HttpRequestFilterEvent.EventName) + .Select(x => { - WorkflowId = workflowType.Id.ToString(), - ActivityId = x.ActivityId, - HttpMethod = activity.HttpMethod, - RouteValues = activity.RouteValues - }; + var activity = activityLibrary.InstantiateActivity(x); + var entry = new WorkflowRoutesEntry + { + WorkflowId = workflowType.Id.ToString(), + ActivityId = x.ActivityId, + HttpMethod = activity.HttpMethod, + RouteValues = activity.RouteValues + }; - return entry; - }); + return entry; + }); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Startup.cs index 01055854428..94910393887 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/Startup.cs @@ -53,12 +53,7 @@ public override void ConfigureServices(IServiceCollection services) public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { - routes.MapAreaControllerRoute( - name: "HttpWorkflow", - areaName: "OrchardCore.Workflows", - pattern: "workflows/{action}", - defaults: new { controller = "HttpWorkflow" } - ); + routes.MapAreaControllerRoute(name: "HttpWorkflow", areaName: "OrchardCore.Workflows", pattern: "workflows/{action}", defaults: new { controller = "HttpWorkflow" }); routes.MapAreaControllerRoute( name: "InvokeWorkflow", diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/ViewModels/HttpRequestEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/ViewModels/HttpRequestEventViewModel.cs index 50a637e2bf3..25a9ec803b5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/ViewModels/HttpRequestEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/ViewModels/HttpRequestEventViewModel.cs @@ -6,15 +6,7 @@ namespace OrchardCore.Workflows.Http.ViewModels { public class HttpRequestEventViewModel { - private static readonly IEnumerable _availableHttpMethods = new[] - { - "GET", - "POST", - "PUT", - "PATCH", - "DELETE", - "OPTIONS" - }; + private static readonly IEnumerable _availableHttpMethods = new[] { "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS" }; public string HttpMethod { get; set; } @@ -26,7 +18,6 @@ public class HttpRequestEventViewModel public string FormLocationKey { get; set; } - public static IList GetAvailableHttpMethods() - => _availableHttpMethods.Select(x => new SelectListItem { Text = x, Value = x }).ToList(); + public static IList GetAvailableHttpMethods() => _availableHttpMethods.Select(x => new SelectListItem { Text = x, Value = x }).ToList(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/ViewModels/HttpRequestFilterEventViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/ViewModels/HttpRequestFilterEventViewModel.cs index c9244f818dc..70d8915c59f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Http/ViewModels/HttpRequestFilterEventViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Http/ViewModels/HttpRequestFilterEventViewModel.cs @@ -10,6 +10,7 @@ public class HttpRequestFilterEventViewModel public string ControllerName { get; set; } public string ActionName { get; set; } public string AreaName { get; set; } + // TODO: Add support for arbitrary route values. private readonly IList _availableHttpMethods = new[] { "GET", "POST", "PUT", "DELETE", "OPTIONS" }; diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Indexes/WorkflowIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Indexes/WorkflowIndexProvider.cs index 1ddc23dd5aa..6d30f14e46a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Indexes/WorkflowIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Indexes/WorkflowIndexProvider.cs @@ -28,21 +28,20 @@ public class WorkflowIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() - .Map(workflow => - new WorkflowIndex - { - WorkflowTypeId = workflow.WorkflowTypeId, - WorkflowId = workflow.WorkflowId, - CreatedUtc = workflow.CreatedUtc, - WorkflowStatus = (int)workflow.Status - } - ); + context + .For() + .Map(workflow => new WorkflowIndex + { + WorkflowTypeId = workflow.WorkflowTypeId, + WorkflowId = workflow.WorkflowId, + CreatedUtc = workflow.CreatedUtc, + WorkflowStatus = (int)workflow.Status + }); - context.For() + context + .For() .Map(workflow => - workflow.BlockingActivities.Select(x => - new WorkflowBlockingActivitiesIndex + workflow.BlockingActivities.Select(x => new WorkflowBlockingActivitiesIndex { ActivityId = x.ActivityId, ActivityName = x.Name, diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Indexes/WorkflowTypeIndexProvider.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Indexes/WorkflowTypeIndexProvider.cs index 4b5554061d8..ff813dbef69 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Indexes/WorkflowTypeIndexProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Indexes/WorkflowTypeIndexProvider.cs @@ -26,21 +26,22 @@ public class WorkflowTypeIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() - .Map(workflowType => - new WorkflowTypeIndex - { - WorkflowTypeId = workflowType.WorkflowTypeId, - Name = workflowType.Name, - IsEnabled = workflowType.IsEnabled, - HasStart = workflowType.Activities.Any(x => x.IsStart) - } - ); + context + .For() + .Map(workflowType => new WorkflowTypeIndex + { + WorkflowTypeId = workflowType.WorkflowTypeId, + Name = workflowType.Name, + IsEnabled = workflowType.IsEnabled, + HasStart = workflowType.Activities.Any(x => x.IsStart) + }); - context.For() + context + .For() .Map(workflowType => - workflowType.Activities.Where(x => x.IsStart).Select(x => - new WorkflowTypeStartActivitiesIndex + workflowType + .Activities.Where(x => x.IsStart) + .Select(x => new WorkflowTypeStartActivitiesIndex { WorkflowTypeId = workflowType.WorkflowTypeId, Name = workflowType.Name, diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Migrations.cs index 78a9a89bbde..1a9daf58d9a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Migrations.cs @@ -10,78 +10,50 @@ public class Migrations : DataMigration { public async Task CreateAsync() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("WorkflowTypeId", c => c.WithLength(26)) - .Column("Name") - .Column("IsEnabled") - .Column("HasStart") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table.Column("WorkflowTypeId", c => c.WithLength(26)).Column("Name").Column("IsEnabled").Column("HasStart") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_WorkflowTypeIndex_DocumentId", - "DocumentId", - "WorkflowTypeId", - "Name", - "IsEnabled", - "HasStart") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_WorkflowTypeIndex_DocumentId", "DocumentId", "WorkflowTypeId", "Name", "IsEnabled", "HasStart") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("WorkflowTypeId") - .Column("Name") - .Column("IsEnabled") - .Column("StartActivityId") - .Column("StartActivityName") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table.Column("WorkflowTypeId").Column("Name").Column("IsEnabled").Column("StartActivityId").Column("StartActivityName") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_WorkflowTypeStartActivitiesIndex_DocumentId", - "DocumentId", - "WorkflowTypeId", - "StartActivityId", - "StartActivityName", - "IsEnabled") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_WorkflowTypeStartActivitiesIndex_DocumentId", "DocumentId", "WorkflowTypeId", "StartActivityId", "StartActivityName", "IsEnabled") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("WorkflowTypeId", c => c.WithLength(26)) - .Column("WorkflowId", c => c.WithLength(26)) - .Column("WorkflowStatus", c => c.WithLength(26)) - .Column("CreatedUtc") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("WorkflowTypeId", c => c.WithLength(26)) + .Column("WorkflowId", c => c.WithLength(26)) + .Column("WorkflowStatus", c => c.WithLength(26)) + .Column("CreatedUtc") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_WorkflowIndex_DocumentId", - "DocumentId", - "WorkflowTypeId", - "WorkflowId", - "WorkflowStatus", - "CreatedUtc") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_WorkflowIndex_DocumentId", "DocumentId", "WorkflowTypeId", "WorkflowId", "WorkflowStatus", "CreatedUtc") ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ActivityId") - .Column("ActivityName") - .Column("ActivityIsStart") - .Column("WorkflowTypeId") - .Column("WorkflowId") - .Column("WorkflowCorrelationId") + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ActivityId") + .Column("ActivityName") + .Column("ActivityIsStart") + .Column("WorkflowTypeId") + .Column("WorkflowId") + .Column("WorkflowCorrelationId") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_WFBlockingActivities_DocumentId_ActivityId", - "DocumentId", - "ActivityId", - "WorkflowTypeId", - "WorkflowId") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_WFBlockingActivities_DocumentId_ActivityId", "DocumentId", "ActivityId", "WorkflowTypeId", "WorkflowId") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_WFBlockingActivities_DocumentId_ActivityName", - "DocumentId", - "ActivityName", - "WorkflowTypeId", - "WorkflowCorrelationId") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_WFBlockingActivities_DocumentId_ActivityName", "DocumentId", "ActivityName", "WorkflowTypeId", "WorkflowCorrelationId") ); // Shortcut other migration steps on new content definition schemas. @@ -102,47 +74,24 @@ await SchemaBuilder.AlterIndexTableAsync(table => // This code can be removed in a later version. public async Task UpdateFrom2Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_WorkflowTypeIndex_DocumentId", - "DocumentId", - "WorkflowTypeId", - "Name", - "IsEnabled", - "HasStart") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_WorkflowTypeIndex_DocumentId", "DocumentId", "WorkflowTypeId", "Name", "IsEnabled", "HasStart") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_WorkflowTypeStartActivitiesIndex_DocumentId", - "DocumentId", - "WorkflowTypeId", - "StartActivityId", - "StartActivityName", - "IsEnabled") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_WorkflowTypeStartActivitiesIndex_DocumentId", "DocumentId", "WorkflowTypeId", "StartActivityId", "StartActivityName", "IsEnabled") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_WorkflowIndex_DocumentId", - "DocumentId", - "WorkflowTypeId", - "WorkflowId", - "WorkflowStatus", - "CreatedUtc") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_WorkflowIndex_DocumentId", "DocumentId", "WorkflowTypeId", "WorkflowId", "WorkflowStatus", "CreatedUtc") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_WFBlockingActivities_DocumentId_ActivityId", - "DocumentId", - "ActivityId", - "WorkflowTypeId", - "WorkflowId") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_WFBlockingActivities_DocumentId_ActivityId", "DocumentId", "ActivityId", "WorkflowTypeId", "WorkflowId") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_WFBlockingActivities_DocumentId_ActivityName", - "DocumentId", - "ActivityName", - "WorkflowTypeId", - "WorkflowCorrelationId") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_WFBlockingActivities_DocumentId_ActivityName", "DocumentId", "ActivityName", "WorkflowTypeId", "WorkflowCorrelationId") ); return 3; diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Permissions.cs index 1c3686eb336..2482ec0f88f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Permissions.cs @@ -9,26 +9,10 @@ public class Permissions : IPermissionProvider public static readonly Permission ManageWorkflows = new("ManageWorkflows", "Manage workflows", isSecurityCritical: true); public static readonly Permission ExecuteWorkflows = new("ExecuteWorkflows", "Execute workflows", isSecurityCritical: true); - private readonly IEnumerable _allPermissions = - [ - ManageWorkflows, - ExecuteWorkflows, - ]; + private readonly IEnumerable _allPermissions = [ManageWorkflows, ExecuteWorkflows,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - new PermissionStereotype - { - Name = "Editor", - Permissions = _allPermissions, - } - ]; + [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, }, new PermissionStereotype { Name = "Editor", Permissions = _allPermissions, }]; } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Recipes/WorkflowTypeStep.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Recipes/WorkflowTypeStep.cs index a452ce70521..685f6388250 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Recipes/WorkflowTypeStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Recipes/WorkflowTypeStep.cs @@ -21,10 +21,12 @@ public class WorkflowTypeStep : IRecipeStepHandler private readonly ISecurityTokenService _securityTokenService; private readonly IUrlHelper _urlHelper; - public WorkflowTypeStep(IWorkflowTypeStore workflowTypeStore, + public WorkflowTypeStep( + IWorkflowTypeStore workflowTypeStore, ISecurityTokenService securityTokenService, IActionContextAccessor actionContextAccessor, - IUrlHelperFactory urlHelperFactory) + IUrlHelperFactory urlHelperFactory + ) { _workflowTypeStore = workflowTypeStore; _securityTokenService = securityTokenService; @@ -70,8 +72,10 @@ public async Task ExecuteAsync(RecipeExecutionContext context) private string ReGenerateHttpRequestEventUrl(WorkflowType workflow, ActivityRecord activity, int tokenLifeSpan) { - var token = _securityTokenService.CreateToken(new WorkflowPayload(workflow.WorkflowTypeId, activity.ActivityId), - TimeSpan.FromDays(tokenLifeSpan == 0 ? HttpWorkflowController.NoExpiryTokenLifespan : tokenLifeSpan)); + var token = _securityTokenService.CreateToken( + new WorkflowPayload(workflow.WorkflowTypeId, activity.ActivityId), + TimeSpan.FromDays(tokenLifeSpan == 0 ? HttpWorkflowController.NoExpiryTokenLifespan : tokenLifeSpan) + ); return _urlHelper.Action("Invoke", "HttpWorkflow", new { token }); } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/ResourceManagementOptionsConfiguration.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/ResourceManagementOptionsConfiguration.cs index aa4088f04d9..fcec103ce24 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/ResourceManagementOptionsConfiguration.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/ResourceManagementOptionsConfiguration.cs @@ -16,14 +16,23 @@ static ResourceManagementOptionsConfiguration() .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Workflows/Scripts/jsplumb.min.js", "~/OrchardCore.Workflows/Scripts/jsplumb.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/jsPlumb/2.15.5/js/jsplumb.min.js", "https://cdnjs.cloudflare.com/ajax/libs/jsPlumb/2.15.5/js/jsplumb.js") - .SetCdnIntegrity("sha384-vJ4MOlEjImsRl4La5sTXZ1UBtJ8uOOqxl2+0gdjRB7oVF6AvTVZ3woqYbTJb7vaf", "sha384-6qcVETlKUuSEc/QpsceL6BNiyEMBFSPE/uyfdRUvEfao8/K9lynY+r8nd/mwLGGh") + .SetCdnIntegrity( + "sha384-vJ4MOlEjImsRl4La5sTXZ1UBtJ8uOOqxl2+0gdjRB7oVF6AvTVZ3woqYbTJb7vaf", + "sha384-6qcVETlKUuSEc/QpsceL6BNiyEMBFSPE/uyfdRUvEfao8/K9lynY+r8nd/mwLGGh" + ) .SetVersion("2.15.5"); _manifest .DefineStyle("jsplumbtoolkit-defaults") .SetUrl("~/OrchardCore.Workflows/Styles/jsplumbtoolkit-defaults.min.css", "~/OrchardCore.Workflows/Styles/jsplumbtoolkit-defaults.css") - .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/jsPlumb/2.15.5/css/jsplumbtoolkit-defaults.min.css", "https://cdnjs.cloudflare.com/ajax/libs/jsPlumb/2.15.5/css/jsplumbtoolkit-defaults.css") - .SetCdnIntegrity("sha384-4TTNOHwtAFYbq+UTSu/7Fj0xnqOabg7FYr9DkNtEKnmIx/YaACNiwhd2XZfO0A/u", "sha384-Q0wOomiqdBpz2z6/yYA8b3gc8A9t7z7QjD14d1WABvXVHbRYBu/IGOv3SOR57anB") + .SetCdn( + "https://cdnjs.cloudflare.com/ajax/libs/jsPlumb/2.15.5/css/jsplumbtoolkit-defaults.min.css", + "https://cdnjs.cloudflare.com/ajax/libs/jsPlumb/2.15.5/css/jsplumbtoolkit-defaults.css" + ) + .SetCdnIntegrity( + "sha384-4TTNOHwtAFYbq+UTSu/7Fj0xnqOabg7FYr9DkNtEKnmIx/YaACNiwhd2XZfO0A/u", + "sha384-Q0wOomiqdBpz2z6/yYA8b3gc8A9t7z7QjD14d1WABvXVHbRYBu/IGOv3SOR57anB" + ) .SetVersion("2.15.5"); } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Scripting/OutcomeMethodProvider.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Scripting/OutcomeMethodProvider.cs index f5f74bf7f99..840c32fc62f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Scripting/OutcomeMethodProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Scripting/OutcomeMethodProvider.cs @@ -10,11 +10,7 @@ public class OutcomeMethodProvider : IGlobalMethodProvider public OutcomeMethodProvider(IList outcomes) { - _setOutcomeMethod = new GlobalMethod - { - Name = "setOutcome", - Method = serviceProvider => (Action)(name => outcomes.Add(name)), - }; + _setOutcomeMethod = new GlobalMethod { Name = "setOutcome", Method = serviceProvider => (Action)(name => outcomes.Add(name)), }; } public IEnumerable GetMethods() diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Scripting/WorkflowMethodsProvider.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Scripting/WorkflowMethodsProvider.cs index 03b7984ab0c..d1045ac43fd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Scripting/WorkflowMethodsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Scripting/WorkflowMethodsProvider.cs @@ -18,17 +18,9 @@ public class WorkflowMethodsProvider : IGlobalMethodProvider public WorkflowMethodsProvider(WorkflowExecutionContext workflowContext) { - _workflowMethod = new GlobalMethod - { - Name = "workflow", - Method = serviceProvider => (Func)(() => workflowContext), - }; + _workflowMethod = new GlobalMethod { Name = "workflow", Method = serviceProvider => (Func)(() => workflowContext), }; - _workflowIdMethod = new GlobalMethod - { - Name = "workflowId", - Method = serviceProvider => (Func)(() => workflowContext.Workflow.WorkflowId), - }; + _workflowIdMethod = new GlobalMethod { Name = "workflowId", Method = serviceProvider => (Func)(() => workflowContext.Workflow.WorkflowId), }; _inputMethod = new GlobalMethod { @@ -36,11 +28,7 @@ public WorkflowMethodsProvider(WorkflowExecutionContext workflowContext) Method = serviceProvider => (Func)((name) => workflowContext.Input.TryGetValue(name, out var value) ? value : null), }; - _outputMethod = new GlobalMethod - { - Name = "output", - Method = serviceProvider => (Action)((name, value) => workflowContext.Output[name] = value), - }; + _outputMethod = new GlobalMethod { Name = "output", Method = serviceProvider => (Action)((name, value) => workflowContext.Output[name] = value), }; _propertyMethod = new GlobalMethod { @@ -54,17 +42,9 @@ public WorkflowMethodsProvider(WorkflowExecutionContext workflowContext) Method = serviceProvider => (Action)((name, value) => workflowContext.Properties[name] = value), }; - _resultMethod = new GlobalMethod - { - Name = "lastResult", - Method = serviceProvider => (Func)(() => workflowContext.LastResult), - }; + _resultMethod = new GlobalMethod { Name = "lastResult", Method = serviceProvider => (Func)(() => workflowContext.LastResult), }; - _correlationIdMethod = new GlobalMethod - { - Name = "correlationId", - Method = serviceProvider => (Func)(() => workflowContext.Workflow.CorrelationId), - }; + _correlationIdMethod = new GlobalMethod { Name = "correlationId", Method = serviceProvider => (Func)(() => workflowContext.Workflow.CorrelationId), }; } public IEnumerable GetMethods() diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/ActivityDisplayManager.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/ActivityDisplayManager.cs index 1151ae13bb0..ce7b5eeb47b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/ActivityDisplayManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/ActivityDisplayManager.cs @@ -18,13 +18,15 @@ namespace OrchardCore.Workflows.Services public class ActivityDisplayManager : IActivityDisplayManager { private readonly DisplayManager _displayManager; + public ActivityDisplayManager( IOptions workflowOptions, IServiceProvider serviceProvider, IShapeFactory shapeFactory, IEnumerable placementProviders, ILogger> displayManagerLogger, - ILayoutAccessor layoutAccessor) + ILayoutAccessor layoutAccessor + ) { var drivers = workflowOptions.Value.ActivityDisplayDriverTypes.Select(x => serviceProvider.CreateInstance>(x)); _displayManager = new DisplayManager(drivers, shapeFactory, placementProviders, displayManagerLogger, layoutAccessor); diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/ActivityLibrary.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/ActivityLibrary.cs index 793cf0c25bb..5baddfc1a62 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/ActivityLibrary.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/ActivityLibrary.cs @@ -19,8 +19,17 @@ public class ActivityLibrary : IActivityLibrary public ActivityLibrary(IOptions workflowOptions, IServiceProvider serviceProvider, ILogger logger) { - _activityDictionary = new Lazy>(() => workflowOptions.Value.ActivityTypes.Where(x => !x.IsAbstract).Select(x => serviceProvider.CreateInstance(x)).OrderBy(x => x.Name).ToDictionary(x => x.Name)); - _activityCategories = new Lazy>(() => _activityDictionary.Value.Values.OrderBy(x => x.Category.Value).Select(x => x.Category).Distinct(new LocalizedStringComparer()).ToList()); + _activityDictionary = new Lazy>( + () => + workflowOptions + .Value.ActivityTypes.Where(x => !x.IsAbstract) + .Select(x => serviceProvider.CreateInstance(x)) + .OrderBy(x => x.Name) + .ToDictionary(x => x.Name) + ); + _activityCategories = new Lazy>( + () => _activityDictionary.Value.Values.OrderBy(x => x.Category.Value).Select(x => x.Category).Distinct(new LocalizedStringComparer()).ToList() + ); _serviceProvider = serviceProvider; _logger = logger; } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/Resolver.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/Resolver.cs index b3696c878f5..84d47032d0d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/Resolver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/Resolver.cs @@ -9,6 +9,7 @@ namespace OrchardCore.Workflows.Services public class Resolver { private readonly IServiceProvider _serviceProvider; + public Resolver(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/SecurityTokenService.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/SecurityTokenService.cs index fd43daea115..6b28a6153a0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/SecurityTokenService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/SecurityTokenService.cs @@ -10,9 +10,7 @@ public class SecurityTokenService : ISecurityTokenService private readonly ITimeLimitedDataProtector _dataProtector; private readonly IClock _clock; - public SecurityTokenService( - IDataProtectionProvider dataProtectionProvider, - IClock clock) + public SecurityTokenService(IDataProtectionProvider dataProtectionProvider, IClock clock) { _dataProtector = dataProtectionProvider.CreateProtector("Tokens").ToTimeLimitedDataProtector(); _clock = clock; @@ -39,9 +37,7 @@ public bool TryDecryptToken(string token, out T payload) return true; } } - catch - { - } + catch { } return false; } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowManager.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowManager.cs index 301096184a9..e32a686ab90 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowManager.cs @@ -35,8 +35,7 @@ public class WorkflowManager : IWorkflowManager private readonly Dictionary _recursions = []; private int _currentRecursionDepth; - public WorkflowManager - ( + public WorkflowManager( IActivityLibrary activityLibrary, IWorkflowTypeStore workflowTypeRepository, IWorkflowStore workflowRepository, @@ -47,7 +46,8 @@ public WorkflowManager ILogger logger, ILogger missingActivityLogger, IStringLocalizer missingActivityLocalizer, - IClock clock) + IClock clock + ) { _activityLibrary = activityLibrary; _workflowTypeStore = workflowTypeRepository; @@ -70,10 +70,7 @@ public Workflow NewWorkflow(WorkflowType workflowType, string correlationId = nu { WorkflowTypeId = workflowType.WorkflowTypeId, Status = WorkflowStatus.Idle, - State = JObject.FromObject(new WorkflowState - { - ActivityStates = workflowType.Activities.ToDictionary(x => x.ActivityId, x => x.Properties) - }), + State = JObject.FromObject(new WorkflowState { ActivityStates = workflowType.Activities.ToDictionary(x => x.ActivityId, x => x.Properties) }), CorrelationId = correlationId, LockTimeout = workflowType.LockTimeout, LockExpiration = workflowType.LockExpiration, @@ -91,15 +88,17 @@ public async Task CreateWorkflowExecutionContextAsync( ArgumentNullException.ThrowIfNull(workflow); var state = workflow.State.ToObject(); - var activityQuery = await Task.WhenAll(workflowType.Activities.Select(x => - { - if (!state.ActivityStates.TryGetValue(x.ActivityId, out var activityState)) + var activityQuery = await Task.WhenAll( + workflowType.Activities.Select(x => { - activityState = []; - } + if (!state.ActivityStates.TryGetValue(x.ActivityId, out var activityState)) + { + activityState = []; + } - return CreateActivityExecutionContextAsync(x, activityState); - })); + return CreateActivityExecutionContextAsync(x, activityState); + }) + ); var mergedInput = (await DeserializeAsync(state.Input)).Merge(input ?? new Dictionary()); var properties = await DeserializeAsync(state.Properties); @@ -118,20 +117,25 @@ public Task CreateActivityExecutionContextAsync(ActivityRecord if (activity == null) { - _logger.LogWarning("Requested activity '{ActivityName}' does not exist in the library. This could indicate a changed name or a missing feature. Replacing it with MissingActivity.", activityRecord.Name); + _logger.LogWarning( + "Requested activity '{ActivityName}' does not exist in the library. This could indicate a changed name or a missing feature. Replacing it with MissingActivity.", + activityRecord.Name + ); activity = new MissingActivity(_missingActivityLocalizer, _missingActivityLogger, activityRecord); } - var context = new ActivityContext - { - ActivityRecord = activityRecord, - Activity = activity - }; + var context = new ActivityContext { ActivityRecord = activityRecord, Activity = activity }; return Task.FromResult(context); } - public async Task> TriggerEventAsync(string name, IDictionary input = null, string correlationId = null, bool isExclusive = false, bool isAlwaysCorrelated = false) + public async Task> TriggerEventAsync( + string name, + IDictionary input = null, + string correlationId = null, + bool isExclusive = false, + bool isAlwaysCorrelated = false + ) { var activity = _activityLibrary.GetActivityByName(name); if (activity == null) @@ -219,8 +223,12 @@ public async Task> TriggerEventAsync(strin } // Check if the event is exclusive and there's already a correlated instance halted on a starting activity of this type. - if (isExclusive && (await _workflowStore.ListAsync(workflowType.WorkflowTypeId, name, correlationId, isAlwaysCorrelated)) - .Any(x => x.BlockingActivities.Any(x => x.Name == name && x.IsStart))) + if ( + isExclusive + && (await _workflowStore.ListAsync(workflowType.WorkflowTypeId, name, correlationId, isAlwaysCorrelated)).Any(x => + x.BlockingActivities.Any(x => x.Name == name && x.IsStart) + ) + ) { continue; } @@ -299,7 +307,8 @@ public async Task RestartWorkflowAsync(WorkflowType wo { ArgumentNullException.ThrowIfNull(workflowType); - var startActivity = workflowType.Activities?.FirstOrDefault(x => x.IsStart) + var startActivity = + workflowType.Activities?.FirstOrDefault(x => x.IsStart) ?? throw new InvalidOperationException($"Workflow with ID {workflowType.Id} does not have a start activity."); // Create a new workflow instance. @@ -349,11 +358,17 @@ public async Task RestartWorkflowAsync(WorkflowType wo return workflowContext; } - public async Task StartWorkflowAsync(WorkflowType workflowType, ActivityRecord startActivity = null, IDictionary input = null, string correlationId = null) + public async Task StartWorkflowAsync( + WorkflowType workflowType, + ActivityRecord startActivity = null, + IDictionary input = null, + string correlationId = null + ) { ArgumentNullException.ThrowIfNull(workflowType); - startActivity ??= workflowType.Activities?.FirstOrDefault(x => x.IsStart) + startActivity ??= + workflowType.Activities?.FirstOrDefault(x => x.IsStart) ?? throw new InvalidOperationException($"Workflow with ID {workflowType.Id} does not have a start activity."); // Create a new workflow instance. @@ -481,7 +496,13 @@ public async Task> ExecuteWorkflowAsync(WorkflowExec } catch (Exception ex) { - _logger.LogError(ex, "An unhandled error occurred while executing an activity. Workflow ID: '{WorkflowTypeId}'. Activity: '{ActivityId}', '{ActivityName}'. Putting the workflow in the faulted state.", workflowType.Id, activityContext.ActivityRecord.ActivityId, activityContext.ActivityRecord.Name); + _logger.LogError( + ex, + "An unhandled error occurred while executing an activity. Workflow ID: '{WorkflowTypeId}'. Activity: '{ActivityId}', '{ActivityName}'. Putting the workflow in the faulted state.", + workflowType.Id, + activityContext.ActivityRecord.ActivityId, + activityContext.ActivityRecord.Name + ); workflowContext.Fault(ex, activityContext); // Decrement the workflow scope recursion count. diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowStore.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowStore.cs index 66f4db11964..eccad053fb0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowStore.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowStore.cs @@ -35,8 +35,7 @@ public async Task HasHaltedInstanceAsync(string workflowTypeId) public Task> ListAsync(string workflowTypeId = null, int? skip = null, int? take = null) { - var query = (IQuery)FilterByWorkflowTypeId(_session.Query(), workflowTypeId) - .OrderByDescending(x => x.CreatedUtc); + var query = (IQuery)FilterByWorkflowTypeId(_session.Query(), workflowTypeId).OrderByDescending(x => x.CreatedUtc); if (skip != null) { @@ -79,9 +78,7 @@ public Task> GetAsync(IEnumerable ids) public Task> ListAsync(string workflowTypeId, IEnumerable blockingActivityIds) { return _session - .Query(index => - index.WorkflowTypeId == workflowTypeId && - index.ActivityId.IsIn(blockingActivityIds)) + .Query(index => index.WorkflowTypeId == workflowTypeId && index.ActivityId.IsIn(blockingActivityIds)) .ListAsync(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowTypeStore.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowTypeStore.cs index 8f3ec49bd12..97332aa18f2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowTypeStore.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Services/WorkflowTypeStore.cs @@ -44,11 +44,7 @@ public Task> ListAsync() public Task> GetByStartActivityAsync(string activityName) { - return _session - .Query(index => - index.StartActivityName == activityName && - index.IsEnabled) - .ListAsync(); + return _session.Query(index => index.StartActivityName == activityName && index.IsEnabled).ListAsync(); } public async Task SaveAsync(WorkflowType workflowType) diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Startup.cs index 1f3a9825097..a915e048d9a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Startup.cs @@ -34,9 +34,21 @@ public override void ConfigureServices(IServiceCollection services) services.Configure(o => { o.MemberAccessStrategy.Register(); - o.MemberAccessStrategy.Register("Input", (obj, context) => new LiquidPropertyAccessor((LiquidTemplateContext)context, (name, context) => LiquidWorkflowExpressionEvaluator.ToFluidValue(obj.Input, name, context))); - o.MemberAccessStrategy.Register("Output", (obj, context) => new LiquidPropertyAccessor((LiquidTemplateContext)context, (name, context) => LiquidWorkflowExpressionEvaluator.ToFluidValue(obj.Output, name, context))); - o.MemberAccessStrategy.Register("Properties", (obj, context) => new LiquidPropertyAccessor((LiquidTemplateContext)context, (name, context) => LiquidWorkflowExpressionEvaluator.ToFluidValue(obj.Properties, name, context))); + o.MemberAccessStrategy.Register( + "Input", + (obj, context) => + new LiquidPropertyAccessor((LiquidTemplateContext)context, (name, context) => LiquidWorkflowExpressionEvaluator.ToFluidValue(obj.Input, name, context)) + ); + o.MemberAccessStrategy.Register( + "Output", + (obj, context) => + new LiquidPropertyAccessor((LiquidTemplateContext)context, (name, context) => LiquidWorkflowExpressionEvaluator.ToFluidValue(obj.Output, name, context)) + ); + o.MemberAccessStrategy.Register( + "Properties", + (obj, context) => + new LiquidPropertyAccessor((LiquidTemplateContext)context, (name, context) => LiquidWorkflowExpressionEvaluator.ToFluidValue(obj.Properties, name, context)) + ); }); services.AddSingleton(); diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Timers/TimerBackgroundTask.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Timers/TimerBackgroundTask.cs index 22c0c1e0cab..7fd4cfe46a1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Timers/TimerBackgroundTask.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Timers/TimerBackgroundTask.cs @@ -7,10 +7,7 @@ namespace OrchardCore.Workflows.Timers { - [BackgroundTask( - Title = "Timed Workflow Starter", - Schedule = "* * * * *", - Description = "Triggers timed workflow events.")] + [BackgroundTask(Title = "Timed Workflow Starter", Schedule = "* * * * *", Description = "Triggers timed workflow events.")] public class TimerBackgroundTask : IBackgroundTask { public Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken) diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/UserTasks/Drivers/UserTaskEventContentDriver.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/UserTasks/Drivers/UserTaskEventContentDriver.cs index d9b0be556d2..b9e3baef942 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/UserTasks/Drivers/UserTaskEventContentDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/UserTasks/Drivers/UserTaskEventContentDriver.cs @@ -34,7 +34,8 @@ public UserTaskEventContentDriver( IWorkflowManager workflowManager, INotifier notifier, IHtmlLocalizer localizer, - IHttpContextAccessor httpContextAccessor) + IHttpContextAccessor httpContextAccessor + ) { _workflowStore = workflowStore; _activityLibrary = activityLibrary; @@ -49,10 +50,15 @@ public override IDisplayResult Edit(ContentItem contentItem) { var results = new List { - Initialize("Content_UserTaskButton", async model => { - var actions = await GetUserTaskActionsAsync(contentItem.ContentItemId); - model.Actions = actions; - }).Location("Actions:30"), + Initialize( + "Content_UserTaskButton", + async model => + { + var actions = await GetUserTaskActionsAsync(contentItem.ContentItemId); + model.Actions = actions; + } + ) + .Location("Actions:30"), }; return Combine(results.ToArray()); diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/ViewComponents/SelectWorkflowTypeViewComponent.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/ViewComponents/SelectWorkflowTypeViewComponent.cs index 8e3171b173e..de77afd4bc0 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/ViewComponents/SelectWorkflowTypeViewComponent.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/ViewComponents/SelectWorkflowTypeViewComponent.cs @@ -18,11 +18,7 @@ public async Task InvokeAsync(string selectedWorkflowTypeI { var selections = await WorkflowTypeSelection.BuildAsync(_contentDefinitionManager, selectedWorkflowTypeId); - var model = new SelectWorkflowTypeViewModel - { - HtmlName = htmlName, - WorkflowTypeSelections = selections - }; + var model = new SelectWorkflowTypeViewModel { HtmlName = htmlName, WorkflowTypeSelections = selections }; return View(model); } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/ViewModels/CommitTransactionTaskViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/ViewModels/CommitTransactionTaskViewModel.cs index e1d99a253f2..7bdde41baa7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/ViewModels/CommitTransactionTaskViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/ViewModels/CommitTransactionTaskViewModel.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Workflows.ViewModels { - public class CommitTransactionTaskViewModel - { - } + public class CommitTransactionTaskViewModel { } } diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/ViewModels/SelectWorkflowTypeViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/ViewModels/SelectWorkflowTypeViewModel.cs index e02bf19c92d..2364b0bdcc7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/ViewModels/SelectWorkflowTypeViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/ViewModels/SelectWorkflowTypeViewModel.cs @@ -21,11 +21,7 @@ public static async Task> BuildAsync(IWorkflowTypeS { var workflowTypes = await workflowTypeStore.ListAsync(); var selections = workflowTypes - .Select(x => new WorkflowTypeSelection - { - IsSelected = x.WorkflowTypeId == selectedWorkflowTypeId, - WorkflowType = x - }) + .Select(x => new WorkflowTypeSelection { IsSelected = x.WorkflowTypeId == selectedWorkflowTypeId, WorkflowType = x }) .OrderBy(x => x.WorkflowType.Name) .ToList(); diff --git a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Controllers/HomeController.cs b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Controllers/HomeController.cs index aabd4a54c67..38a4a197d93 100644 --- a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Controllers/HomeController.cs +++ b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Controllers/HomeController.cs @@ -17,10 +17,7 @@ public class HomeController : Controller private readonly IEnumerable _xmlRpcHandlers; private readonly ILogger _logger; - public HomeController( - IXmlRpcWriter writer, - IEnumerable xmlRpcHandlers, - ILogger logger) + public HomeController(IXmlRpcWriter writer, IEnumerable xmlRpcHandlers, ILogger logger) { _writer = writer; _xmlRpcHandlers = xmlRpcHandlers; diff --git a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Controllers/MetaWeblogController.cs b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Controllers/MetaWeblogController.cs index 3fdb9d7ba30..ba8c2f656f0 100644 --- a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Controllers/MetaWeblogController.cs +++ b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Controllers/MetaWeblogController.cs @@ -14,9 +14,7 @@ public class MetaWeblogController : Controller private readonly IEnumerable _xmlRpcHandlers; private readonly ILogger _logger; - public MetaWeblogController( - IEnumerable xmlRpcHandlers, - ILogger logger) + public MetaWeblogController(IEnumerable xmlRpcHandlers, ILogger logger) { _xmlRpcHandlers = xmlRpcHandlers; _logger = logger; @@ -37,17 +35,15 @@ public ActionResult Manifest() new XElement(XName.Get("supportsKeywords", ManifestUri), "No"), new XElement(XName.Get("supportsCategories", ManifestUri), "No"), new XElement(XName.Get("supportsFileUpload", ManifestUri), "No"), - new XElement(XName.Get("supportsCustomDate", ManifestUri), "No")); + new XElement(XName.Get("supportsCustomDate", ManifestUri), "No") + ); foreach (var handler in _xmlRpcHandlers) { handler.SetCapabilities(options); } - var doc = new XDocument( - new XElement( - XName.Get("manifest", ManifestUri), - options)); + var doc = new XDocument(new XElement(XName.Get("manifest", ManifestUri), options)); return Content(doc.ToString(), "text/xml"); } diff --git a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Manifest.cs b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Manifest.cs index 599dc9eb610..57207c693c1 100644 --- a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Manifest.cs +++ b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Manifest.cs @@ -1,11 +1,6 @@ using OrchardCore.Modules.Manifest; -[assembly: Module( - Name = "XML-RPC", - Author = ManifestConstants.OrchardCoreTeam, - Website = ManifestConstants.OrchardCoreWebsite, - Version = ManifestConstants.OrchardCoreVersion -)] +[assembly: Module(Name = "XML-RPC", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion)] [assembly: Feature( Id = "OrchardCore.XmlRpc", diff --git a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcReader.cs b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcReader.cs index 9403c0d8b34..c9cc00d28dc 100644 --- a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcReader.cs +++ b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcReader.cs @@ -23,27 +23,52 @@ public class XmlRpcReader : IXmlRpcReader public XmlRpcReader() { _dispatch = new Dictionary> + { + { + "i4", + x => new XRpcData { Value = (int)x } + }, + { + "int", + x => new XRpcData { Value = (int)x } + }, + { + "boolean", + x => new XRpcData { Value = (string)x == "1" } + }, + { + "string", + x => new XRpcData { Value = (string)x } + }, { - { "i4", x => new XRpcData { Value = (int)x } }, - { "int", x => new XRpcData { Value = (int)x } }, - { "boolean", x => new XRpcData { Value = (string)x == "1" } }, - { "string", x => new XRpcData { Value = (string)x } }, - { "double", x => new XRpcData { Value = (double)x } }, - { "dateTime.iso8601", x => { - DateTime parsedDateTime; - - // try parsing a "normal" datetime string then try what live writer gives us - if (!DateTime.TryParse(x.Value, out parsedDateTime) - && !DateTime.TryParseExact(x.Value, "yyyyMMddTHH:mm:ss", DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out parsedDateTime)) { - parsedDateTime = DateTime.Now; - } - - return new XRpcData { Value = parsedDateTime }; - } }, - { "base64", x => new XRpcData { Value = Convert.FromBase64String((string)x) } }, - { "struct", x => XRpcData.For(MapToStruct(x)) }, - { "array", x => XRpcData.For(MapToArray(x)) }, - }; + "double", + x => new XRpcData { Value = (double)x } + }, + { + "dateTime.iso8601", + x => + { + DateTime parsedDateTime; + + // try parsing a "normal" datetime string then try what live writer gives us + if ( + !DateTime.TryParse(x.Value, out parsedDateTime) + && !DateTime.TryParseExact(x.Value, "yyyyMMddTHH:mm:ss", DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out parsedDateTime) + ) + { + parsedDateTime = DateTime.Now; + } + + return new XRpcData { Value = parsedDateTime }; + } + }, + { + "base64", + x => new XRpcData { Value = Convert.FromBase64String((string)x) } + }, + { "struct", x => XRpcData.For(MapToStruct(x)) }, + { "array", x => XRpcData.For(MapToArray(x)) }, + }; } /// @@ -53,11 +78,7 @@ public XmlRpcReader() /// The rpc method call. public XRpcMethodCall MapToMethodCall(XElement source) { - return new XRpcMethodCall - { - MethodName = (string)source.Element("methodName"), - Params = source.Elements("params").Elements("param").Select(MapToData).ToList() - }; + return new XRpcMethodCall { MethodName = (string)source.Element("methodName"), Params = source.Elements("params").Elements("param").Select(MapToData).ToList() }; } /// @@ -94,9 +115,7 @@ public XRpcStruct MapToStruct(XElement source) var result = new XRpcStruct(); foreach (var member in source.Elements("member")) { - result.Members.Add( - (string)member.Element("name"), - MapValue(member.Element("value"))); + result.Members.Add((string)member.Element("name"), MapValue(member.Element("value"))); } return result; diff --git a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcWriter.cs b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcWriter.cs index 913e0227098..3cd6d754db9 100644 --- a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcWriter.cs +++ b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcWriter.cs @@ -23,19 +23,19 @@ public class XmlRpcWriter : IXmlRpcWriter public XmlRpcWriter() { _dispatch = new Dictionary> - { - { typeof(int), p => new XElement("int", (int)p.Value) }, - { typeof(bool), p => new XElement("boolean", (bool)p.Value ? "1" : "0") }, - { typeof(string), p => new XElement("string", p.Value) }, - { typeof(double), p => new XElement("double", (double)p.Value) }, - { typeof(DateTime), p => new XElement("dateTime.iso8601", ((DateTime)p.Value).ToString("yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture)) }, - { typeof(DateTime?), p => new XElement("dateTime.iso8601", ((DateTime?)p.Value).Value.ToString("yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture)) }, - { typeof(DateTimeOffset), p => new XElement("dateTime.iso8601", ((DateTimeOffset)p.Value).ToString("yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture)) }, - { typeof(DateTimeOffset?), p => new XElement("dateTime.iso8601", ((DateTimeOffset?)p.Value).Value.ToString("yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture)) }, - { typeof(byte[]), p => new XElement("base64", Convert.ToBase64String((byte[])p.Value)) }, - { typeof(XRpcStruct), p => MapStruct((XRpcStruct)p.Value) }, - { typeof(XRpcArray), p => MapArray((XRpcArray)p.Value) }, - }; + { + { typeof(int), p => new XElement("int", (int)p.Value) }, + { typeof(bool), p => new XElement("boolean", (bool)p.Value ? "1" : "0") }, + { typeof(string), p => new XElement("string", p.Value) }, + { typeof(double), p => new XElement("double", (double)p.Value) }, + { typeof(DateTime), p => new XElement("dateTime.iso8601", ((DateTime)p.Value).ToString("yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture)) }, + { typeof(DateTime?), p => new XElement("dateTime.iso8601", ((DateTime?)p.Value).Value.ToString("yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture)) }, + { typeof(DateTimeOffset), p => new XElement("dateTime.iso8601", ((DateTimeOffset)p.Value).ToString("yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture)) }, + { typeof(DateTimeOffset?), p => new XElement("dateTime.iso8601", ((DateTimeOffset?)p.Value).Value.ToString("yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture)) }, + { typeof(byte[]), p => new XElement("base64", Convert.ToBase64String((byte[])p.Value)) }, + { typeof(XRpcStruct), p => MapStruct((XRpcStruct)p.Value) }, + { typeof(XRpcArray), p => MapArray((XRpcArray)p.Value) }, + }; } /// @@ -54,17 +54,10 @@ public XElement MapMethodResponse(XRpcMethodResponse rpcMethodResponse) members.Set("faultCode", rpcMethodResponse.Fault.Code); members.Set("faultString", rpcMethodResponse.Fault.Message); - return new XElement("methodResponse", - new XElement("fault", - new XElement("value", MapStruct(members)) - ) - ); + return new XElement("methodResponse", new XElement("fault", new XElement("value", MapStruct(members)))); } - return new XElement("methodResponse", - new XElement("params", - rpcMethodResponse.Params.Select( - p => new XElement("param", MapValue(p))))); + return new XElement("methodResponse", new XElement("params", rpcMethodResponse.Params.Select(p => new XElement("param", MapValue(p))))); } /// @@ -86,13 +79,7 @@ public XElement MapData(XRpcData rpcData) /// The XML element. public XElement MapStruct(XRpcStruct rpcStruct) { - return new XElement( - "struct", - rpcStruct.Members.Select( - kv => new XElement( - "member", - new XElement("name", kv.Key), - MapValue(kv.Value)))); + return new XElement("struct", rpcStruct.Members.Select(kv => new XElement("member", new XElement("name", kv.Key), MapValue(kv.Value)))); } /// @@ -102,11 +89,7 @@ public XElement MapStruct(XRpcStruct rpcStruct) /// The XML element. public XElement MapArray(XRpcArray rpcArray) { - return new XElement( - "array", - new XElement( - "data", - rpcArray.Data.Select(MapValue))); + return new XElement("array", new XElement("data", rpcArray.Data.Select(MapValue))); } /// diff --git a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Startup.cs b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Startup.cs index d054e2bb8f2..b70943bcff7 100644 --- a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Startup.cs @@ -17,12 +17,7 @@ public override void ConfigureServices(IServiceCollection services) public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { - routes.MapAreaControllerRoute( - name: "XmlRpc", - areaName: "OrchardCore.XmlRpc", - pattern: "xmlrpc", - defaults: new { controller = "Home", action = "Index" } - ); + routes.MapAreaControllerRoute(name: "XmlRpc", areaName: "OrchardCore.XmlRpc", pattern: "xmlrpc", defaults: new { controller = "Home", action = "Index" }); } } diff --git a/src/OrchardCore.Mvc.Web/Program.cs b/src/OrchardCore.Mvc.Web/Program.cs index 785623cd759..08888f89d66 100644 --- a/src/OrchardCore.Mvc.Web/Program.cs +++ b/src/OrchardCore.Mvc.Web/Program.cs @@ -1,8 +1,6 @@ var builder = WebApplication.CreateBuilder(args); -builder.Services - .AddOrchardCore() - .AddMvc(); +builder.Services.AddOrchardCore().AddMvc(); var app = builder.Build(); diff --git a/src/OrchardCore.Themes/TheAdmin/ResourceManagementOptionsConfiguration.cs b/src/OrchardCore.Themes/TheAdmin/ResourceManagementOptionsConfiguration.cs index 649ddc37f44..46f96bcdc1b 100644 --- a/src/OrchardCore.Themes/TheAdmin/ResourceManagementOptionsConfiguration.cs +++ b/src/OrchardCore.Themes/TheAdmin/ResourceManagementOptionsConfiguration.cs @@ -23,16 +23,9 @@ static ResourceManagementOptionsConfiguration() .SetDependencies("js-cookie") .SetVersion("1.0.0"); - _manifest - .DefineScript("admin-main") - .SetUrl("~/TheAdmin/js/TheAdmin-main.min.js", "~/TheAdmin/js/TheAdmin-main.js") - .SetDependencies("admin-head") - .SetVersion("1.0.0"); + _manifest.DefineScript("admin-main").SetUrl("~/TheAdmin/js/TheAdmin-main.min.js", "~/TheAdmin/js/TheAdmin-main.js").SetDependencies("admin-head").SetVersion("1.0.0"); - _manifest - .DefineStyle("admin") - .SetUrl("~/TheAdmin/css/TheAdmin.min.css", "~/TheAdmin/css/TheAdmin.css") - .SetVersion("1.0.0"); + _manifest.DefineStyle("admin").SetUrl("~/TheAdmin/css/TheAdmin.min.css", "~/TheAdmin/css/TheAdmin.css").SetVersion("1.0.0"); } public void Configure(ResourceManagementOptions options) diff --git a/src/OrchardCore.Themes/TheAgencyTheme/ResourceManagementOptionsConfiguration.cs b/src/OrchardCore.Themes/TheAgencyTheme/ResourceManagementOptionsConfiguration.cs index 0e0570a2b64..421a9fd6c58 100644 --- a/src/OrchardCore.Themes/TheAgencyTheme/ResourceManagementOptionsConfiguration.cs +++ b/src/OrchardCore.Themes/TheAgencyTheme/ResourceManagementOptionsConfiguration.cs @@ -14,18 +14,15 @@ static ResourceManagementOptionsConfiguration() _manifest .DefineScript("TheAgencyTheme-bootstrap-bundle") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.js") - .SetCdnIntegrity("sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p", "sha384-8fq7CZc5BnER+jVlJI2Jafpbn4A9320TKhNJfYP33nneHep7sUg/OD30x7fK09pS") + .SetCdnIntegrity( + "sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p", + "sha384-8fq7CZc5BnER+jVlJI2Jafpbn4A9320TKhNJfYP33nneHep7sUg/OD30x7fK09pS" + ) .SetVersion("5.1.3"); - _manifest - .DefineScript("TheAgencyTheme") - .SetUrl("~/TheAgencyTheme/js/scripts.min.js", "~/TheAgencyTheme/js/scripts.js") - .SetVersion("7.0.10"); + _manifest.DefineScript("TheAgencyTheme").SetUrl("~/TheAgencyTheme/js/scripts.min.js", "~/TheAgencyTheme/js/scripts.js").SetVersion("7.0.10"); - _manifest - .DefineStyle("TheAgencyTheme") - .SetUrl("~/TheAgencyTheme/css/styles.min.css", "~/TheAgencyTheme/css/styles.css") - .SetVersion("7.0.10"); + _manifest.DefineStyle("TheAgencyTheme").SetUrl("~/TheAgencyTheme/css/styles.min.css", "~/TheAgencyTheme/css/styles.css").SetVersion("7.0.10"); _manifest .DefineStyle("TheAgencyTheme-bootstrap-oc") diff --git a/src/OrchardCore.Themes/TheBlogTheme/ResourceManagementOptionsConfiguration.cs b/src/OrchardCore.Themes/TheBlogTheme/ResourceManagementOptionsConfiguration.cs index ccef10bba44..67a5dfec292 100644 --- a/src/OrchardCore.Themes/TheBlogTheme/ResourceManagementOptionsConfiguration.cs +++ b/src/OrchardCore.Themes/TheBlogTheme/ResourceManagementOptionsConfiguration.cs @@ -14,13 +14,13 @@ static ResourceManagementOptionsConfiguration() _manifest .DefineScript("TheBlogTheme-bootstrap-bundle") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.js") - .SetCdnIntegrity("sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p", "sha384-8fq7CZc5BnER+jVlJI2Jafpbn4A9320TKhNJfYP33nneHep7sUg/OD30x7fK09pS") + .SetCdnIntegrity( + "sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p", + "sha384-8fq7CZc5BnER+jVlJI2Jafpbn4A9320TKhNJfYP33nneHep7sUg/OD30x7fK09pS" + ) .SetVersion("5.1.3"); - _manifest - .DefineStyle("TheBlogTheme-bootstrap-oc") - .SetUrl("~/TheBlogTheme/css/bootstrap-oc.min.css", "~/TheBlogTheme/css/bootstrap-oc.css") - .SetVersion("1.0.0"); + _manifest.DefineStyle("TheBlogTheme-bootstrap-oc").SetUrl("~/TheBlogTheme/css/bootstrap-oc.min.css", "~/TheBlogTheme/css/bootstrap-oc.css").SetVersion("1.0.0"); _manifest .DefineScript("TheBlogTheme") @@ -28,10 +28,7 @@ static ResourceManagementOptionsConfiguration() .SetUrl("~/TheBlogTheme/js/scripts.min.js", "~/TheBlogTheme/js/scripts.js") .SetVersion("6.0.7"); - _manifest - .DefineStyle("TheBlogTheme") - .SetUrl("~/TheBlogTheme/css/styles.min.css", "~/TheBlogTheme/css/styles.css") - .SetVersion("6.0.7"); + _manifest.DefineStyle("TheBlogTheme").SetUrl("~/TheBlogTheme/css/styles.min.css", "~/TheBlogTheme/css/styles.css").SetVersion("6.0.7"); } public void Configure(ResourceManagementOptions options) diff --git a/src/OrchardCore.Themes/TheComingSoonTheme/ResourceManagementOptionsConfiguration.cs b/src/OrchardCore.Themes/TheComingSoonTheme/ResourceManagementOptionsConfiguration.cs index 67d84d51485..5d3f3514eef 100644 --- a/src/OrchardCore.Themes/TheComingSoonTheme/ResourceManagementOptionsConfiguration.cs +++ b/src/OrchardCore.Themes/TheComingSoonTheme/ResourceManagementOptionsConfiguration.cs @@ -14,18 +14,15 @@ static ResourceManagementOptionsConfiguration() _manifest .DefineScript("TheComingSoonTheme-bootstrap-bundle") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.js") - .SetCdnIntegrity("sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p", "sha384-8fq7CZc5BnER+jVlJI2Jafpbn4A9320TKhNJfYP33nneHep7sUg/OD30x7fK09pS") + .SetCdnIntegrity( + "sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p", + "sha384-8fq7CZc5BnER+jVlJI2Jafpbn4A9320TKhNJfYP33nneHep7sUg/OD30x7fK09pS" + ) .SetVersion("5.1.3"); - _manifest - .DefineScript("coming-soon") - .SetUrl("~/TheComingSoonTheme/js/scripts.min.js", "TheComingSoonTheme/js/scripts.js") - .SetVersion("6.0.5"); + _manifest.DefineScript("coming-soon").SetUrl("~/TheComingSoonTheme/js/scripts.min.js", "TheComingSoonTheme/js/scripts.js").SetVersion("6.0.5"); - _manifest - .DefineStyle("coming-soon") - .SetUrl("~/TheComingSoonTheme/css/styles.min.css", "TheComingSoonTheme/css/styles.css") - .SetVersion("6.0.5"); + _manifest.DefineStyle("coming-soon").SetUrl("~/TheComingSoonTheme/css/styles.min.css", "TheComingSoonTheme/css/styles.css").SetVersion("6.0.5"); _manifest .DefineStyle("TheComingSoonTheme-bootstrap-oc") diff --git a/src/OrchardCore.Themes/TheTheme/Startup.cs b/src/OrchardCore.Themes/TheTheme/Startup.cs index e397b2bc69d..84fc571b8ce 100644 --- a/src/OrchardCore.Themes/TheTheme/Startup.cs +++ b/src/OrchardCore.Themes/TheTheme/Startup.cs @@ -5,7 +5,5 @@ namespace OrchardCore.Themes.TheTheme; public class Startup : StartupBase { - public override void ConfigureServices(IServiceCollection serviceCollection) - { - } + public override void ConfigureServices(IServiceCollection serviceCollection) { } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/BackgroundJobs/HttpBackgroundJob.cs b/src/OrchardCore/OrchardCore.Abstractions/BackgroundJobs/HttpBackgroundJob.cs index 0b320cad0bf..6ba5cfb4442 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/BackgroundJobs/HttpBackgroundJob.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/BackgroundJobs/HttpBackgroundJob.cs @@ -84,7 +84,8 @@ await ShellScope.UsingChildScopeAsync(async scope => ex, "Error while executing the background job '{JobName}' after the end of the request on tenant '{TenantName}'.", jobName, - scope.ShellContext.Settings.Name); + scope.ShellContext.Settings.Name + ); } }); diff --git a/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/BackgroundTaskExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/BackgroundTaskExtensions.cs index 18ccbca6b90..b428aca1578 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/BackgroundTaskExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/BackgroundTaskExtensions.cs @@ -26,15 +26,10 @@ public static BackgroundTaskSettings GetDefaultSettings(this IBackgroundTask tas }; } - return new BackgroundTaskSettings() - { - Name = technicalName, - Title = technicalName, - }; + return new BackgroundTaskSettings() { Name = technicalName, Title = technicalName, }; } - public static IBackgroundTask GetTaskByName(this IEnumerable tasks, string name) - => tasks.LastOrDefault(task => task.GetTaskName() == name); + public static IBackgroundTask GetTaskByName(this IEnumerable tasks, string name) => tasks.LastOrDefault(task => task.GetTaskName() == name); public static string GetTaskName(this IBackgroundTask task) => task.GetType().FullName; } diff --git a/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/DistributedLockExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/DistributedLockExtensions.cs index aea9083cb65..9f46ad784a1 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/DistributedLockExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/DistributedLockExtensions.cs @@ -20,7 +20,8 @@ public static class DistributedLockExtensions return distributedLock.TryAcquireLockAsync( settings.Name + "_LOCK", TimeSpan.FromMilliseconds(settings.LockTimeout), - TimeSpan.FromMilliseconds(settings.LockExpiration)); + TimeSpan.FromMilliseconds(settings.LockExpiration) + ); } } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/ShellContextExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/ShellContextExtensions.cs index 5b039385e29..f38d9e99470 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/ShellContextExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/BackgroundTasks/ShellContextExtensions.cs @@ -13,12 +13,14 @@ public static class ShellContextExtensions public static HttpContext CreateHttpContext(this ShellContext shell) { var context = CreateHttpContext(shell.Settings); - context.Features.Set(new ShellContextFeature - { - ShellContext = shell, - OriginalPathBase = PathString.Empty, - OriginalPath = "/" - }); + context.Features.Set( + new ShellContextFeature + { + ShellContext = shell, + OriginalPathBase = PathString.Empty, + OriginalPath = "/" + } + ); return context; } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Extensions/ExtensionsEnvironmentExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Extensions/ExtensionsEnvironmentExtensions.cs index 6a38a11bb9b..13cf825d969 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Extensions/ExtensionsEnvironmentExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Extensions/ExtensionsEnvironmentExtensions.cs @@ -6,13 +6,9 @@ namespace OrchardCore.Environment.Extensions { public static class ExtensionsEnvironmentExtensions { - public static IFileInfo GetExtensionFileInfo( - this IHostEnvironment environment, - IExtensionInfo extensionInfo, - string subPath) + public static IFileInfo GetExtensionFileInfo(this IHostEnvironment environment, IExtensionInfo extensionInfo, string subPath) { - return environment.ContentRootFileProvider.GetFileInfo( - Path.Combine(extensionInfo.SubPath, subPath)); + return environment.ContentRootFileProvider.GetFileInfo(Path.Combine(extensionInfo.SubPath, subPath)); } } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Extensions/Features/IFeatureBuilderEvents.cs b/src/OrchardCore/OrchardCore.Abstractions/Extensions/Features/IFeatureBuilderEvents.cs index f4f78142016..c0df14d59e9 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Extensions/Features/IFeatureBuilderEvents.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Extensions/Features/IFeatureBuilderEvents.cs @@ -25,12 +25,8 @@ public class FeatureBuildingContext public abstract class FeatureBuilderEvents : IFeatureBuilderEvents { - public virtual void Building(FeatureBuildingContext context) - { - } + public virtual void Building(FeatureBuildingContext context) { } - public virtual void Built(IFeatureInfo featureInfo) - { - } + public virtual void Built(IFeatureInfo featureInfo) { } } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Extensions/Features/IFeaturesProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Extensions/Features/IFeaturesProvider.cs index 4db3f7b6ced..57eee2f85d9 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Extensions/Features/IFeaturesProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Extensions/Features/IFeaturesProvider.cs @@ -13,8 +13,6 @@ public interface IFeaturesProvider /// /// /// - IEnumerable GetFeatures( - IExtensionInfo extensionInfo, - IManifestInfo manifestInfo); + IEnumerable GetFeatures(IExtensionInfo extensionInfo, IManifestInfo manifestInfo); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/IdGenerator.cs b/src/OrchardCore/OrchardCore.Abstractions/IdGenerator.cs index 0c15928ad66..f5e5def19dd 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/IdGenerator.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/IdGenerator.cs @@ -11,43 +11,47 @@ public static string GenerateId() { var guid = Guid.NewGuid().ToByteArray(); - return string.Create(26, guid, (buffer, guid) => - { - var hs = BitConverter.ToInt64(guid, 0); - var ls = BitConverter.ToInt64(guid, 8); + return string.Create( + 26, + guid, + (buffer, guid) => + { + var hs = BitConverter.ToInt64(guid, 0); + var ls = BitConverter.ToInt64(guid, 8); - // Using a local copy prevents additional bound checks by the JIT. - var encode32Chars = _encode32Chars; + // Using a local copy prevents additional bound checks by the JIT. + var encode32Chars = _encode32Chars; - // A char array allows a long as the indexer, so without any cast. - buffer[0] = encode32Chars[(hs >> 60) & 31]; - buffer[1] = encode32Chars[(hs >> 55) & 31]; - buffer[2] = encode32Chars[(hs >> 50) & 31]; - buffer[3] = encode32Chars[(hs >> 45) & 31]; - buffer[4] = encode32Chars[(hs >> 40) & 31]; - buffer[5] = encode32Chars[(hs >> 35) & 31]; - buffer[6] = encode32Chars[(hs >> 30) & 31]; - buffer[7] = encode32Chars[(hs >> 25) & 31]; - buffer[8] = encode32Chars[(hs >> 20) & 31]; - buffer[9] = encode32Chars[(hs >> 15) & 31]; - buffer[10] = encode32Chars[(hs >> 10) & 31]; - buffer[11] = encode32Chars[(hs >> 5) & 31]; - buffer[12] = encode32Chars[hs & 31]; + // A char array allows a long as the indexer, so without any cast. + buffer[0] = encode32Chars[(hs >> 60) & 31]; + buffer[1] = encode32Chars[(hs >> 55) & 31]; + buffer[2] = encode32Chars[(hs >> 50) & 31]; + buffer[3] = encode32Chars[(hs >> 45) & 31]; + buffer[4] = encode32Chars[(hs >> 40) & 31]; + buffer[5] = encode32Chars[(hs >> 35) & 31]; + buffer[6] = encode32Chars[(hs >> 30) & 31]; + buffer[7] = encode32Chars[(hs >> 25) & 31]; + buffer[8] = encode32Chars[(hs >> 20) & 31]; + buffer[9] = encode32Chars[(hs >> 15) & 31]; + buffer[10] = encode32Chars[(hs >> 10) & 31]; + buffer[11] = encode32Chars[(hs >> 5) & 31]; + buffer[12] = encode32Chars[hs & 31]; - buffer[13] = encode32Chars[(ls >> 60) & 31]; - buffer[14] = encode32Chars[(ls >> 55) & 31]; - buffer[15] = encode32Chars[(ls >> 50) & 31]; - buffer[16] = encode32Chars[(ls >> 45) & 31]; - buffer[17] = encode32Chars[(ls >> 40) & 31]; - buffer[18] = encode32Chars[(ls >> 35) & 31]; - buffer[19] = encode32Chars[(ls >> 30) & 31]; - buffer[20] = encode32Chars[(ls >> 25) & 31]; - buffer[21] = encode32Chars[(ls >> 20) & 31]; - buffer[22] = encode32Chars[(ls >> 15) & 31]; - buffer[23] = encode32Chars[(ls >> 10) & 31]; - buffer[24] = encode32Chars[(ls >> 5) & 31]; - buffer[25] = encode32Chars[ls & 31]; - }); + buffer[13] = encode32Chars[(ls >> 60) & 31]; + buffer[14] = encode32Chars[(ls >> 55) & 31]; + buffer[15] = encode32Chars[(ls >> 50) & 31]; + buffer[16] = encode32Chars[(ls >> 45) & 31]; + buffer[17] = encode32Chars[(ls >> 40) & 31]; + buffer[18] = encode32Chars[(ls >> 35) & 31]; + buffer[19] = encode32Chars[(ls >> 30) & 31]; + buffer[20] = encode32Chars[(ls >> 25) & 31]; + buffer[21] = encode32Chars[(ls >> 20) & 31]; + buffer[22] = encode32Chars[(ls >> 15) & 31]; + buffer[23] = encode32Chars[(ls >> 10) & 31]; + buffer[24] = encode32Chars[(ls >> 5) & 31]; + buffer[25] = encode32Chars[ls & 31]; + } + ); } } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicArray.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicArray.cs index d975d859e65..019f9e6480c 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicArray.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicArray.cs @@ -35,10 +35,7 @@ public object? this[int index] return value; } - set - { - SetValue(index, value); - } + set { SetValue(index, value); } } public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object? result) diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicObject.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicObject.cs index 15b374b6b25..54e0a3b3d84 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicObject.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicObject.cs @@ -22,8 +22,7 @@ public class JsonDynamicObject : DynamicObject public int Count => _jsonObject.Count; - public void Merge(JsonNode? content, JsonMergeSettings? settings = null) => - _jsonObject.Merge(content, settings); + public void Merge(JsonNode? content, JsonMergeSettings? settings = null) => _jsonObject.Merge(content, settings); public object? this[string key] { @@ -37,10 +36,7 @@ public object? this[string key] return value; } - set - { - SetValue(key, value); - } + set { SetValue(key, value); } } public override bool TryGetMember(GetMemberBinder binder, out object? result) diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/JConvert.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/JConvert.cs index a8d330fa5e2..afb8a926e2e 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/JConvert.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/JConvert.cs @@ -11,14 +11,12 @@ public static class JConvert /// /// Converts the provided value into a . /// - public static string SerializeObject(TValue value, JsonSerializerOptions? options = null) - => JsonSerializer.Serialize(value, options ?? JOptions.Default); + public static string SerializeObject(TValue value, JsonSerializerOptions? options = null) => JsonSerializer.Serialize(value, options ?? JOptions.Default); /// /// Parses the text representing a single JSON value into a . /// - public static TValue? DeserializeObject(string json, JsonSerializerOptions? options = null) - => JsonSerializer.Deserialize(json, options ?? JOptions.Default); + public static TValue? DeserializeObject(string json, JsonSerializerOptions? options = null) => JsonSerializer.Deserialize(json, options ?? JOptions.Default); /// /// Attempts to read a value from a . diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/JOptions.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/JOptions.cs index f587531b902..8f2d63ce491 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/JOptions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/JOptions.cs @@ -10,15 +10,16 @@ namespace System.Text.Json; /// public static class JOptions { - public static readonly JsonSerializerOptions Base = new() - { - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - ReferenceHandler = ReferenceHandler.IgnoreCycles, - ReadCommentHandling = JsonCommentHandling.Skip, - PropertyNameCaseInsensitive = true, - AllowTrailingCommas = true, - WriteIndented = false - }; + public static readonly JsonSerializerOptions Base = + new() + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + ReferenceHandler = ReferenceHandler.IgnoreCycles, + ReadCommentHandling = JsonCommentHandling.Skip, + PropertyNameCaseInsensitive = true, + AllowTrailingCommas = true, + WriteIndented = false + }; public static readonly JsonSerializerOptions Default; public static readonly JsonSerializerOptions Indented; @@ -35,35 +36,16 @@ static JOptions() Default.Converters.Add(new DynamicJsonConverter()); Default.Converters.Add(new PathStringJsonConverter()); - Indented = new JsonSerializerOptions(Default) - { - WriteIndented = true, - }; + Indented = new JsonSerializerOptions(Default) { WriteIndented = true, }; - CamelCase = new JsonSerializerOptions(Default) - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - }; + CamelCase = new JsonSerializerOptions(Default) { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; - CamelCaseIndented = new JsonSerializerOptions(CamelCase) - { - WriteIndented = true, - }; + CamelCaseIndented = new JsonSerializerOptions(CamelCase) { WriteIndented = true, }; - UnsafeRelaxedJsonEscaping = new JsonSerializerOptions(Default) - { - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - }; + UnsafeRelaxedJsonEscaping = new JsonSerializerOptions(Default) { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; - Node = new JsonNodeOptions - { - PropertyNameCaseInsensitive = Default.PropertyNameCaseInsensitive, - }; + Node = new JsonNodeOptions { PropertyNameCaseInsensitive = Default.PropertyNameCaseInsensitive, }; - Document = new JsonDocumentOptions - { - CommentHandling = Default.ReadCommentHandling, - AllowTrailingCommas = Default.AllowTrailingCommas, - }; + Document = new JsonDocumentOptions { CommentHandling = Default.ReadCommentHandling, AllowTrailingCommas = Default.AllowTrailingCommas, }; } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/JsonDerivedTypesOptions.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/JsonDerivedTypesOptions.cs index 5d7be845c57..67035a7a849 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/JsonDerivedTypesOptions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/JsonDerivedTypesOptions.cs @@ -3,6 +3,7 @@ using System.Text.Json.Serialization; namespace OrchardCore.Json; + public class JsonDerivedTypesOptions { internal Dictionary> DerivedTypes { get; } = []; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JArray.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JArray.cs index 1a7a5082d3c..8ecc7d2413d 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JArray.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JArray.cs @@ -21,14 +21,13 @@ public static class JArray Stream utf8Json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default, - CancellationToken cancellationToken = default) - => (await JNode.LoadAsync(utf8Json, nodeOptions, documentOptions, cancellationToken))?.AsArray(); + CancellationToken cancellationToken = default + ) => (await JNode.LoadAsync(utf8Json, nodeOptions, documentOptions, cancellationToken))?.AsArray(); /// /// Loads a JSON array from the provided reader. /// - public static JsonArray? Load(ref Utf8JsonReader reader, JsonNodeOptions? nodeOptions = null) - => JNode.Load(ref reader, nodeOptions)?.AsArray(); + public static JsonArray? Load(ref Utf8JsonReader reader, JsonNodeOptions? nodeOptions = null) => JNode.Load(ref reader, nodeOptions)?.AsArray(); /// /// Parses text representing a single JSON array. @@ -43,16 +42,15 @@ public static class JArray /// /// Parses text representing a single JSON array. /// - public static JsonArray? Parse(string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) - => JNode.Parse(json, nodeOptions, documentOptions)?.AsArray(); + public static JsonArray? Parse(string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) => + JNode.Parse(json, nodeOptions, documentOptions)?.AsArray(); /// /// Tries to parse text representing a single JSON array. /// public static bool TryParse(string json, out JsonArray? jsonArray, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) { - if (!JNode.TryParse(json, out var jsonNode, nodeOptions, documentOptions) || - jsonNode is not JsonArray jArray) + if (!JNode.TryParse(json, out var jsonNode, nodeOptions, documentOptions) || jsonNode is not JsonArray jArray) { jsonArray = null; return false; @@ -245,8 +243,7 @@ public static bool ContainsValue(this JsonArray? jsonArray, JsonValue? value) if (existingItem is JsonValue || existingItem.GetValueKind() != item.GetValueKind()) { - if (item.GetValueKind() != JsonValueKind.Null || - settings?.MergeNullValueHandling == MergeNullValueHandling.Merge) + if (item.GetValueKind() != JsonValueKind.Null || settings?.MergeNullValueHandling == MergeNullValueHandling.Merge) { jsonArray[i] = item.Clone(); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JNode.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JNode.cs index b289d045206..dba0a7492cf 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JNode.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JNode.cs @@ -23,14 +23,13 @@ public static class JNode Stream utf8Json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default, - CancellationToken cancellationToken = default) - => (await JsonNode.ParseAsync(utf8Json, nodeOptions ?? JOptions.Node, documentOptions, cancellationToken)); + CancellationToken cancellationToken = default + ) => (await JsonNode.ParseAsync(utf8Json, nodeOptions ?? JOptions.Node, documentOptions, cancellationToken)); /// /// Loads a JSON node (including objects or arrays) from the provided reader. /// - public static JsonNode? Load(ref Utf8JsonReader reader, JsonNodeOptions? nodeOptions = null) - => JsonNode.Parse(ref reader, nodeOptions ?? JOptions.Node); + public static JsonNode? Load(ref Utf8JsonReader reader, JsonNodeOptions? nodeOptions = null) => JsonNode.Parse(ref reader, nodeOptions ?? JOptions.Node); /// /// Parses text representing a single JSON node. @@ -45,8 +44,8 @@ public static class JNode /// /// Parses text representing a single JSON node. /// - public static JsonNode? Parse(string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) - => JsonNode.Parse(json, nodeOptions ?? JOptions.Node, documentOptions); + public static JsonNode? Parse(string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) => + JsonNode.Parse(json, nodeOptions ?? JOptions.Node, documentOptions); /// /// Tries to parse text representing a single JSON node. @@ -96,20 +95,17 @@ public static bool TryParse(string json, out JsonNode? jsonNode, JsonNodeOptions /// /// Creates an instance of the specified type from this . /// - public static T? ToObject(this JsonNode? jsonNode, JsonSerializerOptions? options = null) => - jsonNode.Deserialize(options ?? JOptions.Default); + public static T? ToObject(this JsonNode? jsonNode, JsonSerializerOptions? options = null) => jsonNode.Deserialize(options ?? JOptions.Default); /// /// Creates an instance of the specified type from this . /// - public static object? ToObject(this JsonNode? jsonNode, Type type, JsonSerializerOptions? options = null) => - jsonNode.Deserialize(type, options ?? JOptions.Default); + public static object? ToObject(this JsonNode? jsonNode, Type type, JsonSerializerOptions? options = null) => jsonNode.Deserialize(type, options ?? JOptions.Default); /// /// Gets the value of the specified type of this . /// - public static T? Value(this JsonNode? jsonNode) => - jsonNode is JsonValue jsonValue && jsonValue.TryGetValue(out var value) ? value : default; + public static T? Value(this JsonNode? jsonNode) => jsonNode is JsonValue jsonValue && jsonValue.TryGetValue(out var value) ? value : default; /// /// Gets the value of the specified type of this . @@ -136,9 +132,7 @@ public static bool TryParse(string json, out JsonNode? jsonNode, JsonNodeOptions /// /// Whether this node contains elements or not. /// - public static bool HasValues(this JsonNode? jsonNode) => - jsonNode is JsonObject jsonObject && jsonObject.Count > 0 || - jsonNode is JsonArray jsonArray && jsonArray.Count > 0; + public static bool HasValues(this JsonNode? jsonNode) => jsonNode is JsonObject jsonObject && jsonObject.Count > 0 || jsonNode is JsonArray jsonArray && jsonArray.Count > 0; /// /// Gets the values of the specified type of this . diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JObject.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JObject.cs index 75c1285e3f5..0cf018335fc 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JObject.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JObject.cs @@ -21,14 +21,13 @@ public static class JObject Stream utf8Json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default, - CancellationToken cancellationToken = default) - => (await JNode.LoadAsync(utf8Json, nodeOptions, documentOptions, cancellationToken))?.AsObject(); + CancellationToken cancellationToken = default + ) => (await JNode.LoadAsync(utf8Json, nodeOptions, documentOptions, cancellationToken))?.AsObject(); /// /// Loads a JSON object from the provided reader. /// - public static JsonObject? Load(ref Utf8JsonReader reader, JsonNodeOptions? nodeOptions = null) - => JNode.Load(ref reader, nodeOptions)?.AsObject(); + public static JsonObject? Load(ref Utf8JsonReader reader, JsonNodeOptions? nodeOptions = null) => JNode.Load(ref reader, nodeOptions)?.AsObject(); /// /// Parses text representing a single JSON object. @@ -43,16 +42,15 @@ public static class JObject /// /// Parses text representing a single JSON object. /// - public static JsonObject? Parse(string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) - => JNode.Parse(json, nodeOptions, documentOptions)?.AsObject(); + public static JsonObject? Parse(string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) => + JNode.Parse(json, nodeOptions, documentOptions)?.AsObject(); /// /// Tries to parse text representing a single JSON object. /// public static bool TryParse(string json, out JsonObject? jsonObject, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) { - if (!JNode.TryParse(json, out var jsonNode, nodeOptions, documentOptions) || - jsonNode is not JsonObject jObject) + if (!JNode.TryParse(json, out var jsonNode, nodeOptions, documentOptions) || jsonNode is not JsonObject jObject) { jsonObject = null; return false; @@ -176,8 +174,7 @@ public static bool TryParse(string json, out JsonObject? jsonObject, JsonNodeOpt if (existingProperty is JsonValue || existingProperty.GetValueKind() != item.Value.GetValueKind()) { - if (item.Value.GetValueKind() != JsonValueKind.Null || - settings?.MergeNullValueHandling == MergeNullValueHandling.Merge) + if (item.Value.GetValueKind() != JsonValueKind.Null || settings?.MergeNullValueHandling == MergeNullValueHandling.Merge) { jsonObject[item.Key] = item.Value.Clone(); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JValue.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JValue.cs index 3fbcfefa18a..2734b1ae7f0 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JValue.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/Nodes/JValue.cs @@ -12,8 +12,8 @@ public static class JValue /// /// Parses text representing a single JSON value. /// - public static JsonValue? Parse(string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) - => JNode.Parse(json, nodeOptions, documentOptions)?.AsValue(); + public static JsonValue? Parse(string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) => + JNode.Parse(json, nodeOptions, documentOptions)?.AsValue(); /// /// Creates a from an object. diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/DynamicJsonConverter.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/DynamicJsonConverter.cs index 5d6651b18e9..04b0bf9f9d2 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/DynamicJsonConverter.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/DynamicJsonConverter.cs @@ -96,9 +96,6 @@ public class DynamicJsonConverter : JsonConverter } } - public override void Write( - Utf8JsonWriter writer, - object objectToWrite, - JsonSerializerOptions options) => + public override void Write(Utf8JsonWriter writer, object objectToWrite, JsonSerializerOptions options) => JsonSerializer.Serialize(writer, objectToWrite, objectToWrite.GetType(), options); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/JsonDerivedTypeInfo.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/JsonDerivedTypeInfo.cs index 32dfddea245..971ded66882 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/JsonDerivedTypeInfo.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/JsonDerivedTypeInfo.cs @@ -4,9 +4,9 @@ namespace System.Text.Json.Serialization; public class JsonDerivedTypeInfo : IJsonDerivedTypeInfo - where TDerived : class where TBase : class + where TDerived : class + where TBase : class { - private static readonly JsonDerivedType _instance = new(typeof(TDerived), CreateTypeDiscriminator()); public JsonDerivedType DerivedType => _instance; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/PathStringJsonConverter.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/PathStringJsonConverter.cs index e0cde2f1ff3..fb560dc55bc 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/PathStringJsonConverter.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/PathStringJsonConverter.cs @@ -21,6 +21,6 @@ public override PathString Read(ref Utf8JsonReader reader, Type typeToConvert, J return new PathString(result); } - public override void Write(Utf8JsonWriter writer, PathString value, JsonSerializerOptions options) - => JsonSerializer.Serialize(writer, value.ToString(), typeof(string), options); + public override void Write(Utf8JsonWriter writer, PathString value, JsonSerializerOptions options) => + JsonSerializer.Serialize(writer, value.ToString(), typeof(string), options); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/ServiceCollectionExtensions.cs index d3c5687a6b0..c010a2027b6 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Json/Serialization/ServiceCollectionExtensions.cs @@ -9,11 +9,10 @@ public static class ServiceCollectionExtensions /// Registers a JSON type resolver allowing to serialize a given type from its base type. /// public static IServiceCollection AddJsonDerivedTypeInfo(this IServiceCollection services) - where TDerived : class where TBase : class => - + where TDerived : class + where TBase : class => services.Configure(options => { - if (!options.DerivedTypes.TryGetValue(typeof(TBase), out var derivedTypes)) { derivedTypes = []; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Localization/CultureScope.cs b/src/OrchardCore/OrchardCore.Abstractions/Localization/CultureScope.cs index 10f5def0c77..75407e20fd8 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Localization/CultureScope.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Localization/CultureScope.cs @@ -41,8 +41,7 @@ private CultureScope(string culture, string uiCulture, bool ignoreSystemSettings /// /// The culture that will be used within the scope. /// Whether to ignore the system culture settings or not. Defaults to false. - public static CultureScope Create(string culture, bool ignoreSystemSettings = false) - => Create(culture, culture, ignoreSystemSettings); + public static CultureScope Create(string culture, bool ignoreSystemSettings = false) => Create(culture, culture, ignoreSystemSettings); /// /// Creates a scope with a given culture. @@ -50,16 +49,14 @@ public static CultureScope Create(string culture, bool ignoreSystemSettings = fa /// The culture that will be used within the scope. /// The UI culture that will be used within the scope. /// Whether to ignore the system culture settings or not. Defaults to false. - public static CultureScope Create(string culture, string uiCulture, bool ignoreSystemSettings = false) - => new(culture, uiCulture, ignoreSystemSettings); + public static CultureScope Create(string culture, string uiCulture, bool ignoreSystemSettings = false) => new(culture, uiCulture, ignoreSystemSettings); /// /// Creates a scope with a given culture. /// /// The culture that will be used within the scope. /// Whether to ignore the system culture settings or not. Defaults to false. - public static CultureScope Create(CultureInfo culture, bool ignoreSystemSettings = false) - => Create(culture, culture, ignoreSystemSettings); + public static CultureScope Create(CultureInfo culture, bool ignoreSystemSettings = false) => Create(culture, culture, ignoreSystemSettings); /// /// Creates a scope with a given culture. @@ -67,8 +64,7 @@ public static CultureScope Create(CultureInfo culture, bool ignoreSystemSettings /// The culture that will be used within the scope. /// The UI culture that will be used within the scope. /// Whether to ignore the system culture settings or not. Defaults to false. - public static CultureScope Create(CultureInfo culture, CultureInfo uiCulture, bool ignoreSystemSettings = false) - => new(culture.Name, uiCulture.Name, ignoreSystemSettings); + public static CultureScope Create(CultureInfo culture, CultureInfo uiCulture, bool ignoreSystemSettings = false) => new(culture.Name, uiCulture.Name, ignoreSystemSettings); /// public void Dispose() diff --git a/src/OrchardCore/OrchardCore.Abstractions/Localization/ILocalizationService.cs b/src/OrchardCore/OrchardCore.Abstractions/Localization/ILocalizationService.cs index 912296edbff..d49d5ce5f65 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Localization/ILocalizationService.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Localization/ILocalizationService.cs @@ -9,11 +9,7 @@ namespace OrchardCore.Localization /// public interface ILocalizationService { - private static readonly CultureInfo[] _cultureAliases = - [ - CultureInfo.GetCultureInfo("zh-CN"), - CultureInfo.GetCultureInfo("zh-TW") - ]; + private static readonly CultureInfo[] _cultureAliases = [CultureInfo.GetCultureInfo("zh-CN"), CultureInfo.GetCultureInfo("zh-TW")]; /// /// Returns the default culture of the site. @@ -30,9 +26,7 @@ public interface ILocalizationService /// static CultureInfo[] GetAllCulturesAndAliases() { - var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures) - .Union(_cultureAliases) - .OrderBy(c => c.Name); + var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures).Union(_cultureAliases).OrderBy(c => c.Name); return cultures.ToArray(); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Locking/Distributed/IDistributedLock.cs b/src/OrchardCore/OrchardCore.Abstractions/Locking/Distributed/IDistributedLock.cs index ea1cd729713..7bd69debf47 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Locking/Distributed/IDistributedLock.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Locking/Distributed/IDistributedLock.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Locking.Distributed { - public interface IDistributedLock : ILock - { - } + public interface IDistributedLock : ILock { } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Locking/ILocalLock.cs b/src/OrchardCore/OrchardCore.Abstractions/Locking/ILocalLock.cs index 544baa956c0..aee62755822 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Locking/ILocalLock.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Locking/ILocalLock.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Locking { - public interface ILocalLock : ILock - { - } + public interface ILocalLock : ILock { } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Locking/ILocker.cs b/src/OrchardCore/OrchardCore.Abstractions/Locking/ILocker.cs index 7d3efbc406c..ebc550dd836 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Locking/ILocker.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Locking/ILocker.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Locking { - public interface ILocker : IDisposable, IAsyncDisposable - { - } + public interface ILocker : IDisposable, IAsyncDisposable { } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Builder/OrchardCoreBuilder.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Builder/OrchardCoreBuilder.cs index 58d79ea341c..48101263a0c 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Builder/OrchardCoreBuilder.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Builder/OrchardCoreBuilder.cs @@ -20,7 +20,8 @@ public OrchardCoreBuilder(IServiceCollection services) public IServiceCollection ApplicationServices { get; } - public OrchardCoreBuilder RegisterStartup() where T : class, IStartup + public OrchardCoreBuilder RegisterStartup() + where T : class, IStartup { ApplicationServices.AddTransient(); return this; @@ -38,8 +39,7 @@ public OrchardCoreBuilder ConfigureServices(Action(sp => new StartupActionsStartup( - sp.GetRequiredService(), actions, order)); + ApplicationServices.AddTransient(sp => new StartupActionsStartup(sp.GetRequiredService(), actions, order)); } actions.ConfigureServicesActions.Add(configure); @@ -69,8 +69,7 @@ public OrchardCoreBuilder Configure(Action(sp => new StartupActionsStartup( - sp.GetRequiredService(), actions, order)); + ApplicationServices.AddTransient(sp => new StartupActionsStartup(sp.GetRequiredService(), actions, order)); } actions.ConfigureActions.Add(configure); @@ -109,8 +108,7 @@ public OrchardCoreBuilder Configure(Func(sp => new StartupActionsStartup( - sp.GetRequiredService(), actions, order)); + ApplicationServices.AddTransient(sp => new StartupActionsStartup(sp.GetRequiredService(), actions, order)); } actions.AsyncConfigureActions.Add(configureAsync); @@ -145,8 +143,7 @@ public OrchardCoreBuilder EnableFeature(string id) for (var index = 0; index < services.Count; index++) { var service = services[index]; - if (service.GetImplementationInstance() is ShellFeature feature && - string.Equals(feature.Id, id, StringComparison.OrdinalIgnoreCase)) + if (service.GetImplementationInstance() is ShellFeature feature && string.Equals(feature.Id, id, StringComparison.OrdinalIgnoreCase)) { return; } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Exceptions/ExceptionExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Exceptions/ExceptionExtensions.cs index 2ccbf4f59bb..2b71676cb55 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Exceptions/ExceptionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Exceptions/ExceptionExtensions.cs @@ -14,15 +14,9 @@ public static class ExceptionExtensions public static bool IsFatal(this Exception ex) { - return - ex is OutOfMemoryException || - ex is SecurityException || - ex is SEHException; + return ex is OutOfMemoryException || ex is SecurityException || ex is SEHException; } - public static bool IsFileSharingViolation(this Exception ex) => - ex is IOException && - (ex.HResult == ERROR_SHARING_VIOLATION || - ex.HResult == ERROR_LOCK_VIOLATION); + public static bool IsFileSharingViolation(this Exception ex) => ex is IOException && (ex.HResult == ERROR_SHARING_VIOLATION || ex.HResult == ERROR_LOCK_VIOLATION); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/EnumerableExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/EnumerableExtensions.cs index 987cea11774..d2d5b1b5466 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/EnumerableExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/EnumerableExtensions.cs @@ -14,16 +14,19 @@ public static Task ForEachAsync(this IEnumerable source, Func bod return Task.WhenAll( from partition in Partitioner.Create(source).GetPartitions(partitionCount) - select Task.Run(async delegate - { - using (partition) + select Task.Run( + async delegate { - while (partition.MoveNext()) + using (partition) { - await body(partition.Current); + while (partition.MoveNext()) + { + await body(partition.Current); + } } } - })); + ) + ); } } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/InvokeExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/InvokeExtensions.cs index eea7d4df0ed..63782298e32 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/InvokeExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/InvokeExtensions.cs @@ -160,7 +160,14 @@ public static async Task InvokeAsync(this IEnumerable /// /// Safely invoke methods by catching non fatal exceptions and logging them. /// - public static async Task InvokeAsync(this IEnumerable events, Func dispatch, T1 arg1, T2 arg2, T3 arg3, ILogger logger) + public static async Task InvokeAsync( + this IEnumerable events, + Func dispatch, + T1 arg1, + T2 arg2, + T3 arg3, + ILogger logger + ) { foreach (var sink in events) { @@ -178,7 +185,15 @@ public static async Task InvokeAsync(this IEnumerable /// Safely invoke methods by catching non fatal exceptions and logging them. /// - public static async Task InvokeAsync(this IEnumerable events, Func dispatch, T1 arg1, T2 arg2, T3 arg3, T4 arg4, ILogger logger) + public static async Task InvokeAsync( + this IEnumerable events, + Func dispatch, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + ILogger logger + ) { foreach (var sink in events) { @@ -196,7 +211,16 @@ public static async Task InvokeAsync(this IEnumerable /// Safely invoke methods by catching non fatal exceptions and logging them. /// - public static async Task InvokeAsync(this IEnumerable events, Func dispatch, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, ILogger logger) + public static async Task InvokeAsync( + this IEnumerable events, + Func dispatch, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + ILogger logger + ) { foreach (var sink in events) { @@ -231,7 +255,12 @@ public static async Task> InvokeAsync(thi return results; } - public static async Task> InvokeAsync(this IEnumerable events, Func> dispatch, T1 arg1, ILogger logger) + public static async Task> InvokeAsync( + this IEnumerable events, + Func> dispatch, + T1 arg1, + ILogger logger + ) { var results = new List(); @@ -251,7 +280,11 @@ public static async Task> InvokeAsync return results; } - public static async Task> InvokeAsync(this IEnumerable events, Func>> dispatch, ILogger logger) + public static async Task> InvokeAsync( + this IEnumerable events, + Func>> dispatch, + ILogger logger + ) { var results = new List(); @@ -275,10 +308,7 @@ public static void HandleException(Exception ex, ILogger logger, string sourceTy { if (IsLogged(ex)) { - logger.LogError(ex, "{Type} thrown from {Method} by {Exception}", - sourceType, - method, - ex.GetType().Name); + logger.LogError(ex, "{Type} thrown from {Method} by {Exception}", sourceType, method, ex.GetType().Name); } if (ex.IsFatal()) @@ -286,6 +316,7 @@ public static void HandleException(Exception ex, ILogger logger, string sourceTy throw ex; } } + private static bool IsLogged(Exception ex) { return !ex.IsFatal(); diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/StringExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/StringExtensions.cs index d003cd57928..61bca0bc714 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/StringExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/StringExtensions.cs @@ -14,19 +14,13 @@ public static string ToHexString(this byte[] bytes) public static byte[] ToByteArray(this string hex) { - return Enumerable.Range(0, hex.Length). - Where(x => 0 == x % 2). - Select(x => Convert.ToByte(hex.Substring(x, 2), 16)). - ToArray(); + return Enumerable.Range(0, hex.Length).Where(x => 0 == x % 2).Select(x => Convert.ToByte(hex.Substring(x, 2), 16)).ToArray(); } - public static bool EqualsOrdinalIgnoreCase(this string? a, string? b) - => string.Equals(a, b, StringComparison.OrdinalIgnoreCase); + public static bool EqualsOrdinalIgnoreCase(this string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase); - public static bool StartsWithOrdinalIgnoreCase(this string? a, string? b) => - a is not null && b is not null && a.StartsWith(b, StringComparison.OrdinalIgnoreCase); + public static bool StartsWithOrdinalIgnoreCase(this string? a, string? b) => a is not null && b is not null && a.StartsWith(b, StringComparison.OrdinalIgnoreCase); - public static bool EndsWithOrdinalIgnoreCase(this string? a, string? b) => - a is not null && b is not null && a.EndsWith(b, StringComparison.OrdinalIgnoreCase); + public static bool EndsWithOrdinalIgnoreCase(this string? a, string? b) => a is not null && b is not null && a.EndsWith(b, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/FileInfoExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/FileInfoExtensions.cs index 8e3c9826b0c..0e79677c5fd 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/FileInfoExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/FileInfoExtensions.cs @@ -7,8 +7,7 @@ namespace OrchardCore.Modules.FileProviders { public static class FileInfoExtensions { - public static IEnumerable ReadAllLines(this IFileInfo fileInfo) - => ReadAllLinesAsync(fileInfo).GetAwaiter().GetResult(); + public static IEnumerable ReadAllLines(this IFileInfo fileInfo) => ReadAllLinesAsync(fileInfo).GetAwaiter().GetResult(); public static async Task> ReadAllLinesAsync(this IFileInfo fileInfo) { diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/IStaticFileProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/IStaticFileProvider.cs index 7d7f6e254a1..dc863371dd8 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/IStaticFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/IStaticFileProvider.cs @@ -6,7 +6,5 @@ namespace OrchardCore.Modules.FileProviders /// This custom implementation provides Di registration identification /// for IStaticFileProviders that should be served via UseStaticFiles. /// - public interface IStaticFileProvider : IFileProvider - { - } + public interface IStaticFileProvider : IFileProvider { } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/NormalizedPaths.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/NormalizedPaths.cs index 61aea12344b..1db6c38c76e 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/NormalizedPaths.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/NormalizedPaths.cs @@ -10,8 +10,7 @@ public static class NormalizedPaths /// Use a collection of file paths to resolve files and subfolders directly under a given folder. /// Paths need to be normalized by using '/' for the directory separator and with no leading '/'. /// - public static void ResolveFolderContents(string folder, IEnumerable normalizedPaths, - out IEnumerable filePaths, out IEnumerable folderPaths) + public static void ResolveFolderContents(string folder, IEnumerable normalizedPaths, out IEnumerable filePaths, out IEnumerable folderPaths) { var files = new HashSet(StringComparer.Ordinal); var folders = new HashSet(StringComparer.Ordinal); diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/IModuleStaticFileProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/IModuleStaticFileProvider.cs index 5ef2150150f..477d9c89278 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/IModuleStaticFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/IModuleStaticFileProvider.cs @@ -7,7 +7,5 @@ namespace OrchardCore.Modules /// This custom implementation provides Di registration identification /// for IStaticFileProviders that should be served via UseStaticFiles. /// - public interface IModuleStaticFileProvider : IStaticFileProvider - { - } + public interface IModuleStaticFileProvider : IStaticFileProvider { } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/FeatureAttribute.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/FeatureAttribute.cs index 91b2a1ca47d..5f2388d3b2c 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/FeatureAttribute.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/FeatureAttribute.cs @@ -47,26 +47,8 @@ public FeatureAttribute() /// Whether feature is always enabled. /// Whether feature is enabled by dependency only. /// Supported types are and only. - public FeatureAttribute( - string id, - string description, - string featureDependencies, - object defaultTenant, - object alwaysEnabled, - object enabledByDependencyOnly - ) : this( - id, - default, - default, - default, - description, - featureDependencies, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly - ) - { - } + public FeatureAttribute(string id, string description, string featureDependencies, object defaultTenant, object alwaysEnabled, object enabledByDependencyOnly) + : this(id, default, default, default, description, featureDependencies, defaultTenant, alwaysEnabled, enabledByDependencyOnly) { } /// /// Constructs an instance of the attribute with some default values. @@ -83,27 +65,8 @@ object enabledByDependencyOnly /// Supported types are and only. /// Whether feature is enabled by dependency only. /// Supported types are and only. - public FeatureAttribute( - string id, - string name, - string description, - string featureDependencies, - object defaultTenant, - object alwaysEnabled, - object enabledByDependencyOnly - ) : this( - id, - name, - default, - default, - description, - featureDependencies, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly - ) - { - } + public FeatureAttribute(string id, string name, string description, string featureDependencies, object defaultTenant, object alwaysEnabled, object enabledByDependencyOnly) + : this(id, name, default, default, description, featureDependencies, defaultTenant, alwaysEnabled, enabledByDependencyOnly) { } /// /// Constructs an instance of the attribute with some default values. @@ -167,10 +130,7 @@ public virtual string Id // Guards setting Id with strictly invalid values. if (string.IsNullOrEmpty(value)) { - throw new InvalidOperationException($"When '{nameof(Id)}' has been provided it should not be null or empty.") - { - Data = { { nameof(value), value } } - }; + throw new InvalidOperationException($"When '{nameof(Id)}' has been provided it should not be null or empty.") { Data = { { nameof(value), value } } }; } _id = value; @@ -226,9 +186,7 @@ protected static IEnumerable GetValues(params T[] values) internal virtual string Describe(params FeatureAttribute[] additionalFeatures) { static bool IsNotNullOrEmpty(string s) => !string.IsNullOrEmpty(s); - var firstOrDefaultResult = GetValues(this).Concat(additionalFeatures) - .Select(feature => feature.Description) - .FirstOrDefault(IsNotNullOrEmpty); + var firstOrDefaultResult = GetValues(this).Concat(additionalFeatures).Select(feature => feature.Description).FirstOrDefault(IsNotNullOrEmpty); return firstOrDefaultResult ?? DefaultDescription; } @@ -294,9 +252,7 @@ public virtual string[] Dependencies /// internal virtual int Prioritize(params FeatureAttribute[] additionalFeatures) { - var firstPriority = GetValues(this).Concat(additionalFeatures) - .Select(feature => feature.InternalPriority) - .FirstOrDefault(priority => priority.HasValue); + var firstPriority = GetValues(this).Concat(additionalFeatures).Select(feature => feature.InternalPriority).FirstOrDefault(priority => priority.HasValue); return firstPriority ?? DefaultPriority; } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ManifestConstants.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ManifestConstants.cs index e01761f5c0f..81e29cba24b 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ManifestConstants.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ManifestConstants.cs @@ -1,4 +1,3 @@ - namespace OrchardCore.Modules.Manifest; public static class ManifestConstants diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleAttribute.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleAttribute.cs index 79ef52a3d1a..c0fedc39d8a 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleAttribute.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleAttribute.cs @@ -22,9 +22,8 @@ public class ModuleAttribute : FeatureAttribute /// /// Default parameterless ctor. /// - public ModuleAttribute() : base() - { - } + public ModuleAttribute() + : base() { } /// /// Ctor allowing , as well as defaults for @@ -59,23 +58,8 @@ public ModuleAttribute( object defaultTenant, object alwaysEnabled, object enabledByDependencyOnly - ) : this( - id, - default, - default, - default, - description, - author, - semVer, - websiteUrl, - featureDependencies, - tags, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly ) - { - } + : this(id, default, default, default, description, author, semVer, websiteUrl, featureDependencies, tags, defaultTenant, alwaysEnabled, enabledByDependencyOnly) { } /// /// Ctor allowing , as well as defaults for @@ -113,23 +97,8 @@ public ModuleAttribute( object defaultTenant, object alwaysEnabled, object enabledByDependencyOnly - ) : this( - id, - name, - default, - default, - description, - author, - semVer, - websiteUrl, - featureDependencies, - tags, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly ) - { - } + : this(id, name, default, default, description, author, semVer, websiteUrl, featureDependencies, tags, defaultTenant, alwaysEnabled, enabledByDependencyOnly) { } /// /// Ctor allowing , as well as defaults for @@ -171,17 +140,8 @@ public ModuleAttribute( object defaultTenant, object alwaysEnabled, object enabledByDependencyOnly - ) : base( - id, - name, - category, - priority, - description, - featureDependencies, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly ) + : base(id, name, category, priority, description, featureDependencies, defaultTenant, alwaysEnabled, enabledByDependencyOnly) { Author = author; Website = websiteUrl; @@ -231,21 +191,8 @@ public ModuleAttribute( object defaultTenant, object alwaysEnabled, object enabledByDependencyOnly - ) : this( - id, - name, - category, - priority, - description, - author, - semVer, - websiteUrl, - featureDependencies, - tags, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly ) + : this(id, name, category, priority, description, author, semVer, websiteUrl, featureDependencies, tags, defaultTenant, alwaysEnabled, enabledByDependencyOnly) { type = (type ?? string.Empty).Trim(); _type = string.IsNullOrEmpty(type) ? null : type; @@ -262,11 +209,7 @@ protected internal static string GetAttributePrefix(Type attributeType) const string attributeSuffix = nameof(Attribute); // Drops the 'Attribute' suffix from the conventional abbreviation, or leaves it alone - static string GetTypeNamePrefix(string typeName) => - typeName.EndsWith(attributeSuffix) - ? typeName[..^attributeSuffix.Length] - : typeName - ; + static string GetTypeNamePrefix(string typeName) => typeName.EndsWith(attributeSuffix) ? typeName[..^attributeSuffix.Length] : typeName; return GetTypeNamePrefix(attributeType.Name); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleMarkerAttribute.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleMarkerAttribute.cs index bcbac3e58e8..347dd71499f 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleMarkerAttribute.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleMarkerAttribute.cs @@ -13,10 +13,7 @@ public class ModuleMarkerAttribute : ModuleAttribute /// /// The identifier for the Module. /// Allows authors to specify a module specific Type. - public ModuleMarkerAttribute( - string id, - string type - ) + public ModuleMarkerAttribute(string id, string type) { Id = id; Type = type; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs index e4af891e4c8..f4d64012b9f 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs @@ -41,20 +41,18 @@ private void EnsureInitialized() private ConcurrentBag GetModules() { - var modules = new ConcurrentBag - { - new(_environment.ApplicationName, true), - }; + var modules = new ConcurrentBag { new(_environment.ApplicationName, true), }; - var names = _moduleNamesProviders - .SelectMany(p => p.GetModuleNames()) - .Where(n => n != _environment.ApplicationName) - .Distinct(); + var names = _moduleNamesProviders.SelectMany(p => p.GetModuleNames()).Where(n => n != _environment.ApplicationName).Distinct(); - Parallel.ForEach(names, new ParallelOptions { MaxDegreeOfParallelism = 8 }, (name) => - { - modules.Add(new Module(name, false)); - }); + Parallel.ForEach( + names, + new ParallelOptions { MaxDegreeOfParallelism = 8 }, + (name) => + { + modules.Add(new Module(name, false)); + } + ); return modules; } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Module.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Module.cs index 9064da4e837..d54724d5798 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Module.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Module.cs @@ -33,8 +33,7 @@ public Module(string assemblyName, bool isApplication = false) { Assembly = Assembly.Load(new AssemblyName(assemblyName)); - Assets = Assembly.GetCustomAttributes() - .Select(a => new Asset(a.Asset)).ToArray(); + Assets = Assembly.GetCustomAttributes().Select(a => new Asset(a.Asset)).ToArray(); AssetPaths = Assets.Select(a => a.ModuleAssetPath).ToArray(); @@ -47,8 +46,7 @@ public Module(string assemblyName, bool isApplication = false) // This is better use the default parameterless ctor and assign the property. ?? new ModuleAttribute() { Name = assemblyName }; - var features = Assembly.GetCustomAttributes() - .Where(f => f is not ModuleAttribute).ToList(); + var features = Assembly.GetCustomAttributes().Where(f => f is not ModuleAttribute).ToList(); if (isApplication) { @@ -59,30 +57,36 @@ public Module(string assemblyName, bool isApplication = false) ModuleInfo.DefaultTenantOnly = true; // Adds the application primary feature. - features.Insert(0, new Manifest.FeatureAttribute( - assemblyName, - Application.ModuleName, - Application.ModuleCategory, - Application.ModulePriority, - Application.ModuleDescription, - null, - true, - default, - default - )); + features.Insert( + 0, + new Manifest.FeatureAttribute( + assemblyName, + Application.ModuleName, + Application.ModuleCategory, + Application.ModulePriority, + Application.ModuleDescription, + null, + true, + default, + default + ) + ); // Adds the application default feature. - features.Insert(1, new Manifest.FeatureAttribute( - Application.DefaultFeatureId, - Application.DefaultFeatureName, - Application.ModuleCategory, - Application.ModulePriority, - Application.DefaultFeatureDescription, - null, - true, - default, - default - )); + features.Insert( + 1, + new Manifest.FeatureAttribute( + Application.DefaultFeatureId, + Application.DefaultFeatureName, + Application.ModuleCategory, + Application.ModulePriority, + Application.DefaultFeatureDescription, + null, + true, + default, + default + ) + ); } ModuleInfo.Features.AddRange(features); @@ -113,12 +117,8 @@ public Module(string assemblyName, bool isApplication = false) { _lastModified = File.GetLastWriteTimeUtc(Assembly.Location); } - catch (PathTooLongException) - { - } - catch (UnauthorizedAccessException) - { - } + catch (PathTooLongException) { } + catch (UnauthorizedAccessException) { } } } @@ -151,8 +151,7 @@ public IFileInfo GetFileInfo(string subpath) return new NotFoundFileInfo(fileName); } - _fileInfos[subpath] = fileInfo = new EmbeddedResourceFileInfo( - Assembly, resourcePath, fileName, _lastModified); + _fileInfos[subpath] = fileInfo = new EmbeddedResourceFileInfo(Assembly, resourcePath, fileName, _lastModified); } } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleCompositeStaticFileProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleCompositeStaticFileProvider.cs index 7bfb358df8b..c588aa488cb 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleCompositeStaticFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleCompositeStaticFileProvider.cs @@ -10,11 +10,10 @@ namespace OrchardCore.Modules /// public class ModuleCompositeStaticFileProvider : CompositeFileProvider, IModuleStaticFileProvider { - public ModuleCompositeStaticFileProvider(params IStaticFileProvider[] fileProviders) : base(fileProviders) - { - } - public ModuleCompositeStaticFileProvider(IEnumerable fileProviders) : base(fileProviders) - { - } + public ModuleCompositeStaticFileProvider(params IStaticFileProvider[] fileProviders) + : base(fileProviders) { } + + public ModuleCompositeStaticFileProvider(IEnumerable fileProviders) + : base(fileProviders) { } } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleProjectStaticFileProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleProjectStaticFileProvider.cs index 6d8aea13989..3122ac18078 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleProjectStaticFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleProjectStaticFileProvider.cs @@ -37,15 +37,13 @@ public ModuleProjectStaticFileProvider(IApplicationContext applicationContext) { // If the module and the application assemblies are not at the same location, // this means that the module is referenced as a package, not as a project in dev. - if (module.Assembly == null || Path.GetDirectoryName(module.Assembly.Location) - != Path.GetDirectoryName(application.Assembly.Location)) + if (module.Assembly == null || Path.GetDirectoryName(module.Assembly.Location) != Path.GetDirectoryName(application.Assembly.Location)) { continue; } // Get the 1st module asset under "Areas/{ModuleId}/wwwroot/". - var asset = module.Assets.FirstOrDefault(a => a.ModuleAssetPath - .StartsWith(module.Root + Module.WebRoot, StringComparison.Ordinal)); + var asset = module.Assets.FirstOrDefault(a => a.ModuleAssetPath.StartsWith(module.Root + Module.WebRoot, StringComparison.Ordinal)); if (asset != null) { diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonConfigurationExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonConfigurationExtensions.cs index 1fd5fce5483..555d08dc88e 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonConfigurationExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonConfigurationExtensions.cs @@ -91,8 +91,8 @@ public static IConfigurationBuilder AddTenantJsonFile(this IConfigurationBuilder /// The to add to. /// Configures the source. /// The . - public static IConfigurationBuilder AddTenantJsonFile(this IConfigurationBuilder builder, Action? configureSource) - => builder.Add(configureSource); + public static IConfigurationBuilder AddTenantJsonFile(this IConfigurationBuilder builder, Action? configureSource) => + builder.Add(configureSource); /// /// Adds a JSON configuration source to . diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonConfigurationProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonConfigurationProvider.cs index fa5c5fd7b54..3b152329bb0 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonConfigurationProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonConfigurationProvider.cs @@ -12,7 +12,8 @@ public class TenantJsonConfigurationProvider : FileConfigurationProvider /// Initializes a new instance with the specified source. /// /// The source settings. - public TenantJsonConfigurationProvider(TenantJsonConfigurationSource source) : base(source) { } + public TenantJsonConfigurationProvider(TenantJsonConfigurationSource source) + : base(source) { } /// /// Loads the JSON data from a stream. diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonStreamConfigurationProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonStreamConfigurationProvider.cs index 41d6a3280c6..6ff931c60f2 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonStreamConfigurationProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonStreamConfigurationProvider.cs @@ -15,7 +15,8 @@ public class TenantJsonStreamConfigurationProvider : StreamConfigurationProvider /// Constructor. /// /// The . - public TenantJsonStreamConfigurationProvider(TenantJsonStreamConfigurationSource source) : base(source) { } + public TenantJsonStreamConfigurationProvider(TenantJsonStreamConfigurationSource source) + : base(source) { } /// /// Loads json configuration key/values from a stream into a provider. diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonStreamConfigurationSource.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonStreamConfigurationSource.cs index be5d67d5c6a..9996521dab7 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonStreamConfigurationSource.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Overrides/Configuration/TenantJsonStreamConfigurationSource.cs @@ -13,7 +13,6 @@ public class TenantJsonStreamConfigurationSource : StreamConfigurationSource /// /// The . /// An . - public override IConfigurationProvider Build(IConfigurationBuilder builder) - => new TenantJsonStreamConfigurationProvider(this); + public override IConfigurationProvider Build(IConfigurationBuilder builder) => new TenantJsonStreamConfigurationProvider(this); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/RequireFeaturesAttribute.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/RequireFeaturesAttribute.cs index 3c892e05b1c..28ef4dd26a9 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/RequireFeaturesAttribute.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/RequireFeaturesAttribute.cs @@ -19,10 +19,7 @@ public RequireFeaturesAttribute(string featureName) public RequireFeaturesAttribute(string featureName, params string[] otherFeatureNames) { - RequiredFeatureNames = new List(otherFeatureNames) - { - featureName - }; + RequiredFeatureNames = new List(otherFeatureNames) { featureName }; } /// diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/ShellRequestPipeline.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/ShellRequestPipeline.cs index dbadf6ac420..eddb8e24beb 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/ShellRequestPipeline.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/ShellRequestPipeline.cs @@ -7,6 +7,7 @@ namespace OrchardCore.Modules public class ShellRequestPipeline : IShellPipeline { public RequestDelegate Next { get; set; } + public Task Invoke(object context) => Next(context as HttpContext); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/StartupBase.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/StartupBase.cs index 97087c5dbbd..6f2f298d209 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/StartupBase.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/StartupBase.cs @@ -15,14 +15,10 @@ public abstract class StartupBase : IStartup, IAsyncStartup public virtual int ConfigureOrder => Order; /// - public virtual void ConfigureServices(IServiceCollection services) - { - } + public virtual void ConfigureServices(IServiceCollection services) { } /// - public virtual void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) - { - } + public virtual void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { } /// public virtual ValueTask ConfigureAsync(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) => default; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Pooling/ZStringWriter.cs b/src/OrchardCore/OrchardCore.Abstractions/Pooling/ZStringWriter.cs index e68ce00b898..c4fbe7e463b 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Pooling/ZStringWriter.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Pooling/ZStringWriter.cs @@ -17,11 +17,11 @@ internal sealed class ZStringWriter : TextWriter private bool _isOpen; private UnicodeEncoding _encoding; - public ZStringWriter() : this(CultureInfo.CurrentCulture) - { - } + public ZStringWriter() + : this(CultureInfo.CurrentCulture) { } - public ZStringWriter(IFormatProvider formatProvider) : base(formatProvider) + public ZStringWriter(IFormatProvider formatProvider) + : base(formatProvider) { _sb = ZString.CreateStringBuilder(); _isOpen = true; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredMatcherPolicy.cs b/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredMatcherPolicy.cs index 6d082488154..4a997f4672d 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredMatcherPolicy.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredMatcherPolicy.cs @@ -9,9 +9,7 @@ namespace OrchardCore.Routing { public class FormValueRequiredMatcherPolicy : MatcherPolicy, IEndpointSelectorPolicy, IEndpointComparerPolicy { - public FormValueRequiredMatcherPolicy() - { - } + public FormValueRequiredMatcherPolicy() { } public override int Order => int.MinValue + 100; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Routing/IShellRouteValuesAddressScheme.cs b/src/OrchardCore/OrchardCore.Abstractions/Routing/IShellRouteValuesAddressScheme.cs index 882de26f2a0..1e749c2746b 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Routing/IShellRouteValuesAddressScheme.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Routing/IShellRouteValuesAddressScheme.cs @@ -5,7 +5,5 @@ namespace OrchardCore.Routing /// /// Marker interface to retrieve tenant 'RouteValuesAddress' schemes used for link generation. /// - public interface IShellRouteValuesAddressScheme : IEndpointAddressScheme - { - } + public interface IShellRouteValuesAddressScheme : IEndpointAddressScheme { } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Routing/ShellRouteValuesAddressScheme.cs b/src/OrchardCore/OrchardCore.Abstractions/Routing/ShellRouteValuesAddressScheme.cs index 55e657cc13a..0e7971bdb31 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Routing/ShellRouteValuesAddressScheme.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Routing/ShellRouteValuesAddressScheme.cs @@ -44,8 +44,8 @@ public IEnumerable FindEndpoints(RouteValuesAddress address) lock (this) { // Try once to get and cache the default scheme but not me. - _defaultScheme = _httpContextAccessor.HttpContext?.RequestServices - .GetServices>() + _defaultScheme = _httpContextAccessor + .HttpContext?.RequestServices.GetServices>() .Where(scheme => scheme.GetType() != GetType()) .LastOrDefault(); diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/IAsyncConfigureOptions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/IAsyncConfigureOptions.cs index 3567382bb4e..92a896993ba 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/IAsyncConfigureOptions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/IAsyncConfigureOptions.cs @@ -5,7 +5,8 @@ namespace Microsoft.Extensions.Options; /// /// Used to configure asynchronously a type of options just after a tenant container is created. /// -public interface IAsyncConfigureOptions where TOptions : class, IAsyncOptions +public interface IAsyncConfigureOptions + where TOptions : class, IAsyncOptions { /// /// Configures asynchronously an options instance. diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/IAsyncOptions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/IAsyncOptions.cs index 5c6fb037f5e..d63198d4cd7 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/IAsyncOptions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/IAsyncOptions.cs @@ -4,6 +4,4 @@ namespace Microsoft.Extensions.Options; /// Marks a type of options intended to be registered as a singleton and configured asynchronously /// by an just after a tenant container is created. /// -public interface IAsyncOptions -{ -} +public interface IAsyncOptions { } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceCollectionExtensions.cs index 88350dd775e..9fca978edff 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceCollectionExtensions.cs @@ -11,14 +11,13 @@ public static class ServiceCollectionExtensions /// /// Registers a delegate to be invoked asynchronously just after a tenant container is created. /// - public static IServiceCollection Initialize(this IServiceCollection services, Func initializeAsync) - => services.Configure(options => options.Initializers.Add(initializeAsync)); + public static IServiceCollection Initialize(this IServiceCollection services, Func initializeAsync) => + services.Configure(options => options.Initializers.Add(initializeAsync)); /// /// Registers a delegate used to configure asynchronously a type of options just after a tenant container is created. /// - public static IServiceCollection Configure( - this IServiceCollection services, Func configureAsync) + public static IServiceCollection Configure(this IServiceCollection services, Func configureAsync) where TOptions : class, IAsyncOptions, new() { if (!services.Any(d => d.ServiceType == typeof(TOptions))) @@ -40,7 +39,8 @@ public static IServiceCollection Configure( /// asynchronously a type of options just after a tenant container is created. /// public static IServiceCollection Configure(this IServiceCollection services) - where TOptions : class, IAsyncOptions, new() where TConfigure : IAsyncConfigureOptions + where TOptions : class, IAsyncOptions, new() + where TConfigure : IAsyncConfigureOptions { if (!services.Any(d => d.ServiceType == typeof(TOptions))) { diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceDescriptorExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceDescriptorExtensions.cs index 0ccaa55b924..2971fbe6f6d 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceDescriptorExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceDescriptorExtensions.cs @@ -33,13 +33,11 @@ public static class ServiceDescriptorExtensions return null; } - public static object? GetImplementationInstance(this ServiceDescriptor serviceDescriptor) => serviceDescriptor.IsKeyedService - ? serviceDescriptor.KeyedImplementationInstance - : serviceDescriptor.ImplementationInstance; + public static object? GetImplementationInstance(this ServiceDescriptor serviceDescriptor) => + serviceDescriptor.IsKeyedService ? serviceDescriptor.KeyedImplementationInstance : serviceDescriptor.ImplementationInstance; - public static object? GetImplementationFactory(this ServiceDescriptor serviceDescriptor) => serviceDescriptor.IsKeyedService - ? serviceDescriptor.KeyedImplementationFactory - : serviceDescriptor.ImplementationFactory; + public static object? GetImplementationFactory(this ServiceDescriptor serviceDescriptor) => + serviceDescriptor.IsKeyedService ? serviceDescriptor.KeyedImplementationFactory : serviceDescriptor.ImplementationFactory; public static bool TryGetImplementationType(this ServiceDescriptor serviceDescriptor, out Type? type) { @@ -62,9 +60,8 @@ public static bool TryGetImplementationFactory(this ServiceDescriptor serviceDes return factory is not null; } - internal static Type? GetImplementationTypeInternal(this ServiceDescriptor serviceDescriptor) => serviceDescriptor.IsKeyedService - ? serviceDescriptor.KeyedImplementationType - : serviceDescriptor.ImplementationType; + internal static Type? GetImplementationTypeInternal(this ServiceDescriptor serviceDescriptor) => + serviceDescriptor.IsKeyedService ? serviceDescriptor.KeyedImplementationType : serviceDescriptor.ImplementationType; internal static bool TryGetImplementationTypeInternal(this ServiceDescriptor serviceDescriptor, out Type? type) { diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceProviderExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceProviderExtensions.cs index e4e22aee29b..6ce17a32b63 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceProviderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/Extensions/ServiceProviderExtensions.cs @@ -10,7 +10,8 @@ public static class ServiceProviderExtensions /// /// Instantiates a new object of the specified type, but with support for constructor injection. /// - public static TResult CreateInstance(this IServiceProvider provider) where TResult : class + public static TResult CreateInstance(this IServiceProvider provider) + where TResult : class { return CreateInstance(provider, typeof(TResult)); } @@ -18,7 +19,8 @@ public static TResult CreateInstance(this IServiceProvider provider) wh /// /// Instantiates a new object of the specified type, but with support for constructor injection. /// - public static TResult CreateInstance(this IServiceProvider provider, Type type) where TResult : class + public static TResult CreateInstance(this IServiceProvider provider, Type type) + where TResult : class { return (TResult)ActivatorUtilities.CreateInstance(provider, type); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/IShellContainerFactory.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/IShellContainerFactory.cs index 763cb391457..1e436c21b23 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/IShellContainerFactory.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/IShellContainerFactory.cs @@ -12,7 +12,7 @@ public interface IShellContainerFactory public static class ShellContainerFactoryExtensions { [Obsolete("This method will be removed in a future version, use CreateContainerAsync instead.", false)] - public static IServiceProvider CreateContainer(this IShellContainerFactory factory, ShellSettings settings, ShellBlueprint blueprint) - => factory.CreateContainerAsync(settings, blueprint).GetAwaiter().GetResult(); + public static IServiceProvider CreateContainer(this IShellContainerFactory factory, ShellSettings settings, ShellBlueprint blueprint) => + factory.CreateContainerAsync(settings, blueprint).GetAwaiter().GetResult(); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/ShellContextExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/ShellContextExtensions.cs index 61e5c6561c9..5ad3a930574 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/ShellContextExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Builders/ShellContextExtensions.cs @@ -20,7 +20,8 @@ public static class ShellContextExtensions ? (ILock)shellContext.ServiceProvider.GetRequiredService() : shellContext.ServiceProvider.GetRequiredService(); - TimeSpan timeout, expiration; + TimeSpan timeout, + expiration; if (lockService is ILocalLock) { // If it is a local lock, don't use any timeout and expiration. @@ -42,7 +43,8 @@ public static class ShellContextExtensions /// public static Task<(ILocker locker, bool locked)> TryAcquireShellRemovingLockAsync(this ShellContext shellContext) { - TimeSpan timeout, expiration; + TimeSpan timeout, + expiration; var lockService = shellContext.ServiceProvider.GetRequiredService(); if (lockService is ILocalLock) @@ -65,21 +67,18 @@ public static class ShellContextExtensions /// Creates a on this shell context. /// [Obsolete("This method will be removed in a future version, use CreateScopeAsync instead.", false)] - public static ShellScope CreateScope(this ShellContext shellContext) => - shellContext.CreateScopeAsync().GetAwaiter().GetResult(); + public static ShellScope CreateScope(this ShellContext shellContext) => shellContext.CreateScopeAsync().GetAwaiter().GetResult(); /// /// Mark the as released and then a candidate to be disposed. /// [Obsolete("This method will be removed in a future version, use ReleaseAsync instead.", false)] - public static void Release(this ShellContext shellContext) => - shellContext.ReleaseInternalAsync().GetAwaiter().GetResult(); + public static void Release(this ShellContext shellContext) => shellContext.ReleaseInternalAsync().GetAwaiter().GetResult(); /// /// Registers the specified shellContext as dependent such that it is also released when the current shell context is released. /// [Obsolete("This method will be removed in a future version, use AddDependentShellAsync instead.", false)] - public static void AddDependentShell(this ShellContext shellContext) => - shellContext.AddDependentShellAsync(shellContext).GetAwaiter().GetResult(); + public static void AddDependentShell(this ShellContext shellContext) => shellContext.AddDependentShellAsync(shellContext).GetAwaiter().GetResult(); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/IShellConfiguration.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/IShellConfiguration.cs index 7de9e393065..a30c20d072c 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/IShellConfiguration.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/IShellConfiguration.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Environment.Shell.Configuration { - public interface IShellConfiguration : IConfiguration - { - } + public interface IShellConfiguration : IConfiguration { } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/ConfigurationExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/ConfigurationExtensions.cs index 8948004b2b4..9d2c03bd1d7 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/ConfigurationExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/ConfigurationExtensions.cs @@ -81,9 +81,7 @@ public static JsonNode ToJsonNode(this IConfiguration configuration) public static JsonObject ToJsonObject(this IDictionary configurationData) { - var configuration = new ConfigurationBuilder() - .Add(new UpdatableDataProvider(configurationData)) - .Build(); + var configuration = new ConfigurationBuilder().Add(new UpdatableDataProvider(configurationData)).Build(); using var disposable = configuration as IDisposable; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/JsonConfigurationParser.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/JsonConfigurationParser.cs index 0ab3d1a1d41..9731ae83f48 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/JsonConfigurationParser.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/JsonConfigurationParser.cs @@ -17,19 +17,13 @@ private JsonConfigurationParser() { } private readonly Dictionary _data = new(StringComparer.OrdinalIgnoreCase); private readonly Stack _paths = new(); - public static IDictionary Parse(Stream input) - => new JsonConfigurationParser().ParseStream(input); + public static IDictionary Parse(Stream input) => new JsonConfigurationParser().ParseStream(input); - public static Task> ParseAsync(Stream input) - => new JsonConfigurationParser().ParseStreamAsync(input); + public static Task> ParseAsync(Stream input) => new JsonConfigurationParser().ParseStreamAsync(input); private Dictionary ParseStream(Stream input) { - var jsonDocumentOptions = new JsonDocumentOptions - { - CommentHandling = JsonCommentHandling.Skip, - AllowTrailingCommas = true, - }; + var jsonDocumentOptions = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, }; try { @@ -54,11 +48,7 @@ private JsonConfigurationParser() { } private async Task> ParseStreamAsync(Stream input) { - var jsonDocumentOptions = new JsonDocumentOptions - { - CommentHandling = JsonCommentHandling.Skip, - AllowTrailingCommas = true, - }; + var jsonDocumentOptions = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, }; try { @@ -158,10 +148,7 @@ private void VisitValue(JsonElement value, bool visitArray = false) } } - private void EnterContext(string context) => - _paths.Push(_paths.Count > 0 ? - _paths.Peek() + ConfigurationPath.KeyDelimiter + context : - context); + private void EnterContext(string context) => _paths.Push(_paths.Count > 0 ? _paths.Peek() + ConfigurationPath.KeyDelimiter + context : context); private void ExitContext() => _paths.Pop(); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/UpdatableDataProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/UpdatableDataProvider.cs index a98b3cc1056..f0b06217e21 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/UpdatableDataProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/UpdatableDataProvider.cs @@ -29,16 +29,13 @@ public UpdatableDataProvider(IEnumerable> initialDa public virtual void Set(string key, string value) => Data[key] = value; - public virtual void Load() - { - } + public virtual void Load() { } public virtual IEnumerable GetChildKeys(IEnumerable earlierKeys, string parentPath) { var prefix = parentPath == null ? string.Empty : parentPath + ConfigurationPath.KeyDelimiter; - return Data - .Where(kv => kv.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + return Data.Where(kv => kv.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) .Select(kv => Segment(kv.Key, prefix.Length)) .Concat(earlierKeys) .OrderBy(k => k, ConfigurationKeyComparer.Instance); diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/ShellConfiguration.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/ShellConfiguration.cs index 1d3767f76be..be26c158fbd 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/ShellConfiguration.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/ShellConfiguration.cs @@ -24,18 +24,13 @@ public class ShellConfiguration : IShellConfiguration private readonly SemaphoreSlim _semaphore = new(1); private bool _released; - public ShellConfiguration() - { - } + public ShellConfiguration() { } public ShellConfiguration(IConfiguration configuration) { _updatableData = new UpdatableDataProvider(); - _configuration = new ConfigurationBuilder() - .AddConfiguration(configuration) - .Add(_updatableData) - .Build(); + _configuration = new ConfigurationBuilder().AddConfiguration(configuration).Add(_updatableData).Build(); } public ShellConfiguration(IConfigurationBuilder builder) @@ -50,9 +45,8 @@ public ShellConfiguration(string name, Func { - public ShellFeature() - { - } + public ShellFeature() { } public ShellFeature(string id, bool alwaysEnabled = false) { diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Distributed/DistributedShellMarkerService.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Distributed/DistributedShellMarkerService.cs index c8ef2a467cb..a3d26e05b0b 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Distributed/DistributedShellMarkerService.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Distributed/DistributedShellMarkerService.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Environment.Shell.Distributed { - public class DistributedShellMarkerService - { - } + public class DistributedShellMarkerService { } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellContextFactoryExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellContextFactoryExtensions.cs index 34d8c40fa3f..87dbe4cd0bc 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellContextFactoryExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellContextFactoryExtensions.cs @@ -11,10 +11,9 @@ public static class ShellContextFactoryExtensions { /// /// Creates a maximum shell context composed of all installed features, and - /// marked by default as using shared settings that should not be disposed. + /// marked by default as using shared settings that should not be disposed. /// - public static async Task CreateMaximumContextAsync( - this IShellContextFactory shellContextFactory, ShellSettings shellSettings, bool sharedSettings = true) + public static async Task CreateMaximumContextAsync(this IShellContextFactory shellContextFactory, ShellSettings shellSettings, bool sharedSettings = true) { var shellDescriptor = await shellContextFactory.GetShellDescriptorAsync(shellSettings); if (shellDescriptor is null) @@ -35,10 +34,9 @@ public static async Task CreateMaximumContextAsync( /// /// Creates a minimum shell context without any feature, and marked - /// by default as using shared settings that should not be disposed. + /// by default as using shared settings that should not be disposed. /// - public static async Task CreateMinimumContextAsync( - this IShellContextFactory shellContextFactory, ShellSettings shellSettings, bool sharedSettings = true) + public static async Task CreateMinimumContextAsync(this IShellContextFactory shellContextFactory, ShellSettings shellSettings, bool sharedSettings = true) { var context = await shellContextFactory.CreateDescribedContextAsync(shellSettings, new ShellDescriptor()); if (sharedSettings) diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellFeaturesManagerExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellFeaturesManagerExtensions.cs index da814b112bd..b010694ed3f 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellFeaturesManagerExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellFeaturesManagerExtensions.cs @@ -6,27 +6,23 @@ namespace OrchardCore.Environment.Shell { public static class ShellFeaturesManagerExtensions { - public static Task> EnableFeaturesAsync(this IShellFeaturesManager shellFeaturesManager, - IEnumerable features) + public static Task> EnableFeaturesAsync(this IShellFeaturesManager shellFeaturesManager, IEnumerable features) { return shellFeaturesManager.EnableFeaturesAsync(features, false); } - public static async Task> EnableFeaturesAsync(this IShellFeaturesManager shellFeaturesManager, - IEnumerable features, bool force) + public static async Task> EnableFeaturesAsync(this IShellFeaturesManager shellFeaturesManager, IEnumerable features, bool force) { var (_, featuresToEnable) = await shellFeaturesManager.UpdateFeaturesAsync([], features, force); return featuresToEnable; } - public static Task> DisableFeaturesAsync(this IShellFeaturesManager shellFeaturesManager, - IEnumerable features) + public static Task> DisableFeaturesAsync(this IShellFeaturesManager shellFeaturesManager, IEnumerable features) { return shellFeaturesManager.DisableFeaturesAsync(features, false); } - public static async Task> DisableFeaturesAsync(this IShellFeaturesManager shellFeaturesManager, - IEnumerable features, bool force) + public static async Task> DisableFeaturesAsync(this IShellFeaturesManager shellFeaturesManager, IEnumerable features, bool force) { var (featuresToDisable, _) = await shellFeaturesManager.UpdateFeaturesAsync(features, [], force); return featuresToDisable; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellHostExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellHostExtensions.cs index 2409ae223c2..8023c657769 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellHostExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellHostExtensions.cs @@ -70,8 +70,6 @@ public static ShellSettings GetSettings(this IShellHost shellHost, string tenant /// Whether or not a given tenant is in use in at least one active scope. /// public static bool IsShellActive(this IShellHost shellHost, ShellSettings settings) => - settings is { Name: not null } && - shellHost.TryGetShellContext(settings.Name, out var context) && - context.IsActive(); + settings is { Name: not null } && shellHost.TryGetShellContext(settings.Name, out var context) && context.IsActive(); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellSettingsExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellSettingsExtensions.cs index cddeca94809..695148fab3c 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellSettingsExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellSettingsExtensions.cs @@ -49,19 +49,13 @@ public static class ShellSettingsExtensions /// Whether or not the tenant has the provided url prefix. /// public static bool HasUrlPrefix(this ShellSettings settings, string urlPrefix) => - settings is not null && - string.Equals( - settings.RequestUrlPrefix ?? string.Empty, - urlPrefix?.Trim(' ', '/') ?? string.Empty, - StringComparison.OrdinalIgnoreCase); + settings is not null && string.Equals(settings.RequestUrlPrefix ?? string.Empty, urlPrefix?.Trim(' ', '/') ?? string.Empty, StringComparison.OrdinalIgnoreCase); /// /// Whether or not the tenant has one of the url host(s) defined by the provided string. /// public static bool HasUrlHost(this ShellSettings settings, string urlHost) => - settings.HasUrlHost(urlHost - ?.Split(ShellSettings.HostSeparators, StringSplitOptions.RemoveEmptyEntries) - ?? []); + settings.HasUrlHost(urlHost?.Split(ShellSettings.HostSeparators, StringSplitOptions.RemoveEmptyEntries) ?? []); /// /// Whether or not the tenant has one of the provided url hosts. diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellStringExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellStringExtensions.cs index 95a2f2d95b5..7fba814da6f 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellStringExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Extensions/ShellStringExtensions.cs @@ -12,8 +12,7 @@ public static class ShellStringExtensions /// /// Whether or not the provided name may be in conflict with the 'Default' tenant name. /// - public static bool IsDefaultShellNameIgnoreCase(this string name) => - name is not null && name.Equals(ShellSettings.DefaultShellName, StringComparison.OrdinalIgnoreCase); + public static bool IsDefaultShellNameIgnoreCase(this string name) => name is not null && name.Equals(ShellSettings.DefaultShellName, StringComparison.OrdinalIgnoreCase); } [Obsolete("This class will be removed in a future release, use 'ShellSettings' instead.", false)] diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/IShellDescriptorFeaturesManager.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/IShellDescriptorFeaturesManager.cs index b898f2e3376..a34d2d72403 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/IShellDescriptorFeaturesManager.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/IShellDescriptorFeaturesManager.cs @@ -9,7 +9,11 @@ namespace OrchardCore.Environment.Shell public interface IShellDescriptorFeaturesManager { - Task<(IEnumerable, IEnumerable)> UpdateFeaturesAsync(ShellDescriptor shellDescriptor, - IEnumerable featuresToDisable, IEnumerable featuresToEnable, bool force); + Task<(IEnumerable, IEnumerable)> UpdateFeaturesAsync( + ShellDescriptor shellDescriptor, + IEnumerable featuresToDisable, + IEnumerable featuresToEnable, + bool force + ); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/IShellFeaturesManager.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/IShellFeaturesManager.cs index 9ff6e9a52a9..cc28ef9c555 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/IShellFeaturesManager.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/IShellFeaturesManager.cs @@ -12,7 +12,10 @@ public interface IShellFeaturesManager Task> GetAlwaysEnabledFeaturesAsync(); Task> GetDisabledFeaturesAsync(); Task<(IEnumerable, IEnumerable)> UpdateFeaturesAsync( - IEnumerable featuresToDisable, IEnumerable featuresToEnable, bool force); + IEnumerable featuresToDisable, + IEnumerable featuresToEnable, + bool force + ); Task> GetEnabledExtensionsAsync(); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Removing/ShellRemovingContext.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Removing/ShellRemovingContext.cs index 4f82ee1482b..4072f550b7a 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Removing/ShellRemovingContext.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Removing/ShellRemovingContext.cs @@ -14,7 +14,6 @@ public class ShellRemovingContext public string ErrorMessage { get => Error != null ? $"{_errorMessage} {Error.GetType().FullName}: {Error.Message}" : _errorMessage; - set => _errorMessage = value; } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScope.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScope.cs index a838e28f958..ce256b55ff4 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScope.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScope.cs @@ -46,8 +46,7 @@ public ShellScope(ShellContext shellContext) // Keep the counter clean before failing. Interlocked.Decrement(ref shellContext._refCount); - throw new InvalidOperationException( - $"Can't resolve a scope on tenant '{shellContext.Settings.Name}' as it is disabled or disposed"); + throw new InvalidOperationException($"Can't resolve a scope on tenant '{shellContext.Settings.Name}' as it is disabled or disposed"); } _serviceScope = shellContext.ServiceProvider.CreateAsyncScope(); @@ -93,12 +92,24 @@ public static void Set(object key, object value) /// /// Gets a shared item from the current shell scope. /// - public static object Get(object key) => Current is null ? null : Current._items.TryGetValue(key, out var value) ? value : null; + public static object Get(object key) => + Current is null + ? null + : Current._items.TryGetValue(key, out var value) + ? value + : null; /// /// Gets a shared item of a given type from the current shell scope. /// - public static T Get(object key) => Current is null ? default : Current._items.TryGetValue(key, out var value) ? value is T item ? item : default : default; + public static T Get(object key) => + Current is null + ? default + : Current._items.TryGetValue(key, out var value) + ? value is T item + ? item + : default + : default; /// /// Gets (or creates) a shared item of a given type from the current shell scope. @@ -121,7 +132,8 @@ public static T GetOrCreate(object key, Func factory) /// /// Gets (or creates) a shared item of a given type from the current shell scope. /// - public static T GetOrCreate(object key) where T : class, new() + public static T GetOrCreate(object key) + where T : class, new() { if (Current is null) { @@ -154,7 +166,8 @@ public static T GetOrCreate(object key, Func factory) /// /// Gets (or creates) a shared feature from the current shell scope. /// - public static T GetOrCreateFeature() where T : class, new() => GetOrCreate(typeof(T)); + public static T GetOrCreateFeature() + where T : class, new() => GetOrCreate(typeof(T)); /// /// Creates a child scope from the current one. @@ -211,9 +224,10 @@ public static async Task UsingChildScopeAsync(string tenant, Func public void StartAsyncFlow() - // Use an object indirection to hold the current scope in the 'AsyncLocal', - // so that it can be cleared in all execution contexts when it is cleared. - => _current.Value = new ShellScopeHolder { Scope = this }; + // Use an object indirection to hold the current scope in the 'AsyncLocal', + // so that it can be cleared in all execution contexts when it is cleared. + => + _current.Value = new ShellScopeHolder { Scope = this }; /// /// Executes a delegate using this shell scope in an isolated async flow, @@ -317,19 +331,22 @@ internal async Task ActivateShellInternalAsync() // The tenant gets activated here. if (!ShellContext.IsActivated) { - await new ShellScope(ShellContext).UsingAsync(async scope => - { - var tenantEvents = scope.ServiceProvider.GetServices(); - foreach (var tenantEvent in tenantEvents) + await new ShellScope(ShellContext).UsingAsync( + async scope => { - await tenantEvent.ActivatingAsync(); - } + var tenantEvents = scope.ServiceProvider.GetServices(); + foreach (var tenantEvent in tenantEvents) + { + await tenantEvent.ActivatingAsync(); + } - foreach (var tenantEvent in tenantEvents.Reverse()) - { - await tenantEvent.ActivatedAsync(); - } - }, activateShell: false); + foreach (var tenantEvent in tenantEvents.Reverse()) + { + await tenantEvent.ActivatedAsync(); + } + }, + activateShell: false + ); ShellContext.IsActivated = true; } @@ -432,24 +449,29 @@ internal async Task BeforeDisposeAsync() // Use 'UsingAsync' in place of 'UsingServiceScopeAsync()' to allow a deferred task to // trigger another one, but still prevent the shell to be activated in a deferred task. - await scope.UsingAsync(async scope => - { - var logger = scope.ServiceProvider.GetService>(); - - try - { - await task(scope); - } - catch (Exception e) + await scope.UsingAsync( + async scope => { - logger?.LogError(e, - "Error while processing deferred task '{TaskName}' on tenant '{TenantName}'.", - task.GetType().FullName, ShellContext.Settings.Name); - - await scope.HandleExceptionAsync(e); - } - }, - activateShell: false); + var logger = scope.ServiceProvider.GetService>(); + + try + { + await task(scope); + } + catch (Exception e) + { + logger?.LogError( + e, + "Error while processing deferred task '{TaskName}' on tenant '{TenantName}'.", + task.GetType().FullName, + ShellContext.Settings.Name + ); + + await scope.HandleExceptionAsync(e); + } + }, + activateShell: false + ); } } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScopeExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScopeExtensions.cs index 4c91df15f42..bfa3f856dbd 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScopeExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScopeExtensions.cs @@ -74,11 +74,13 @@ public static ShellScope AddExceptionHandler(this ShellScope scope, Func public static ShellScope AddExceptionHandler(this ShellScope scope, Action handler) { - scope?.ExceptionHandler((scope, e) => - { - handler(scope, e); - return Task.CompletedTask; - }); + scope?.ExceptionHandler( + (scope, e) => + { + handler(scope, e); + return Task.CompletedTask; + } + ); return scope; } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScopeServices.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScopeServices.cs index be1fbec6279..ac392ade611 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScopeServices.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScopeServices.cs @@ -11,15 +11,11 @@ public class ShellScopeServices(IServiceProvider services) : IKeyedServiceProvid { private readonly IServiceProvider _services = services; - private IServiceProvider Services - => ShellScope.Services ?? _services; + private IServiceProvider Services => ShellScope.Services ?? _services; - public object GetKeyedService(Type serviceType, object serviceKey) - => Services.GetKeyedService(serviceType, serviceKey); + public object GetKeyedService(Type serviceType, object serviceKey) => Services.GetKeyedService(serviceType, serviceKey); - public object GetRequiredKeyedService(Type serviceType, object serviceKey) - => Services.GetRequiredKeyedService(serviceType, serviceKey); + public object GetRequiredKeyedService(Type serviceType, object serviceKey) => Services.GetRequiredKeyedService(serviceType, serviceKey); - public object GetService(Type serviceType) - => Services?.GetService(serviceType); + public object GetService(Type serviceType) => Services?.GetService(serviceType); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/ShellHostReloadException.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/ShellHostReloadException.cs index 1fc807594a9..a3241cf8c44 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/ShellHostReloadException.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/ShellHostReloadException.cs @@ -12,8 +12,7 @@ public class ShellHostReloadException : Exception /// exception message. /// /// The message that describes the error. - public ShellHostReloadException(string message) : base(message) - { - } + public ShellHostReloadException(string message) + : base(message) { } } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/ShellSettings.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/ShellSettings.cs index c1e90df6218..4a4a7e8608f 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/ShellSettings.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/ShellSettings.cs @@ -106,9 +106,7 @@ public string RequestUrlHost /// The tenant request url host(s). /// [JsonIgnore] - public string[] RequestUrlHosts => _settings["RequestUrlHost"] - ?.Split(HostSeparators, StringSplitOptions.RemoveEmptyEntries) - ?? []; + public string[] RequestUrlHosts => _settings["RequestUrlHost"]?.Split(HostSeparators, StringSplitOptions.RemoveEmptyEntries) ?? []; /// /// The tenant request url prefix. diff --git a/src/OrchardCore/OrchardCore.Admin.Abstractions/Constants.cs b/src/OrchardCore/OrchardCore.Admin.Abstractions/Constants.cs index c1a1383a2f7..a1a08f8cd9b 100644 --- a/src/OrchardCore/OrchardCore.Admin.Abstractions/Constants.cs +++ b/src/OrchardCore/OrchardCore.Admin.Abstractions/Constants.cs @@ -1,4 +1,3 @@ - namespace OrchardCore.Admin { public static class Constants diff --git a/src/OrchardCore/OrchardCore.Admin.Abstractions/Models/Navbar.cs b/src/OrchardCore/OrchardCore.Admin.Abstractions/Models/Navbar.cs index 130614a7411..eedafca2238 100644 --- a/src/OrchardCore/OrchardCore.Admin.Abstractions/Models/Navbar.cs +++ b/src/OrchardCore/OrchardCore.Admin.Abstractions/Models/Navbar.cs @@ -2,6 +2,4 @@ namespace OrchardCore.Admin.Models; -public class Navbar : Entity -{ -} +public class Navbar : Entity { } diff --git a/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/AdminMenuExtensions.cs b/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/AdminMenuExtensions.cs index 8fe4a20fb21..8e28f5abd97 100644 --- a/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/AdminMenuExtensions.cs +++ b/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/AdminMenuExtensions.cs @@ -6,6 +6,7 @@ using OrchardCore.Navigation; namespace OrchardCore.AdminMenu; + public static class AdminMenuExtensions { public static IServiceCollection AddAdminNode(this IServiceCollection services) @@ -37,7 +38,8 @@ public static IServiceCollection AddAdminNode(this IService /// /// The type to register. /// The service collection. - public static IServiceCollection AddAdminNodeDerivedType(this IServiceCollection services) where T : AdminNode + public static IServiceCollection AddAdminNodeDerivedType(this IServiceCollection services) + where T : AdminNode { services.AddJsonDerivedTypeInfo(); services.AddJsonDerivedTypeInfo(); diff --git a/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Services/IAdminNodeProviderFactory.cs b/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Services/IAdminNodeProviderFactory.cs index 720c3936d43..ad473a4140a 100644 --- a/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Services/IAdminNodeProviderFactory.cs +++ b/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Services/IAdminNodeProviderFactory.cs @@ -8,7 +8,8 @@ public interface IAdminNodeProviderFactory AdminNode Create(); } - public class AdminNodeProviderFactory : IAdminNodeProviderFactory where TAdminNode : AdminNode, new() + public class AdminNodeProviderFactory : IAdminNodeProviderFactory + where TAdminNode : AdminNode, new() { private static readonly string _typeName = typeof(TAdminNode).Name; diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/FieldBuilderResolverExtensions.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/FieldBuilderResolverExtensions.cs index d3c507b26da..1fcab91b180 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/FieldBuilderResolverExtensions.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/FieldBuilderResolverExtensions.cs @@ -8,7 +8,10 @@ namespace OrchardCore.Apis.GraphQL { public static class FieldBuilderResolverExtensions { - public static FieldBuilder ResolveLockedAsync(this FieldBuilder builder, Func, ValueTask> resolve) + public static FieldBuilder ResolveLockedAsync( + this FieldBuilder builder, + Func, ValueTask> resolve + ) { return builder.Resolve(new LockedAsyncFieldResolver(resolve)); } diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/PermissionsExtensions.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/PermissionsExtensions.cs index b8d169a6a9d..d92487087ac 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/PermissionsExtensions.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/PermissionsExtensions.cs @@ -24,7 +24,11 @@ public static void RequirePermission(this IProvideMetadata type, Permission perm } } - public static FieldBuilder RequirePermission(this FieldBuilder builder, Permission permission, object resource = null) + public static FieldBuilder RequirePermission( + this FieldBuilder builder, + Permission permission, + object resource = null + ) { builder.FieldType.RequirePermission(permission, resource); return builder; diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/ResolveFieldContextExtensions.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/ResolveFieldContextExtensions.cs index fe9d1645590..2249b64acee 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/ResolveFieldContextExtensions.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/ResolveFieldContextExtensions.cs @@ -16,7 +16,8 @@ public static bool HasPopulatedArgument(this IResolveFieldContext source, string if (source.Arguments?.ContainsKey(argumentName) ?? false) { return !string.IsNullOrEmpty(source.Arguments[argumentName].Value?.ToString()); - }; + } + ; return false; } @@ -26,7 +27,8 @@ public static bool HasPopulatedArgument(this IResolveFieldContext - { - } + public class WhereInputObjectGraphType : WhereInputObjectGraphType { } public class WhereInputObjectGraphType : InputObjectGraphType { @@ -18,38 +16,32 @@ public override object ParseDictionary(IDictionary value) } // Applies to all types. - public static readonly Dictionary EqualityOperators = new() - { - { "", "is equal to" }, - { "_not", "is not equal to" }, - }; + public static readonly Dictionary EqualityOperators = new() { { "", "is equal to" }, { "_not", "is not equal to" }, }; // Applies to all types. - public static readonly Dictionary MultiValueComparisonOperators = new() - { - { "_in", "is in collection" }, - { "_not_in", "is not in collection" }, - }; + public static readonly Dictionary MultiValueComparisonOperators = new() { { "_in", "is in collection" }, { "_not_in", "is not in collection" }, }; // Applies to non strings. - public static readonly Dictionary NonStringValueComparisonOperators = new() - { - { "_gt", "is greater than" }, - { "_gte", "is greater than or equal" }, - { "_lt", "is less than" }, - { "_lte", "is less than or equal" }, - }; + public static readonly Dictionary NonStringValueComparisonOperators = + new() + { + { "_gt", "is greater than" }, + { "_gte", "is greater than or equal" }, + { "_lt", "is less than" }, + { "_lte", "is less than or equal" }, + }; // Applies to strings. - public static readonly Dictionary StringComparisonOperators = new() - { - {"_contains", "contains the string"}, - {"_not_contains", "does not contain the string"}, - {"_starts_with", "starts with the string"}, - {"_not_starts_with", "does not start with the string"}, - {"_ends_with", "ends with the string"}, - {"_not_ends_with", "does not end with the string"}, - }; + public static readonly Dictionary StringComparisonOperators = + new() + { + { "_contains", "contains the string" }, + { "_not_contains", "does not contain the string" }, + { "_starts_with", "starts with the string" }, + { "_not_starts_with", "does not start with the string" }, + { "_ends_with", "ends with the string" }, + { "_not_ends_with", "does not end with the string" }, + }; public void AddScalarFilterFields(string fieldName, string description) { @@ -96,12 +88,14 @@ private void AddFilterFields(Type graphType, IDictionary filters { foreach (var filter in filters) { - AddField(new FieldType - { - Name = fieldName + filter.Key, - Description = $"{description} {filter.Value}", - Type = graphType - }); + AddField( + new FieldType + { + Name = fieldName + filter.Key, + Description = $"{description} {filter.Value}", + Type = graphType + } + ); } } } diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Resolvers/LockedAsyncFieldResolver.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Resolvers/LockedAsyncFieldResolver.cs index 69ad5cbc625..46627413873 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Resolvers/LockedAsyncFieldResolver.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Resolvers/LockedAsyncFieldResolver.cs @@ -7,10 +7,8 @@ namespace OrchardCore.Apis.GraphQL.Resolvers { public class LockedAsyncFieldResolver : FuncFieldResolver { - public LockedAsyncFieldResolver(Func> resolver) : base(resolver) - { - - } + public LockedAsyncFieldResolver(Func> resolver) + : base(resolver) { } public new async ValueTask ResolveAsync(IResolveFieldContext context) { @@ -30,9 +28,8 @@ public LockedAsyncFieldResolver(Func : FuncFieldResolver { - public LockedAsyncFieldResolver(Func, ValueTask> resolver) : base(resolver) - { - } + public LockedAsyncFieldResolver(Func, ValueTask> resolver) + : base(resolver) { } public new async Task ResolveAsync(IResolveFieldContext context) { diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentResource.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentResource.cs index c9da9fbd99d..32e78160714 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentResource.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentResource.cs @@ -20,13 +20,9 @@ public async Task Query(string contentType, Action Query(string contentType, Action Query(string body) { - var requestJson = new JsonObject - { - ["query"] = @"query { " + body + " }", - }; + var requestJson = new JsonObject { ["query"] = @"query { " + body + " }", }; var response = await _client.PostJsonAsync("api/graphql", requestJson.ToJsonString(JOptions.Default)); @@ -55,10 +48,7 @@ public async Task Query(string body) public async Task NamedQueryExecute(string name) { - var requestJson = new JsonObject - { - ["namedquery"] = name, - }; + var requestJson = new JsonObject { ["namedquery"] = name, }; var response = await _client.PostJsonAsync("api/graphql", requestJson.ToJsonString(JOptions.Default)); diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeQueryResourceBuilder.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeQueryResourceBuilder.cs index f289a172d6d..00b11d8ee96 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeQueryResourceBuilder.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeQueryResourceBuilder.cs @@ -60,15 +60,11 @@ public ContentTypeQueryResourceBuilder WithQueryArgument(string argument, string // Field-level argument exists else if (queryValues is IDictionary) { - ((IDictionary)queryValues) - .Add(fieldName.ToGraphQLStringFormat(), fieldValue); + ((IDictionary)queryValues).Add(fieldName.ToGraphQLStringFormat(), fieldValue); } else { - _queries.Add(argument, new Dictionary() - { - { fieldName.ToGraphQLStringFormat(), fieldValue } - }); + _queries.Add(argument, new Dictionary() { { fieldName.ToGraphQLStringFormat(), fieldValue } }); } return this; @@ -89,15 +85,11 @@ public ContentTypeQueryResourceBuilder WithNestedQueryArgument(string argument, // Field-level argument exists else if (queryValues is IDictionary) { - ((IDictionary)queryValues) - .Add(fieldName.ToGraphQLStringFormat(), $"{{ {fieldValue} }}"); + ((IDictionary)queryValues).Add(fieldName.ToGraphQLStringFormat(), $"{{ {fieldValue} }}"); } else { - _queries.Add(argument, new Dictionary() - { - { fieldName.ToGraphQLStringFormat(), $"{{ {fieldValue} }}" } - }); + _queries.Add(argument, new Dictionary() { { fieldName.ToGraphQLStringFormat(), $"{{ {fieldValue} }}" } }); } return this; diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpContentExtensions.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpContentExtensions.cs index 8ca74596593..6460f3824aa 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpContentExtensions.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpContentExtensions.cs @@ -13,7 +13,6 @@ public static async Task ReadAsAsync(this HttpContent content) return await data.ReadAsAsync(); } - public static ValueTask ReadAsAsync(this Stream stream) => - JsonSerializer.DeserializeAsync(stream, JOptions.Default); + public static ValueTask ReadAsAsync(this Stream stream) => JsonSerializer.DeserializeAsync(stream, JOptions.Default); } } diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpRequestExtensions.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpRequestExtensions.cs index 91edc714e58..a6d6041a962 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpRequestExtensions.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpRequestExtensions.cs @@ -32,16 +32,9 @@ internal static class HttpRequestExtensions /// /// The . /// - public static Task PatchAsJsonAsync( - this HttpClient client, - string requestUri, - T value, - JsonSerializerOptions options = null) + public static Task PatchAsJsonAsync(this HttpClient client, string requestUri, T value, JsonSerializerOptions options = null) { - var content = new StringContent( - JConvert.SerializeObject(value, options), - Encoding.UTF8, - "application/json"); + var content = new StringContent(JConvert.SerializeObject(value, options), Encoding.UTF8, "application/json"); return PatchAsync(client, requestUri, content); } @@ -61,10 +54,7 @@ public static Task PatchAsJsonAsync( /// /// The . /// - public static Task PatchAsync( - this HttpClient client, - string requestUri, - HttpContent content) + public static Task PatchAsync(this HttpClient client, string requestUri, HttpContent content) { var request = new HttpRequestMessage { @@ -97,16 +87,9 @@ public static Task PatchAsync( /// /// The . /// - public static Task PutAsJsonAsync( - this HttpClient client, - string requestUri, - T value, - JsonSerializerOptions options = null) + public static Task PutAsJsonAsync(this HttpClient client, string requestUri, T value, JsonSerializerOptions options = null) { - var content = new StringContent( - JConvert.SerializeObject(value, options), - Encoding.UTF8, - "application/json"); + var content = new StringContent(JConvert.SerializeObject(value, options), Encoding.UTF8, "application/json"); return client.PutAsync(requestUri, content); } @@ -131,69 +114,35 @@ public static Task PutAsJsonAsync( /// /// The . /// - public static Task PostAsJsonAsync( - this HttpClient client, - string requestUri, - T value, - JsonSerializerOptions options = null) + public static Task PostAsJsonAsync(this HttpClient client, string requestUri, T value, JsonSerializerOptions options = null) { - var content = new StringContent( - JConvert.SerializeObject(value, options), - Encoding.UTF8, - "application/json"); + var content = new StringContent(JConvert.SerializeObject(value, options), Encoding.UTF8, "application/json"); - var request = new HttpRequestMessage(HttpMethod.Post, requestUri) - { - Content = content, - }; + var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content, }; - request.Headers - .Accept - .Add(new MediaTypeWithQualityHeaderValue("application/json")); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client.SendAsync(request); } - public static Task PostJsonAsync( - this HttpClient client, - string requestUri, - string json) + public static Task PostJsonAsync(this HttpClient client, string requestUri, string json) { - var content = new StringContent( - json, - Encoding.UTF8, - "application/json"); + var content = new StringContent(json, Encoding.UTF8, "application/json"); - var request = new HttpRequestMessage(HttpMethod.Post, requestUri) - { - Content = content, - }; + var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content, }; - request.Headers - .Accept - .Add(new MediaTypeWithQualityHeaderValue("application/json")); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client.SendAsync(request); } - public static Task PostJsonApiAsync( - this HttpClient client, - string requestUri, - string json) + public static Task PostJsonApiAsync(this HttpClient client, string requestUri, string json) { - var content = new StringContent( - json, - Encoding.UTF8, - "application/vnd.api+json"); + var content = new StringContent(json, Encoding.UTF8, "application/vnd.api+json"); - var request = new HttpRequestMessage(HttpMethod.Post, requestUri) - { - Content = content, - }; + var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content, }; - request.Headers - .Accept - .Add(new MediaTypeWithQualityHeaderValue("application/vnd.api+json")); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.api+json")); return client.SendAsync(request); } diff --git a/src/OrchardCore/OrchardCore.Application.Cms.Core.Targets/ServiceExtensions.cs b/src/OrchardCore/OrchardCore.Application.Cms.Core.Targets/ServiceExtensions.cs index 3d570d6d85f..b27502442a3 100644 --- a/src/OrchardCore/OrchardCore.Application.Cms.Core.Targets/ServiceExtensions.cs +++ b/src/OrchardCore/OrchardCore.Application.Cms.Core.Targets/ServiceExtensions.cs @@ -12,22 +12,19 @@ public static OrchardCoreBuilder AddOrchardCms(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); - var builder = services.AddOrchardCore() - + var builder = services + .AddOrchardCore() .AddCommands() - .AddSecurity() .AddMvc() .AddIdGeneration() .AddEmailAddressValidator() .AddHtmlSanitizer() .AddSetupFeatures("OrchardCore.Setup") - .AddDataAccess() .AddDataStorage() .AddBackgroundService() .AddScripting() - .AddTheming() .AddLiquidViews() .AddCaching(); diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Drivers/AuditTrailEventSectionDisplayDriver.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Drivers/AuditTrailEventSectionDisplayDriver.cs index 78d67b58b78..412f6b97b86 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Drivers/AuditTrailEventSectionDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Drivers/AuditTrailEventSectionDisplayDriver.cs @@ -12,7 +12,6 @@ namespace OrchardCore.AuditTrail.Drivers public abstract class AuditTrailEventSectionDisplayDriver : SectionDisplayDriver where TSection : new() { - public override bool CanHandleModel(AuditTrailEvent auditTrailEvent) - => auditTrailEvent.Properties.ContainsKey(PropertyName); + public override bool CanHandleModel(AuditTrailEvent auditTrailEvent) => auditTrailEvent.Properties.ContainsKey(PropertyName); } } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/AuditTrailEventHandlerBase.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/AuditTrailEventHandlerBase.cs index 0be2a11df6b..572ed437c6d 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/AuditTrailEventHandlerBase.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/AuditTrailEventHandlerBase.cs @@ -7,6 +7,7 @@ namespace OrchardCore.AuditTrail.Services public class AuditTrailEventHandlerBase : IAuditTrailEventHandler { public virtual Task CreateAsync(AuditTrailCreateContext context) => Task.CompletedTask; + public virtual Task AlterAsync(AuditTrailCreateContext context, AuditTrailEvent auditTrailEvent) => Task.CompletedTask; } } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/AuditTrailQueryContext.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/AuditTrailQueryContext.cs index a0e8390c7c8..16a2a9a773c 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/AuditTrailQueryContext.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/AuditTrailQueryContext.cs @@ -7,7 +7,8 @@ namespace OrchardCore.AuditTrail.Services { public class AuditTrailQueryContext : QueryExecutionContext { - public AuditTrailQueryContext(IServiceProvider serviceProvider, IQuery query) : base(query) + public AuditTrailQueryContext(IServiceProvider serviceProvider, IQuery query) + : base(query) { ServiceProvider = serviceProvider; } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/IAuditTrailAdminListFilterParser.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/IAuditTrailAdminListFilterParser.cs index dafc708dd09..112045175b9 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/IAuditTrailAdminListFilterParser.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/IAuditTrailAdminListFilterParser.cs @@ -3,7 +3,5 @@ namespace OrchardCore.AuditTrail.Services { - public interface IAuditTrailAdminListFilterParser : IQueryParser - { - } + public interface IAuditTrailAdminListFilterParser : IQueryParser { } } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/IAuditTrailManager.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/IAuditTrailManager.cs index ed7f5e8d03c..c8d25ae2d4f 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/IAuditTrailManager.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/IAuditTrailManager.cs @@ -15,7 +15,8 @@ public interface IAuditTrailManager /// Records an audit trail event. /// /// The used to create a new event. - Task RecordEventAsync(AuditTrailContext context) where TEvent : class, new(); + Task RecordEventAsync(AuditTrailContext context) + where TEvent : class, new(); /// /// Gets a single audit trail event by ID. diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOption.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOption.cs index 2f63e6bf8ad..4c7eb1cecde 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOption.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOption.cs @@ -14,7 +14,8 @@ public AuditTrailAdminListOption( string value, Func, QueryExecutionContext, ValueTask>> query, Func selectListItem, - bool isDefault) + bool isDefault + ) { ArgumentNullException.ThrowIfNull(value); ArgumentNullException.ThrowIfNull(query); diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOptionBuilder.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOptionBuilder.cs index 5a1b50fe6ef..5a6e13ec77c 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOptionBuilder.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOptionBuilder.cs @@ -45,7 +45,10 @@ public AuditTrailAdminListOptionBuilder WithQuery(Func /// Optionally adds a select list item to the option. /// - public AuditTrailAdminListOptionBuilder WithSelectListItem(Func selectListItem) where TLocalizer : class + public AuditTrailAdminListOptionBuilder WithSelectListItem( + Func selectListItem + ) + where TLocalizer : class { _selectListItem = (sp, opt, model) => { diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOptions.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOptions.cs index f51497c78b4..de31bf44902 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOptions.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOptions.cs @@ -11,12 +11,10 @@ public class AuditTrailAdminListOptions private FrozenDictionary _sortOptions; - public IReadOnlyDictionary SortOptions - => _sortOptions ??= BuildSortOptions(); + public IReadOnlyDictionary SortOptions => _sortOptions ??= BuildSortOptions(); private AuditTrailAdminListOption _defaultSortOption; - public AuditTrailAdminListOption DefaultSortOption - => _defaultSortOption ??= SortOptions.Values.FirstOrDefault(x => x.IsDefault); + public AuditTrailAdminListOption DefaultSortOption => _defaultSortOption ??= SortOptions.Values.FirstOrDefault(x => x.IsDefault); private FrozenDictionary BuildSortOptions() { @@ -42,7 +40,6 @@ public static AuditTrailAdminListOptions ForSort(this AuditTrailAdminListOptions return options; } - public static bool RemoveSort(this AuditTrailAdminListOptions options, string value) - => options.SortOptionBuilders.Remove(value); + public static bool RemoveSort(this AuditTrailAdminListOptions options, string value) => options.SortOptionBuilders.Remove(value); } } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptor.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptor.cs index ca2dced161e..a1562c2873e 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptor.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptor.cs @@ -6,10 +6,7 @@ namespace OrchardCore.AuditTrail.Services.Models { public class AuditTrailCategoryDescriptor { - public AuditTrailCategoryDescriptor( - string name, - Func localizedName, - IReadOnlyDictionary events) + public AuditTrailCategoryDescriptor(string name, Func localizedName, IReadOnlyDictionary events) { Name = name; LocalizedName = localizedName; @@ -20,14 +17,8 @@ public AuditTrailCategoryDescriptor( public Func LocalizedName { get; } public IReadOnlyDictionary Events { get; } - private static readonly IReadOnlyDictionary _empty = - new Dictionary(); + private static readonly IReadOnlyDictionary _empty = new Dictionary(); - public static AuditTrailCategoryDescriptor Default(string name) => - new( - name, - (sp) => new LocalizedString(name, name), - _empty - ); + public static AuditTrailCategoryDescriptor Default(string name) => new(name, (sp) => new LocalizedString(name, name), _empty); } } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptorBuilder.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptorBuilder.cs index ee9dc4b6918..b757967494d 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptorBuilder.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptorBuilder.cs @@ -4,14 +4,11 @@ namespace OrchardCore.AuditTrail.Services.Models { - public class AuditTrailCategoryDescriptorBuilder : AuditTrailCategoryDescriptorBuilder where TLocalizer : class + public class AuditTrailCategoryDescriptorBuilder : AuditTrailCategoryDescriptorBuilder + where TLocalizer : class { - public AuditTrailCategoryDescriptorBuilder( - string categoryName, - Func localizedName - ) : base(categoryName, typeof(IStringLocalizer<>).MakeGenericType(typeof(TLocalizer)), localizedName) - { - } + public AuditTrailCategoryDescriptorBuilder(string categoryName, Func localizedName) + : base(categoryName, typeof(IStringLocalizer<>).MakeGenericType(typeof(TLocalizer)), localizedName) { } } public class AuditTrailCategoryDescriptorBuilder @@ -34,7 +31,8 @@ public AuditTrailCategoryDescriptorBuilder WithEvent( Func localizedName, Func description, bool enableByDefault = false, - bool isMandatory = false) + bool isMandatory = false + ) { _events[name] = new AuditTrailEventDescriptor( name, diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailContext.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailContext.cs index 1e66152ad75..79cb6dc97ad 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailContext.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailContext.cs @@ -2,12 +2,7 @@ namespace OrchardCore.AuditTrail.Services.Models { public abstract class AuditTrailContext { - public AuditTrailContext( - string name, - string category, - string correlationId, - string userId, - string userName) + public AuditTrailContext(string name, string category, string correlationId, string userId, string userName) { Name = name; Category = category; @@ -23,15 +18,10 @@ public AuditTrailContext( public string UserName { get; set; } } - public class AuditTrailContext : AuditTrailContext where TEvent : class, new() + public class AuditTrailContext : AuditTrailContext + where TEvent : class, new() { - public AuditTrailContext( - string name, - string category, - string correlationId, - string userId, - string userName, - TEvent auditTrailEventItem) + public AuditTrailContext(string name, string category, string correlationId, string userId, string userName, TEvent auditTrailEventItem) : base(name, category, correlationId, userId, userName) { AuditTrailEventItem = auditTrailEventItem; diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCreateContext.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCreateContext.cs index 791a2e233d6..d0eb1db6782 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCreateContext.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCreateContext.cs @@ -4,28 +4,18 @@ namespace OrchardCore.AuditTrail.Services.Models { public abstract class AuditTrailCreateContext : AuditTrailContext { - public AuditTrailCreateContext( - string name, - string category, - string correlationId, - string userId, - string userName) + public AuditTrailCreateContext(string name, string category, string correlationId, string userId, string userName) : base(name, category, correlationId, userId, userName) { } public string ClientIpAddress { get; set; } public DateTime? CreatedUtc { get; set; } } - public class AuditTrailCreateContext : AuditTrailCreateContext where TEvent : class, new() + public class AuditTrailCreateContext : AuditTrailCreateContext + where TEvent : class, new() { - public AuditTrailCreateContext( - string name, - string category, - string correlationId, - string userId, - string userName, - TEvent auditTrailEventItem) - : base(name, category, correlationId, userId, userName) + public AuditTrailCreateContext(string name, string category, string correlationId, string userId, string userName, TEvent auditTrailEventItem) + : base(name, category, correlationId, userId, userName) { AuditTrailEventItem = auditTrailEventItem; } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailEventDescriptor.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailEventDescriptor.cs index 06620fdc319..286dc73a22f 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailEventDescriptor.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailEventDescriptor.cs @@ -6,7 +6,15 @@ namespace OrchardCore.AuditTrail.Services.Models { public class AuditTrailEventDescriptor { - public AuditTrailEventDescriptor(string name, string category, Func localizedName, Func localizedCategory, Func description, bool isEnabledByDefault = false, bool isMandatory = false) + public AuditTrailEventDescriptor( + string name, + string category, + Func localizedName, + Func localizedCategory, + Func description, + bool isEnabledByDefault = false, + bool isMandatory = false + ) { Name = name; Category = category; diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailOptions.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailOptions.cs index a33b9f83735..744dd32c9e8 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailOptions.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailOptions.cs @@ -10,8 +10,7 @@ public class AuditTrailOptions internal Dictionary CategoryDescriptorBuilders { get; set; } = []; private FrozenDictionary _categoryDescriptors; - public IReadOnlyDictionary CategoryDescriptors - => _categoryDescriptors ??= BuildCategoryDescriptors(); + public IReadOnlyDictionary CategoryDescriptors => _categoryDescriptors ??= BuildCategoryDescriptors(); private FrozenDictionary BuildCategoryDescriptors() { @@ -24,7 +23,12 @@ private FrozenDictionary BuildCategoryDesc public static class AuditTrailOptionsExtensions { - public static AuditTrailCategoryDescriptorBuilder For(this AuditTrailOptions options, string categoryName, Func localizedName) where TLocalizer : class + public static AuditTrailCategoryDescriptorBuilder For( + this AuditTrailOptions options, + string categoryName, + Func localizedName + ) + where TLocalizer : class { if (!options.CategoryDescriptorBuilders.TryGetValue(categoryName, out var auditTrailCategoryDescriptorBuilder)) { @@ -35,7 +39,6 @@ public static AuditTrailCategoryDescriptorBuilder For(this AuditTrai return auditTrailCategoryDescriptorBuilder; } - public static bool Remove(this AuditTrailOptions options, string categoryName) - => options.CategoryDescriptorBuilders.Remove(categoryName); + public static bool Remove(this AuditTrailOptions options, string categoryName) => options.CategoryDescriptorBuilders.Remove(categoryName); } } diff --git a/src/OrchardCore/OrchardCore.Autoroute.Core/Indexes/AutoroutePartIndex.cs b/src/OrchardCore/OrchardCore.Autoroute.Core/Indexes/AutoroutePartIndex.cs index 312777fc509..af98b5fd0f4 100644 --- a/src/OrchardCore/OrchardCore.Autoroute.Core/Indexes/AutoroutePartIndex.cs +++ b/src/OrchardCore/OrchardCore.Autoroute.Core/Indexes/AutoroutePartIndex.cs @@ -85,7 +85,7 @@ public override async Task PublishedAsync(PublishContentContext context) var part = context.ContentItem.As(); // Validate that the content definition contains this part, this prevents indexing parts - // that have been removed from the type definition, but are still present in the elements. + // that have been removed from the type definition, but are still present in the elements. if (part != null) { // Lazy initialization because of ISession cyclic dependency. @@ -106,12 +106,15 @@ public override async Task PublishedAsync(PublishContentContext context) } public string CollectionName { get; set; } + public Type ForType() => typeof(ContentItem); + public void Describe(IDescriptor context) => Describe((DescribeContext)context); public void Describe(DescribeContext context) { - context.For() + context + .For() .When(contentItem => contentItem.Has() || _partRemoved.Contains(contentItem.ContentItemId)) .Map(async contentItem => { @@ -134,7 +137,8 @@ public void Describe(DescribeContext context) var results = new List { // If the part is disabled or was removed, a record is still added but with a null path. - new() { + new() + { ContentItemId = contentItem.ContentItemId, Path = !partRemoved && !part.Disabled ? part.Path : null, Published = contentItem.Published, @@ -157,7 +161,13 @@ public void Describe(DescribeContext context) }); } - private async Task PopulateContainedContentItemIndexesAsync(List results, ContentItem containerContentItem, ContainedContentItemsAspect containedContentItemsAspect, JsonObject content, string basePath) + private async Task PopulateContainedContentItemIndexesAsync( + List results, + ContentItem containerContentItem, + ContainedContentItemsAspect containedContentItemsAspect, + JsonObject content, + string basePath + ) { foreach (var accessor in containedContentItemsAspect.Accessors) { @@ -176,15 +186,17 @@ private async Task PopulateContainedContentItemIndexesAsync(List entries) ILookup entriesByContainer = null; foreach (var entry in entries.Where(x => string.IsNullOrEmpty(x.ContainedContentItemId))) { - entriesByContainer ??= _paths.Values - .Where(x => !string.IsNullOrEmpty(x.ContainedContentItemId)) - .ToLookup(x => x.ContentItemId); + entriesByContainer ??= _paths.Values.Where(x => !string.IsNullOrEmpty(x.ContainedContentItemId)).ToLookup(x => x.ContentItemId); if (!entriesByContainer.Contains(entry.ContentItemId)) { @@ -104,14 +102,12 @@ protected void AddEntries(IEnumerable entries) foreach (var entry in entries) { - if (_paths.TryGetValue(entry.ContentItemId, out var previousContainerEntry) && - string.IsNullOrEmpty(entry.ContainedContentItemId)) + if (_paths.TryGetValue(entry.ContentItemId, out var previousContainerEntry) && string.IsNullOrEmpty(entry.ContainedContentItemId)) { _contentItemIds = _contentItemIds.Remove(previousContainerEntry.Path); } - if (!string.IsNullOrEmpty(entry.ContainedContentItemId) && - _paths.TryGetValue(entry.ContainedContentItemId, out var previousContainedEntry)) + if (!string.IsNullOrEmpty(entry.ContainedContentItemId) && _paths.TryGetValue(entry.ContainedContentItemId, out var previousContainedEntry)) { _contentItemIds = _contentItemIds.Remove(previousContainedEntry.Path); } @@ -134,8 +130,7 @@ protected void RemoveEntries(IEnumerable entries) foreach (var entry in entries) { // Evict all entries related to a container item from autoroute entries. - var entriesToRemove = _paths.Values.Where(x => x.ContentItemId == entry.ContentItemId && - !string.IsNullOrEmpty(x.ContainedContentItemId)); + var entriesToRemove = _paths.Values.Where(x => x.ContentItemId == entry.ContentItemId && !string.IsNullOrEmpty(x.ContainedContentItemId)); _paths = _paths.RemoveRange(entriesToRemove.Select(x => x.ContainedContentItemId)); _contentItemIds = _contentItemIds.RemoveRange(entriesToRemove.Select(x => x.Path)); @@ -157,10 +152,7 @@ private async Task RefreshEntriesAsync(AutorouteStateDocument state) { if (_stateIdentifier != state.Identifier) { - var indexes = await Session - .QueryIndex(i => i.Id > _lastIndexId) - .OrderBy(i => i.Id) - .ListAsync(); + var indexes = await Session.QueryIndex(i => i.Id > _lastIndexId).OrderBy(i => i.Id).ListAsync(); // A draft is indexed to check for conflicts, and to remove an entry, but only if an item is unpublished, // so only if the entry 'DocumentId' matches, this because when a draft is saved more than once, the index @@ -168,22 +160,24 @@ private async Task RefreshEntriesAsync(AutorouteStateDocument state) var entriesToRemove = indexes .Where(i => !i.Published || i.Path == null) - .SelectMany(i => _paths.Values.Where(e => - // The item was removed. - ((!i.Published && !i.Latest) || - // The part was disabled or removed. - (i.Path == null && i.Published) || - // The item was unpublished. - (!i.Published && e.DocumentId == i.DocumentId)) && - (e.ContentItemId == i.ContentItemId || - e.ContainedContentItemId == i.ContentItemId))); + .SelectMany(i => + _paths.Values.Where(e => + // The item was removed. + ( + (!i.Published && !i.Latest) + || + // The part was disabled or removed. + (i.Path == null && i.Published) + || + // The item was unpublished. + (!i.Published && e.DocumentId == i.DocumentId) + ) && (e.ContentItemId == i.ContentItemId || e.ContainedContentItemId == i.ContentItemId) + ) + ); var entriesToAdd = indexes .Where(i => i.Published && i.Path != null) - .Select(i => new AutorouteEntry(i.ContentItemId, i.Path, i.ContainedContentItemId, i.JsonPath) - { - DocumentId = i.DocumentId - }); + .Select(i => new AutorouteEntry(i.ContentItemId, i.Path, i.ContainedContentItemId, i.JsonPath) { DocumentId = i.DocumentId }); RemoveEntries(entriesToRemove); AddEntries(entriesToAdd); @@ -212,15 +206,9 @@ protected virtual async Task InitializeEntriesAsync() { var state = await _autorouteStateManager.GetOrCreateImmutableAsync(); - var indexes = await Session - .QueryIndex(i => i.Published && i.Path != null) - .OrderBy(i => i.Id) - .ListAsync(); + var indexes = await Session.QueryIndex(i => i.Published && i.Path != null).OrderBy(i => i.Id).ListAsync(); - var entries = indexes.Select(i => new AutorouteEntry(i.ContentItemId, i.Path, i.ContainedContentItemId, i.JsonPath) - { - DocumentId = i.DocumentId - }); + var entries = indexes.Select(i => new AutorouteEntry(i.ContentItemId, i.Path, i.ContainedContentItemId, i.JsonPath) { DocumentId = i.DocumentId }); AddEntries(entries); diff --git a/src/OrchardCore/OrchardCore.Configuration.KeyVault/Extensions/AzureKeyVaultConfigurationExtension.cs b/src/OrchardCore/OrchardCore.Configuration.KeyVault/Extensions/AzureKeyVaultConfigurationExtension.cs index 1ffd074169e..14b96a797fc 100644 --- a/src/OrchardCore/OrchardCore.Configuration.KeyVault/Extensions/AzureKeyVaultConfigurationExtension.cs +++ b/src/OrchardCore/OrchardCore.Configuration.KeyVault/Extensions/AzureKeyVaultConfigurationExtension.cs @@ -21,13 +21,15 @@ public static IHostBuilder AddOrchardCoreAzureKeyVault(this IHostBuilder builder { ArgumentNullException.ThrowIfNull(builder); - builder.ConfigureAppConfiguration((context, builder) => - { - // Here 'builder' is a config manager being a builder and also an 'IConfigurationRoot' - // if get from the 'context', allowing to get values from the providers already added - // without having to build a configuration on the fly that would need to be disposed. - AddOrchardCoreAzureKeyVault(builder, context.Configuration, tokenCredential); - }); + builder.ConfigureAppConfiguration( + (context, builder) => + { + // Here 'builder' is a config manager being a builder and also an 'IConfigurationRoot' + // if get from the 'context', allowing to get values from the providers already added + // without having to build a configuration on the fly that would need to be disposed. + AddOrchardCoreAzureKeyVault(builder, context.Configuration, tokenCredential); + } + ); return builder; } @@ -39,13 +41,15 @@ public static IWebHostBuilder AddOrchardCoreAzureKeyVault(this IWebHostBuilder b { ArgumentNullException.ThrowIfNull(builder); - builder.ConfigureAppConfiguration((context, builder) => - { - // Here 'builder' is a config manager being a builder and also an 'IConfigurationRoot' - // if get from the 'context', allowing to get values from the providers already added - // without having to build a configuration on the fly that would need to be disposed. - AddOrchardCoreAzureKeyVault(builder, context.Configuration, tokenCredential); - }); + builder.ConfigureAppConfiguration( + (context, builder) => + { + // Here 'builder' is a config manager being a builder and also an 'IConfigurationRoot' + // if get from the 'context', allowing to get values from the providers already added + // without having to build a configuration on the fly that would need to be disposed. + AddOrchardCoreAzureKeyVault(builder, context.Configuration, tokenCredential); + } + ); return builder; } @@ -53,8 +57,7 @@ public static IWebHostBuilder AddOrchardCoreAzureKeyVault(this IWebHostBuilder b /// /// Adds Azure Key Vault as a Configuration Source. /// - public static ConfigurationManager AddOrchardCoreAzureKeyVault( - this ConfigurationManager manager, TokenCredential tokenCredential = null) + public static ConfigurationManager AddOrchardCoreAzureKeyVault(this ConfigurationManager manager, TokenCredential tokenCredential = null) { ArgumentNullException.ThrowIfNull(manager); @@ -65,25 +68,25 @@ public static ConfigurationManager AddOrchardCoreAzureKeyVault( return manager; } - private static void AddOrchardCoreAzureKeyVault( - this IConfigurationBuilder builder, IConfiguration configuration, TokenCredential tokenCredential) + private static void AddOrchardCoreAzureKeyVault(this IConfigurationBuilder builder, IConfiguration configuration, TokenCredential tokenCredential) { var keyVaultName = configuration["OrchardCore:OrchardCore_KeyVault_Azure:KeyVaultName"]; if (string.IsNullOrEmpty(keyVaultName)) { - throw new Exception("The 'KeyVaultName' property is no configured. Please configure it by specifying the 'OrchardCore:OrchardCore_KeyVault_Azure:KeyVaultName' settings key."); + throw new Exception( + "The 'KeyVaultName' property is no configured. Please configure it by specifying the 'OrchardCore:OrchardCore_KeyVault_Azure:KeyVaultName' settings key." + ); } if (!Uri.TryCreate($"https://{keyVaultName}.vault.azure.net", UriKind.Absolute, out var keyVaultEndpointUri)) { - throw new Exception("Invalid value used for 'KeyVaultName' property. Please provide a valid key-vault name using the 'OrchardCore:OrchardCore_KeyVault_Azure:KeyVaultName' settings key."); + throw new Exception( + "Invalid value used for 'KeyVaultName' property. Please provide a valid key-vault name using the 'OrchardCore:OrchardCore_KeyVault_Azure:KeyVaultName' settings key." + ); } - var configOptions = new AzureKeyVaultConfigurationOptions() - { - Manager = new AzureKeyVaultSecretManager(), - }; + var configOptions = new AzureKeyVaultConfigurationOptions() { Manager = new AzureKeyVaultSecretManager(), }; if (double.TryParse(configuration["OrchardCore:OrchardCore_KeyVault_Azure:ReloadInterval"], out var interval)) { diff --git a/src/OrchardCore/OrchardCore.Configuration.KeyVault/Services/AzureKeyVaultSecretManager.cs b/src/OrchardCore/OrchardCore.Configuration.KeyVault/Services/AzureKeyVaultSecretManager.cs index 790e4f7d905..3a3e5afc44e 100644 --- a/src/OrchardCore/OrchardCore.Configuration.KeyVault/Services/AzureKeyVaultSecretManager.cs +++ b/src/OrchardCore/OrchardCore.Configuration.KeyVault/Services/AzureKeyVaultSecretManager.cs @@ -5,7 +5,6 @@ namespace OrchardCore.Configuration.KeyVault.Services { public class AzureKeyVaultSecretManager : KeyVaultSecretManager { - public override string GetKey(KeyVaultSecret secret) => - secret.Name.Replace("---", "_").Replace("--", ":"); + public override string GetKey(KeyVaultSecret secret) => secret.Name.Replace("---", "_").Replace("--", ":"); } } diff --git a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/ContentLocalizationHandlerBase.cs b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/ContentLocalizationHandlerBase.cs index caf6b5f510a..04fa93bc94c 100644 --- a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/ContentLocalizationHandlerBase.cs +++ b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/ContentLocalizationHandlerBase.cs @@ -8,6 +8,7 @@ public virtual Task LocalizedAsync(LocalizationContentContext context) { return Task.CompletedTask; } + public virtual Task LocalizingAsync(LocalizationContentContext context) { return Task.CompletedTask; diff --git a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/ContentLocalizationPartHandlerBase.cs b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/ContentLocalizationPartHandlerBase.cs index 49e8dbca735..73bba4bbfcc 100644 --- a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/ContentLocalizationPartHandlerBase.cs +++ b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/ContentLocalizationPartHandlerBase.cs @@ -3,7 +3,8 @@ namespace OrchardCore.ContentLocalization.Handlers { - public abstract class ContentLocalizationPartHandlerBase : IContentLocalizationPartHandler where TPart : ContentPart, new() + public abstract class ContentLocalizationPartHandlerBase : IContentLocalizationPartHandler + where TPart : ContentPart, new() { async Task IContentLocalizationPartHandler.LocalizingAsync(LocalizationContentContext context, ContentPart part) { @@ -20,7 +21,9 @@ async Task IContentLocalizationPartHandler.LocalizedAsync(LocalizationContentCon await LocalizedAsync(context, tpart); } } + public virtual Task LocalizingAsync(LocalizationContentContext context, TPart part) => Task.CompletedTask; + public virtual Task LocalizedAsync(LocalizationContentContext context, TPart part) => Task.CompletedTask; } } diff --git a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/LocalizationContentContext.cs b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/LocalizationContentContext.cs index 6f80904f9e8..dca4fdb7cdf 100644 --- a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/LocalizationContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/LocalizationContentContext.cs @@ -8,6 +8,7 @@ public class LocalizationContentContext : ContentContextBase public ContentItem Original { get; set; } public string LocalizationSet { get; set; } public string Culture { get; set; } + public LocalizationContentContext(ContentItem contentItem, ContentItem original, string localizationSet, string culture) : base(contentItem) { diff --git a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/IContentLocalizationManager.cs b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/IContentLocalizationManager.cs index bb266492ad3..eda99be0e07 100644 --- a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/IContentLocalizationManager.cs +++ b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/IContentLocalizationManager.cs @@ -47,6 +47,7 @@ public interface IContentLocalizationManager /// - OR First ContentItemId found in the set. /// Task> GetFirstItemIdForSetsAsync(IEnumerable localizationSets); + /// /// Get the ContenItems that match the culture and localizationSet. /// A single ContentItem is returned per set if it exists. diff --git a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Records/LocalizedContentItemIndex.cs b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Records/LocalizedContentItemIndex.cs index 9adaa9adc3e..16a7ae8eed2 100644 --- a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Records/LocalizedContentItemIndex.cs +++ b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Records/LocalizedContentItemIndex.cs @@ -54,7 +54,7 @@ public override async Task PublishedAsync(PublishContentContext context) var part = context.ContentItem.As(); // Validate that the content definition contains this part, this prevents indexing parts - // that have been removed from the type definition, but are still present in the elements. + // that have been removed from the type definition, but are still present in the elements. if (part != null) { // Lazy initialization because of ISession cyclic dependency. @@ -71,12 +71,15 @@ public override async Task PublishedAsync(PublishContentContext context) } public string CollectionName { get; set; } + public Type ForType() => typeof(ContentItem); + public void Describe(IDescriptor context) => Describe((DescribeContext)context); public void Describe(DescribeContext context) { - context.For() + context + .For() .When(contentItem => contentItem.Has() || _partRemoved.Contains(contentItem.ContentItemId)) .Map(contentItem => { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentDefinitionManagerExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentDefinitionManagerExtensions.cs index ebf23bc93c2..943d83d5f90 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentDefinitionManagerExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentDefinitionManagerExtensions.cs @@ -69,7 +69,8 @@ public static async Task AlterPartDefinitionAsync(this IContentDefinitionManager /// [Obsolete($"Instead, utilize the {nameof(MigratePartSettingsAsync)} method. This current method is slated for removal in upcoming releases.")] public static void MigratePartSettings(this IContentDefinitionManager manager) - where TPart : ContentPart where TSettings : class + where TPart : ContentPart + where TSettings : class { var contentTypes = manager.LoadTypeDefinitions(); @@ -88,13 +89,19 @@ public static void MigratePartSettings(this IContentDefinition } // Apply existing settings to type definition WithSettings - manager.AlterTypeDefinition(contentType.Name, typeBuilder => - { - typeBuilder.WithPart(partDefinition.Name, partBuilder => + manager.AlterTypeDefinition( + contentType.Name, + typeBuilder => { - partBuilder.WithSettings(existingSettings); - }); - }); + typeBuilder.WithPart( + partDefinition.Name, + partBuilder => + { + partBuilder.WithSettings(existingSettings); + } + ); + } + ); } } } @@ -107,7 +114,8 @@ public static void MigratePartSettings(this IContentDefinition /// /// public static async Task MigratePartSettingsAsync(this IContentDefinitionManager manager) - where TPart : ContentPart where TSettings : class + where TPart : ContentPart + where TSettings : class { var contentTypes = await manager.LoadTypeDefinitionsAsync(); @@ -126,15 +134,21 @@ public static async Task MigratePartSettingsAsync(this IConten } // Apply existing settings to type definition WithSettings - await manager.AlterTypeDefinitionAsync(contentType.Name, typeBuilder => - { - typeBuilder.WithPart(partDefinition.Name, partBuilder => + await manager.AlterTypeDefinitionAsync( + contentType.Name, + typeBuilder => { - partBuilder.WithSettings(existingSettings); - }); + typeBuilder.WithPart( + partDefinition.Name, + partBuilder => + { + partBuilder.WithSettings(existingSettings); + } + ); - return Task.CompletedTask; - }); + return Task.CompletedTask; + } + ); } } } @@ -148,40 +162,47 @@ await manager.AlterTypeDefinitionAsync(contentType.Name, typeBuilder => /// [Obsolete($"Instead, utilize the {nameof(MigrateFieldSettingsAsync)} method. This current method is slated for removal in upcoming releases.")] public static void MigrateFieldSettings(this IContentDefinitionManager manager) - where TField : ContentField where TSettings : class + where TField : ContentField + where TSettings : class { var partDefinitions = manager.LoadPartDefinitions(); foreach (var partDefinition in partDefinitions) { - manager.AlterPartDefinition(partDefinition.Name, partBuilder => - { - foreach (var fieldDefinition in partDefinition.Fields.Where(x => x.FieldDefinition.Name == typeof(TField).Name)) + manager.AlterPartDefinition( + partDefinition.Name, + partBuilder => { - var existingFieldSettings = fieldDefinition.Settings.ToObject(); - - // Do this before creating builder, so settings are removed from the builder settings object. - // Remove existing properties from JObject - var fieldSettingsProperties = existingFieldSettings.GetType().GetProperties(); - var hasSetting = false; - foreach (var property in fieldSettingsProperties) + foreach (var fieldDefinition in partDefinition.Fields.Where(x => x.FieldDefinition.Name == typeof(TField).Name)) { - if (fieldDefinition.Settings.ContainsKey(property.Name)) + var existingFieldSettings = fieldDefinition.Settings.ToObject(); + + // Do this before creating builder, so settings are removed from the builder settings object. + // Remove existing properties from JObject + var fieldSettingsProperties = existingFieldSettings.GetType().GetProperties(); + var hasSetting = false; + foreach (var property in fieldSettingsProperties) { - hasSetting = true; - fieldDefinition.Settings.Remove(property.Name); + if (fieldDefinition.Settings.ContainsKey(property.Name)) + { + hasSetting = true; + fieldDefinition.Settings.Remove(property.Name); + } } - } - // Only include settings if the definition already has at least one of these settings. - if (hasSetting) - { - partBuilder.WithField(fieldDefinition.Name, fieldBuilder => + // Only include settings if the definition already has at least one of these settings. + if (hasSetting) { - fieldBuilder.WithSettings(existingFieldSettings); - }); + partBuilder.WithField( + fieldDefinition.Name, + fieldBuilder => + { + fieldBuilder.WithSettings(existingFieldSettings); + } + ); + } } } - }); + ); } } @@ -193,41 +214,48 @@ public static void MigrateFieldSettings(this IContentDefiniti /// /// public static async Task MigrateFieldSettingsAsync(this IContentDefinitionManager manager) - where TField : ContentField where TSettings : class + where TField : ContentField + where TSettings : class { var partDefinitions = await manager.LoadPartDefinitionsAsync(); foreach (var partDefinition in partDefinitions) { - await manager.AlterPartDefinitionAsync(partDefinition.Name, partBuilder => - { - foreach (var fieldDefinition in partDefinition.Fields.Where(x => x.FieldDefinition.Name == typeof(TField).Name)) + await manager.AlterPartDefinitionAsync( + partDefinition.Name, + partBuilder => { - var existingFieldSettings = fieldDefinition.Settings.ToObject(); - - // Do this before creating builder, so settings are removed from the builder settings object. - // Remove existing properties from JObject - var fieldSettingsProperties = existingFieldSettings.GetType().GetProperties(); - var hasSetting = false; - foreach (var property in fieldSettingsProperties) + foreach (var fieldDefinition in partDefinition.Fields.Where(x => x.FieldDefinition.Name == typeof(TField).Name)) { - if (fieldDefinition.Settings.ContainsKey(property.Name)) + var existingFieldSettings = fieldDefinition.Settings.ToObject(); + + // Do this before creating builder, so settings are removed from the builder settings object. + // Remove existing properties from JObject + var fieldSettingsProperties = existingFieldSettings.GetType().GetProperties(); + var hasSetting = false; + foreach (var property in fieldSettingsProperties) { - hasSetting = true; - fieldDefinition.Settings.Remove(property.Name); + if (fieldDefinition.Settings.ContainsKey(property.Name)) + { + hasSetting = true; + fieldDefinition.Settings.Remove(property.Name); + } } - } - // Only include settings if the definition already has at least one of these settings. - if (hasSetting) - { - partBuilder.WithField(fieldDefinition.Name, fieldBuilder => + // Only include settings if the definition already has at least one of these settings. + if (hasSetting) { - fieldBuilder.WithSettings(existingFieldSettings); - }); + partBuilder.WithField( + fieldDefinition.Name, + fieldBuilder => + { + fieldBuilder.WithSettings(existingFieldSettings); + } + ); + } } } - }); + ); } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentElement.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentElement.cs index 0adec5490f6..41343a24a60 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentElement.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentElement.cs @@ -14,9 +14,8 @@ public class ContentElement : IContent private Dictionary _elements; private JsonDynamicObject _dynamicObject; - internal ContentElement() : this([]) - { - } + internal ContentElement() + : this([]) { } internal ContentElement(JsonObject data) => Data = data; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentExtensions.cs index b10447ef7e3..ae68617d7f1 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentExtensions.cs @@ -14,11 +14,8 @@ public static class ContentExtensions /// /// These settings instruct merge to replace current value, even for null values. /// - private static readonly JsonMergeSettings _jsonMergeSettings = new() - { - MergeArrayHandling = MergeArrayHandling.Replace, - MergeNullValueHandling = MergeNullValueHandling.Merge - }; + private static readonly JsonMergeSettings _jsonMergeSettings = + new() { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }; /// /// Gets a content element by its name. @@ -27,7 +24,8 @@ public static class ContentExtensions /// The name of the content element. /// The expected type of the content element. /// The content element instance or. null if it doesn't exist. - public static TElement Get(this ContentElement contentElement, string name) where TElement : ContentElement + public static TElement Get(this ContentElement contentElement, string name) + where TElement : ContentElement { var result = contentElement.Get(typeof(TElement), name); @@ -49,7 +47,8 @@ public static TElement Get(this ContentElement contentElement, string /// /// The . /// The expected type of the content element. - public static bool Has(this ContentElement contentElement) where TElement : ContentElement + public static bool Has(this ContentElement contentElement) + where TElement : ContentElement { return contentElement.Has(typeof(TElement).Name); } @@ -103,16 +102,14 @@ public static bool Remove(this ContentElement contentElement, string name) /// The name of the content element. /// The expected type of the content element. /// The content element instance or a new one if it doesn't exist. - public static TElement GetOrCreate(this ContentElement contentElement, string name) where TElement : ContentElement, new() + public static TElement GetOrCreate(this ContentElement contentElement, string name) + where TElement : ContentElement, new() { var existing = contentElement.Get(name); if (existing == null) { - var newElement = new TElement - { - ContentItem = contentElement.ContentItem, - }; + var newElement = new TElement { ContentItem = contentElement.ContentItem, }; contentElement.Data[name] = newElement.Data; contentElement.Elements[name] = newElement; @@ -148,7 +145,8 @@ public static ContentElement Weld(this ContentElement contentElement, string nam /// This part can be not defined in Content Definitions. /// /// The type of the part to be welded. - public static ContentElement Weld(this ContentElement contentElement, object settings = null) where TElement : ContentElement, new() + public static ContentElement Weld(this ContentElement contentElement, object settings = null) + where TElement : ContentElement, new() { var elementName = typeof(TElement).Name; @@ -168,9 +166,7 @@ public static ContentElement Weld(this ContentElement contentElement, string nam var weldedPartSettings = result.AsObject(); - weldedPartSettings[elementName] = settings is not null - ? JObject.FromObject(settings) - : []; + weldedPartSettings[elementName] = settings is not null ? JObject.FromObject(settings) : []; return contentElement; } @@ -238,7 +234,8 @@ public static ContentElement Apply(this ContentElement contentElement, ContentEl /// An action to apply on the content element. /// The type of the part to be altered. /// The current instance. - public static ContentElement Alter(this ContentElement contentElement, string name, Action action) where TElement : ContentElement, new() + public static ContentElement Alter(this ContentElement contentElement, string name, Action action) + where TElement : ContentElement, new() { var element = contentElement.GetOrCreate(name); action(element); @@ -255,7 +252,8 @@ public static ContentElement Apply(this ContentElement contentElement, ContentEl /// An action to apply on the content element. /// The type of the part to be altered. /// The current instance. - public static async Task AlterAsync(this ContentElement contentElement, string name, Func action) where TElement : ContentElement, new() + public static async Task AlterAsync(this ContentElement contentElement, string name, Func action) + where TElement : ContentElement, new() { var element = contentElement.GetOrCreate(name); @@ -301,7 +299,8 @@ public static bool HasDraft(this IContent content) /// /// The expected type of the content elements. /// The content element instances or empty sequence if no entries exist. - public static IEnumerable OfType(this ContentElement contentElement) where TElement : ContentElement + public static IEnumerable OfType(this ContentElement contentElement) + where TElement : ContentElement { foreach (var part in contentElement.Elements) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentField.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentField.cs index d3649cc5ab3..71f47bef71b 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentField.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentField.cs @@ -1,6 +1,4 @@ namespace OrchardCore.ContentManagement { - public class ContentField : ContentElement - { - } + public class ContentField : ContentElement { } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentFieldOption.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentFieldOption.cs index ec56027bd1c..279c0bc35e5 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentFieldOption.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentFieldOption.cs @@ -7,9 +7,8 @@ public class ContentFieldOption : ContentFieldOptionBase { private readonly List _handlers = []; - public ContentFieldOption(Type contentFieldType) : base(contentFieldType) - { - } + public ContentFieldOption(Type contentFieldType) + : base(contentFieldType) { } public IReadOnlyList Handlers => _handlers; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItem.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItem.cs index 506eddc402b..7a1dddddcdb 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItem.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItem.cs @@ -9,7 +9,8 @@ namespace OrchardCore.ContentManagement [JsonConverter(typeof(ContentItemConverter))] public class ContentItem : ContentElement { - public ContentItem() : base() + public ContentItem() + : base() { ContentItem = this; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemConverter.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemConverter.cs index fa4b82c08e9..aae31eec1e4 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemConverter.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemConverter.cs @@ -65,24 +65,19 @@ public override ContentItem Read(ref Utf8JsonReader reader, Type typeToConvert, contentItem.DisplayText = reader.TokenType == JsonTokenType.String ? reader.GetString() : null; break; case nameof(ContentItem.Latest): - contentItem.Latest = (reader.TokenType == JsonTokenType.True || - reader.TokenType == JsonTokenType.False) && reader.GetBoolean(); + contentItem.Latest = (reader.TokenType == JsonTokenType.True || reader.TokenType == JsonTokenType.False) && reader.GetBoolean(); break; case nameof(ContentItem.Published): - contentItem.Published = (reader.TokenType == JsonTokenType.True || - reader.TokenType == JsonTokenType.False) && reader.GetBoolean(); + contentItem.Published = (reader.TokenType == JsonTokenType.True || reader.TokenType == JsonTokenType.False) && reader.GetBoolean(); break; case nameof(ContentItem.PublishedUtc): - contentItem.PublishedUtc = reader.TokenType != JsonTokenType.Null && - reader.TryGetDateTime(out var date) ? date : null; + contentItem.PublishedUtc = reader.TokenType != JsonTokenType.Null && reader.TryGetDateTime(out var date) ? date : null; break; case nameof(ContentItem.ModifiedUtc): - contentItem.ModifiedUtc = reader.TokenType != JsonTokenType.Null && - reader.TryGetDateTime(out date) ? date : null; + contentItem.ModifiedUtc = reader.TokenType != JsonTokenType.Null && reader.TryGetDateTime(out date) ? date : null; break; case nameof(ContentItem.CreatedUtc): - contentItem.CreatedUtc = reader.TokenType != JsonTokenType.Null && - reader.TryGetDateTime(out date) ? date : null; + contentItem.CreatedUtc = reader.TokenType != JsonTokenType.Null && reader.TryGetDateTime(out date) ? date : null; break; case nameof(ContentItem.Author): contentItem.Author = reader.TokenType == JsonTokenType.String ? reader.GetString() : null; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemExtensions.cs index d0ce29c42d2..32b411152a6 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemExtensions.cs @@ -14,8 +14,8 @@ public static class ContentItemExtensions /// The . /// The if one existed. /// true if a part found, otherwise false. - public static bool TryGet(this ContentItem contentItem, out TPart part) where TPart : ContentPart - => contentItem.TryGet(typeof(TPart).Name, out part); + public static bool TryGet(this ContentItem contentItem, out TPart part) + where TPart : ContentPart => contentItem.TryGet(typeof(TPart).Name, out part); /// /// Tries to get a content part by its type. @@ -25,7 +25,8 @@ public static bool TryGet(this ContentItem contentItem, out TPart part) w /// The name of the content part. /// The if one existed. /// true if a part found, otherwise false. - public static bool TryGet(this ContentItem contentItem, string name, out TPart part) where TPart : ContentPart + public static bool TryGet(this ContentItem contentItem, string name, out TPart part) + where TPart : ContentPart { ArgumentException.ThrowIfNullOrEmpty(name); @@ -69,8 +70,8 @@ public static bool TryGet(this ContentItem contentItem, Type contentElementType, /// The . /// The type of the content part. /// The content part or. null if it doesn't exist. - public static TPart As(this ContentItem contentItem) where TPart : ContentPart - => contentItem.Get(typeof(TPart).Name); + public static TPart As(this ContentItem contentItem) + where TPart : ContentPart => contentItem.Get(typeof(TPart).Name); /// /// Gets a content part by its type or create a new one. @@ -78,16 +79,16 @@ public static TPart As(this ContentItem contentItem) where TPart : Conten /// The . /// The type of the content part. /// The content part instance or a new one if it doesn't exist. - public static TPart GetOrCreate(this ContentItem contentItem) where TPart : ContentPart, new() - => contentItem.GetOrCreate(typeof(TPart).Name); + public static TPart GetOrCreate(this ContentItem contentItem) + where TPart : ContentPart, new() => contentItem.GetOrCreate(typeof(TPart).Name); /// /// Removes a content part by its type. /// /// The . /// The type of the content part. - public static void Remove(this ContentItem contentItem) where TPart : ContentPart, new() - => contentItem.Remove(typeof(TPart).Name); + public static void Remove(this ContentItem contentItem) + where TPart : ContentPart, new() => contentItem.Remove(typeof(TPart).Name); /// /// Adds a content part by its type. @@ -96,7 +97,8 @@ public static TPart As(this ContentItem contentItem) where TPart : Conten /// The content part to weld. /// The type of the content part. /// The current instance. - public static ContentItem Weld(this ContentItem contentItem, TPart part) where TPart : ContentPart + public static ContentItem Weld(this ContentItem contentItem, TPart part) + where TPart : ContentPart { contentItem.Weld(typeof(TPart).Name, part); @@ -110,7 +112,8 @@ public static ContentItem Weld(this ContentItem contentItem, TPart part) /// The content part to update. /// The type of the content part. /// The current instance. - public static ContentItem Apply(this ContentItem contentItem, TPart part) where TPart : ContentPart + public static ContentItem Apply(this ContentItem contentItem, TPart part) + where TPart : ContentPart { contentItem.Apply(typeof(TPart).Name, part); @@ -124,7 +127,8 @@ public static ContentItem Apply(this ContentItem contentItem, TPart part) /// An action to apply on the content part. /// The type of the content part. /// The current instance. - public static ContentItem Alter(this ContentItem contentItem, Action action) where TPart : ContentPart, new() + public static ContentItem Alter(this ContentItem contentItem, Action action) + where TPart : ContentPart, new() { var part = contentItem.GetOrCreate(); action(part); @@ -140,7 +144,8 @@ public static ContentItem Apply(this ContentItem contentItem, TPart part) /// An action to apply on the content part. /// The type of the content part. /// The current instance. - public static async Task AlterAsync(this ContentItem contentItem, Func action) where TPart : ContentPart, new() + public static async Task AlterAsync(this ContentItem contentItem, Func action) + where TPart : ContentPart, new() { var part = contentItem.GetOrCreate(); await action(part); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentOptions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentOptions.cs index 51f9b653949..952878ce9b5 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentOptions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentOptions.cs @@ -14,12 +14,10 @@ public class ContentOptions private readonly List _contentFields = []; private IReadOnlyDictionary _contentPartOptionsLookup; - public IReadOnlyDictionary ContentPartOptionsLookup - => _contentPartOptionsLookup ??= ContentPartOptions.ToFrozenDictionary(k => k.Type.Name); + public IReadOnlyDictionary ContentPartOptionsLookup => _contentPartOptionsLookup ??= ContentPartOptions.ToFrozenDictionary(k => k.Type.Name); private IReadOnlyDictionary _contentFieldOptionsLookup; - public IReadOnlyDictionary ContentFieldOptionsLookup - => _contentFieldOptionsLookup ??= ContentFieldOptions.ToFrozenDictionary(k => k.Type.Name); + public IReadOnlyDictionary ContentFieldOptionsLookup => _contentFieldOptionsLookup ??= ContentFieldOptions.ToFrozenDictionary(k => k.Type.Name); public IReadOnlyList ContentPartOptions => _contentParts; public IReadOnlyList ContentFieldOptions => _contentFields; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPart.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPart.cs index a862a17539c..8839f780504 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPart.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPart.cs @@ -1,6 +1,4 @@ namespace OrchardCore.ContentManagement { - public class ContentPart : ContentElement - { - } + public class ContentPart : ContentElement { } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPartOption.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPartOption.cs index 7f3f79e5b7e..072cbce3587 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPartOption.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPartOption.cs @@ -7,9 +7,8 @@ public class ContentPartOption : ContentPartOptionBase { private readonly List _handlers = []; - public ContentPartOption(Type contentPartType) : base(contentPartType) - { - } + public ContentPartOption(Type contentPartType) + : base(contentPartType) { } public IReadOnlyList Handlers => _handlers; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentQueryExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentQueryExtensions.cs index 587606b7f96..32523ecf52f 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentQueryExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentQueryExtensions.cs @@ -30,14 +30,14 @@ public static async Task FirstOrDefaultAsync(this IQuery to return all matching s /// but after having invoked the load events on them by using the . /// - public static async Task> ListAsync(this IQuery query, IContentManager contentManager) - => await contentManager.LoadAsync(await query.ListAsync()); + public static async Task> ListAsync(this IQuery query, IContentManager contentManager) => + await contentManager.LoadAsync(await query.ListAsync()); /// /// Executes this to return all matching s /// but after having invoked the load events on them by using the . /// - public static IAsyncEnumerable ToAsyncEnumerable(this IQuery query, IContentManager contentManager) - => contentManager.LoadAsync(query.ToAsyncEnumerable()); + public static IAsyncEnumerable ToAsyncEnumerable(this IQuery query, IContentManager contentManager) => + contentManager.LoadAsync(query.ToAsyncEnumerable()); } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentQueryOfTIndexExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentQueryOfTIndexExtensions.cs index 7cfb5323e4e..9447a3eb52a 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentQueryOfTIndexExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentQueryOfTIndexExtensions.cs @@ -33,15 +33,13 @@ public static async Task FirstOrDefaultAsync(this IQuery. /// public static async Task> ListAsync(this IQuery query, IContentManager contentManager) - where TIndex : class, IIndex - => await contentManager.LoadAsync(await query.ListAsync()); + where TIndex : class, IIndex => await contentManager.LoadAsync(await query.ListAsync()); /// /// Executes this to return all matching s /// but after having invoked the load events on them by using the . /// public static IAsyncEnumerable ToAsyncEnumerable(this IQuery query, IContentManager contentManager) - where TIndex : class, IIndex - => contentManager.LoadAsync(query.ToAsyncEnumerable()); + where TIndex : class, IIndex => contentManager.LoadAsync(query.ToAsyncEnumerable()); } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ActivatedContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ActivatedContentContext.cs index bf5f7805a54..17696a66564 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ActivatedContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ActivatedContentContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.ContentManagement.Handlers { public class ActivatedContentContext : ContentContextBase { - public ActivatedContentContext(ContentItem contentItem) : base(contentItem) - { - } + public ActivatedContentContext(ContentItem contentItem) + : base(contentItem) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ActivatingContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ActivatingContentContext.cs index cf9a6f8219a..1e9f5cf2bee 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ActivatingContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ActivatingContentContext.cs @@ -4,9 +4,8 @@ namespace OrchardCore.ContentManagement.Handlers { public class ActivatingContentContext : ContentContextBase { - public ActivatingContentContext(ContentItem contentItem) : base(contentItem) - { - } + public ActivatingContentContext(ContentItem contentItem) + : base(contentItem) { } public string ContentType { get; set; } public ContentTypeDefinition Definition { get; set; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentFieldHandler.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentFieldHandler.cs index 129866378c8..e90beb901ea 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentFieldHandler.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentFieldHandler.cs @@ -2,181 +2,134 @@ namespace OrchardCore.ContentManagement.Handlers; -public abstract class ContentFieldHandler : IContentFieldHandler where TField : ContentField, new() +public abstract class ContentFieldHandler : IContentFieldHandler + where TField : ContentField, new() { Task IContentFieldHandler.ActivatedAsync(ActivatedContentFieldContext context, ContentField field) { - return field is TField tfield - ? ActivatedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? ActivatedAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.ActivatingAsync(ActivatingContentFieldContext context, ContentField field) { - return field is TField tfield - ? ActivatingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? ActivatingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.InitializingAsync(InitializingContentFieldContext context, ContentField field) { - return field is TField tfield - ? InitializingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? InitializingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.InitializedAsync(InitializingContentFieldContext context, ContentField field) { - return field is TField tfield - ? InitializedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? InitializedAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.CreatingAsync(CreateContentFieldContext context, ContentField field) { - return field is TField tfield - ? CreatingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? CreatingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.CreatedAsync(CreateContentFieldContext context, ContentField field) { - return field is TField tfield - ? CreatedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? CreatedAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.LoadingAsync(LoadContentFieldContext context, ContentField field) { - return field is TField tfield - ? LoadingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? LoadingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.LoadedAsync(LoadContentFieldContext context, ContentField field) { - return field is TField tfield - ? LoadedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? LoadedAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.ImportingAsync(ImportContentFieldContext context, ContentField field) { - return field is TField tfield - ? ImportingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? ImportingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.ImportedAsync(ImportContentFieldContext context, ContentField field) { - return field is TField tfield - ? ImportedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? ImportedAsync(context, tfield) : Task.CompletedTask; } + Task IContentFieldHandler.UpdatingAsync(UpdateContentFieldContext context, ContentField field) { - return field is TField tfield - ? UpdatingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? UpdatingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.UpdatedAsync(UpdateContentFieldContext context, ContentField field) { - return field is TField tfield - ? UpdatedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? UpdatedAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.ValidatingAsync(ValidateContentFieldContext context, ContentField field) { - return field is TField tfield - ? ValidatingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? ValidatingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.ValidatedAsync(ValidateContentFieldContext context, ContentField field) { - return field is TField tfield - ? ValidatedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? ValidatedAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.VersioningAsync(VersionContentFieldContext context, ContentField existing, ContentField building) { - return existing is TField texisting && building is TField tbuilding - ? VersioningAsync(context, texisting, tbuilding) - : Task.CompletedTask; + return existing is TField texisting && building is TField tbuilding ? VersioningAsync(context, texisting, tbuilding) : Task.CompletedTask; } Task IContentFieldHandler.VersionedAsync(VersionContentFieldContext context, ContentField existing, ContentField building) { - return existing is TField texisting && building is TField tbuilding - ? VersionedAsync(context, texisting, tbuilding) - : Task.CompletedTask; + return existing is TField texisting && building is TField tbuilding ? VersionedAsync(context, texisting, tbuilding) : Task.CompletedTask; } Task IContentFieldHandler.DraftSavingAsync(SaveDraftContentFieldContext context, ContentField field) { - return field is TField tfield - ? DraftSavingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? DraftSavingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.DraftSavedAsync(SaveDraftContentFieldContext context, ContentField field) { - return field is TField tfield - ? DraftSavedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? DraftSavedAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.PublishingAsync(PublishContentFieldContext context, ContentField field) { - return field is TField tfield - ? PublishingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? PublishingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.PublishedAsync(PublishContentFieldContext context, ContentField field) { - return field is TField tfield - ? PublishedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? PublishedAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.UnpublishingAsync(PublishContentFieldContext context, ContentField field) { - return field is TField tfield - ? UnpublishingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? UnpublishingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.UnpublishedAsync(PublishContentFieldContext context, ContentField field) { - return field is TField tfield - ? UnpublishedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? UnpublishedAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.RemovingAsync(RemoveContentFieldContext context, ContentField field) { - return field is TField tfield - ? RemovingAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? RemovingAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.RemovedAsync(RemoveContentFieldContext context, ContentField field) { - return field is TField tfield - ? RemovedAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? RemovedAsync(context, tfield) : Task.CompletedTask; } Task IContentFieldHandler.GetContentItemAspectAsync(ContentItemAspectContext context, ContentField field) { - return field is TField tfield - ? GetContentItemAspectAsync(context, tfield) - : Task.CompletedTask; + return field is TField tfield ? GetContentItemAspectAsync(context, tfield) : Task.CompletedTask; } + async Task IContentFieldHandler.CloningAsync(CloneContentFieldContext context, ContentField field) { if (field is TField tfield) @@ -194,30 +147,56 @@ async Task IContentFieldHandler.ClonedAsync(CloneContentFieldContext context, Co } public virtual Task ActivatedAsync(ActivatedContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task ActivatingAsync(ActivatingContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task InitializingAsync(InitializingContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task InitializedAsync(InitializingContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task CreatingAsync(CreateContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task CreatedAsync(CreateContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task LoadingAsync(LoadContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task LoadedAsync(LoadContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task ImportingAsync(ImportContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task ImportedAsync(ImportContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task UpdatingAsync(UpdateContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task UpdatedAsync(UpdateContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task ValidatingAsync(ValidateContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task ValidatedAsync(ValidateContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task VersioningAsync(VersionContentFieldContext context, TField existing, TField building) => Task.CompletedTask; + public virtual Task VersionedAsync(VersionContentFieldContext context, TField existing, TField building) => Task.CompletedTask; + public virtual Task DraftSavingAsync(SaveDraftContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task DraftSavedAsync(SaveDraftContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task PublishingAsync(PublishContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task PublishedAsync(PublishContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task UnpublishingAsync(PublishContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task UnpublishedAsync(PublishContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task RemovingAsync(RemoveContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task RemovedAsync(RemoveContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task GetContentItemAspectAsync(ContentItemAspectContext context, TField field) => Task.CompletedTask; + public virtual Task CloningAsync(CloneContentFieldContext context, TField field) => Task.CompletedTask; + public virtual Task ClonedAsync(CloneContentFieldContext context, TField field) => Task.CompletedTask; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentHandlerBase.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentHandlerBase.cs index 73a468bec4f..ec65a6e9f35 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentHandlerBase.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentHandlerBase.cs @@ -28,6 +28,7 @@ public virtual Task CreatingAsync(CreateContentContext context) { return Task.CompletedTask; } + public virtual Task CreatedAsync(CreateContentContext context) { return Task.CompletedTask; @@ -137,6 +138,7 @@ public virtual Task CloningAsync(CloneContentContext context) { return Task.CompletedTask; } + public virtual Task ClonedAsync(CloneContentContext context) { return Task.CompletedTask; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentItemAspectContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentItemAspectContext.cs index 2ac802a6000..b629dc1f3ce 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentItemAspectContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentItemAspectContext.cs @@ -11,7 +11,8 @@ public class ContentItemAspectContext /// /// Provides a value for a specific aspect type. /// - public async Task ForAsync(Func action) where TAspect : class + public async Task ForAsync(Func action) + where TAspect : class { var aspect = Aspect as TAspect; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentPartHandler.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentPartHandler.cs index 34f14333ace..75b305a36a2 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentPartHandler.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentPartHandler.cs @@ -2,89 +2,67 @@ namespace OrchardCore.ContentManagement.Handlers { - public abstract class ContentPartHandler : IContentPartHandler where TPart : ContentPart, new() + public abstract class ContentPartHandler : IContentPartHandler + where TPart : ContentPart, new() { Task IContentPartHandler.ActivatedAsync(ActivatedContentContext context, ContentPart part) { - return part is TPart tpart - ? ActivatedAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? ActivatedAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.ActivatingAsync(ActivatingContentContext context, ContentPart part) { - return part is TPart tpart - ? ActivatingAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? ActivatingAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.InitializingAsync(InitializingContentContext context, ContentPart part) { - return part is TPart tpart - ? InitializingAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? InitializingAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.InitializedAsync(InitializingContentContext context, ContentPart part) { - return part is TPart tpart - ? InitializedAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? InitializedAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.CreatingAsync(CreateContentContext context, ContentPart part) { - return part is TPart tpart - ? CreatingAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? CreatingAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.CreatedAsync(CreateContentContext context, ContentPart part) { - return part is TPart tpart - ? CreatedAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? CreatedAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.LoadingAsync(LoadContentContext context, ContentPart part) { - return part is TPart tpart - ? LoadingAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? LoadingAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.LoadedAsync(LoadContentContext context, ContentPart part) { - return part is TPart tpart - ? LoadedAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? LoadedAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.ImportingAsync(ImportContentContext context, ContentPart part) { - return part is TPart tpart - ? ImportingAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? ImportingAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.ImportedAsync(ImportContentContext context, ContentPart part) { - return part is TPart tpart - ? ImportedAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? ImportedAsync(context, tpart) : Task.CompletedTask; } + Task IContentPartHandler.UpdatingAsync(UpdateContentContext context, ContentPart part) { - return part is TPart tpart - ? UpdatingAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? UpdatingAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.UpdatedAsync(UpdateContentContext context, ContentPart part) { - return part is TPart tpart - ? UpdatedAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? UpdatedAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.ValidatingAsync(ValidateContentContext context, ContentPart part) @@ -119,80 +97,59 @@ Task IContentPartHandler.ValidatedAsync(ValidateContentContext context, ContentP Task IContentPartHandler.VersioningAsync(VersionContentContext context, ContentPart existing, ContentPart building) { - return existing is TPart texisting && building is TPart tbuilding - ? VersioningAsync(context, texisting, tbuilding) - : Task.CompletedTask; + return existing is TPart texisting && building is TPart tbuilding ? VersioningAsync(context, texisting, tbuilding) : Task.CompletedTask; } Task IContentPartHandler.VersionedAsync(VersionContentContext context, ContentPart existing, ContentPart building) { - return existing is TPart texisting && building is TPart tbuilding - ? VersionedAsync(context, texisting, tbuilding) - : Task.CompletedTask; + return existing is TPart texisting && building is TPart tbuilding ? VersionedAsync(context, texisting, tbuilding) : Task.CompletedTask; } Task IContentPartHandler.DraftSavingAsync(SaveDraftContentContext context, ContentPart part) { - return part is TPart tpart - ? DraftSavingAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? DraftSavingAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.DraftSavedAsync(SaveDraftContentContext context, ContentPart part) { - return part is TPart tpart - ? DraftSavedAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? DraftSavedAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.PublishingAsync(PublishContentContext context, ContentPart part) { - return part is TPart tpart - ? PublishingAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? PublishingAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.PublishedAsync(PublishContentContext context, ContentPart part) { - return part is TPart tpart - ? PublishedAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? PublishedAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.UnpublishingAsync(PublishContentContext context, ContentPart part) { - return part is TPart tpart - ? UnpublishingAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? UnpublishingAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.UnpublishedAsync(PublishContentContext context, ContentPart part) { - return part is TPart tpart - ? UnpublishedAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? UnpublishedAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.RemovingAsync(RemoveContentContext context, ContentPart part) { - return part is TPart tpart - ? RemovingAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? RemovingAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.RemovedAsync(RemoveContentContext context, ContentPart part) { - return part is TPart tpart - ? RemovedAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? RemovedAsync(context, tpart) : Task.CompletedTask; } Task IContentPartHandler.GetContentItemAspectAsync(ContentItemAspectContext context, ContentPart part) { - return part is TPart tpart - ? GetContentItemAspectAsync(context, tpart) - : Task.CompletedTask; + return part is TPart tpart ? GetContentItemAspectAsync(context, tpart) : Task.CompletedTask; } + async Task IContentPartHandler.CloningAsync(CloneContentContext context, ContentPart part) { if (part is TPart tpart) @@ -210,37 +167,61 @@ async Task IContentPartHandler.ClonedAsync(CloneContentContext context, ContentP } public virtual Task ActivatedAsync(ActivatedContentContext context, TPart part) => Task.CompletedTask; + public virtual Task ActivatingAsync(ActivatingContentContext context, TPart part) => Task.CompletedTask; + public virtual Task InitializingAsync(InitializingContentContext context, TPart part) => Task.CompletedTask; + public virtual Task InitializedAsync(InitializingContentContext context, TPart part) => Task.CompletedTask; + public virtual Task CreatingAsync(CreateContentContext context, TPart part) => Task.CompletedTask; + public virtual Task CreatedAsync(CreateContentContext context, TPart part) => Task.CompletedTask; + public virtual Task LoadingAsync(LoadContentContext context, TPart part) => Task.CompletedTask; + public virtual Task LoadedAsync(LoadContentContext context, TPart part) => Task.CompletedTask; + public virtual Task ImportingAsync(ImportContentContext context, TPart part) => Task.CompletedTask; + public virtual Task ImportedAsync(ImportContentContext context, TPart part) => Task.CompletedTask; + public virtual Task UpdatingAsync(UpdateContentContext context, TPart part) => Task.CompletedTask; + public virtual Task UpdatedAsync(UpdateContentContext context, TPart part) => Task.CompletedTask; + public virtual Task ValidatingAsync(ValidateContentContext context, TPart part) => Task.CompletedTask; + public virtual Task ValidatedAsync(ValidateContentContext context, TPart part) => Task.CompletedTask; + public virtual Task VersioningAsync(VersionContentContext context, TPart existing, TPart building) => Task.CompletedTask; + public virtual Task VersionedAsync(VersionContentContext context, TPart existing, TPart building) => Task.CompletedTask; + public virtual Task DraftSavingAsync(SaveDraftContentContext context, TPart part) => Task.CompletedTask; + public virtual Task DraftSavedAsync(SaveDraftContentContext context, TPart part) => Task.CompletedTask; + public virtual Task PublishingAsync(PublishContentContext context, TPart part) => Task.CompletedTask; + public virtual Task PublishedAsync(PublishContentContext context, TPart part) => Task.CompletedTask; + public virtual Task UnpublishingAsync(PublishContentContext context, TPart part) => Task.CompletedTask; + public virtual Task UnpublishedAsync(PublishContentContext context, TPart part) => Task.CompletedTask; + public virtual Task RemovingAsync(RemoveContentContext context, TPart part) => Task.CompletedTask; + public virtual Task RemovedAsync(RemoveContentContext context, TPart part) => Task.CompletedTask; + public virtual Task GetContentItemAspectAsync(ContentItemAspectContext context, TPart part) => Task.CompletedTask; + public virtual Task CloningAsync(CloneContentContext context, TPart part) => Task.CompletedTask; + public virtual Task ClonedAsync(CloneContentContext context, TPart part) => Task.CompletedTask; - protected virtual Task ValidatingAsync(ValidateContentPartContext context, TPart part) - => ValidatingAsync(context as ValidateContentContext, part); + protected virtual Task ValidatingAsync(ValidateContentPartContext context, TPart part) => ValidatingAsync(context as ValidateContentContext, part); - protected virtual Task ValidatedAsync(ValidateContentPartContext context, TPart part) - => ValidatedAsync(context as ValidateContentContext, part); + protected virtual Task ValidatedAsync(ValidateContentPartContext context, TPart part) => ValidatedAsync(context as ValidateContentContext, part); } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentValidateResult.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentValidateResult.cs index 59d25091d87..ce27894b169 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentValidateResult.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentValidateResult.cs @@ -19,6 +19,5 @@ public void Fail(ValidationResult error) Succeeded = false; _errors.Add(error); } - } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/CreateContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/CreateContentContext.cs index e3996726111..6bf97153a15 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/CreateContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/CreateContentContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.ContentManagement.Handlers { public class CreateContentContext : ContentContextBase { - public CreateContentContext(ContentItem contentItem) : base(contentItem) - { - } + public CreateContentContext(ContentItem contentItem) + : base(contentItem) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ActivatedContentFieldContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ActivatedContentFieldContext.cs index cc55cef1931..50b9f75b491 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ActivatedContentFieldContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ActivatedContentFieldContext.cs @@ -3,7 +3,5 @@ namespace OrchardCore.ContentManagement.Handlers; public class ActivatedContentFieldContext : ContentFieldContextBase { public ActivatedContentFieldContext(ContentItem contentItem) - : base(contentItem) - { - } + : base(contentItem) { } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ActivatingContentFieldContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ActivatingContentFieldContext.cs index 9f579e7ff63..7ceae3f2d33 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ActivatingContentFieldContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ActivatingContentFieldContext.cs @@ -3,7 +3,5 @@ namespace OrchardCore.ContentManagement.Handlers; public class ActivatingContentFieldContext : ContentFieldContextBase { public ActivatingContentFieldContext(ContentItem contentItem) - : base(contentItem) - { - } + : base(contentItem) { } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/CreateContentFieldContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/CreateContentFieldContext.cs index 63232498987..dd2a0ecfceb 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/CreateContentFieldContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/CreateContentFieldContext.cs @@ -3,7 +3,5 @@ namespace OrchardCore.ContentManagement.Handlers; public class CreateContentFieldContext : ContentFieldContextBase { public CreateContentFieldContext(ContentItem contentItem) - : base(contentItem) - { - } + : base(contentItem) { } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/InitializingContentFieldContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/InitializingContentFieldContext.cs index e2f54dee7b6..b06bc1cd76f 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/InitializingContentFieldContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/InitializingContentFieldContext.cs @@ -3,7 +3,5 @@ namespace OrchardCore.ContentManagement.Handlers; public class InitializingContentFieldContext : ContentFieldContextBase { public InitializingContentFieldContext(ContentItem contentItem) - : base(contentItem) - { - } + : base(contentItem) { } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/LoadContentFieldContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/LoadContentFieldContext.cs index bceaaf00ae9..8991dfa27c8 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/LoadContentFieldContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/LoadContentFieldContext.cs @@ -3,7 +3,5 @@ namespace OrchardCore.ContentManagement.Handlers; public class LoadContentFieldContext : ContentFieldContextBase { public LoadContentFieldContext(ContentItem contentItem) - : base(contentItem) - { - } + : base(contentItem) { } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/RestoreContentFieldContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/RestoreContentFieldContext.cs index 05cde20b433..aefe6cfec12 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/RestoreContentFieldContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/RestoreContentFieldContext.cs @@ -3,7 +3,5 @@ namespace OrchardCore.ContentManagement.Handlers; public class RestoreContentFieldContext : ContentFieldContextBase { public RestoreContentFieldContext(ContentItem contentItem) - : base(contentItem) - { - } + : base(contentItem) { } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/SaveDraftContentFieldContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/SaveDraftContentFieldContext.cs index a4b2e017a9c..434ba52c16d 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/SaveDraftContentFieldContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/SaveDraftContentFieldContext.cs @@ -3,7 +3,5 @@ namespace OrchardCore.ContentManagement.Handlers; public class SaveDraftContentFieldContext : ContentFieldContextBase { public SaveDraftContentFieldContext(ContentItem contentItem) - : base(contentItem) - { - } + : base(contentItem) { } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/UpdateContentFieldContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/UpdateContentFieldContext.cs index 91c754addf1..1bcca5a77da 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/UpdateContentFieldContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/UpdateContentFieldContext.cs @@ -2,7 +2,8 @@ namespace OrchardCore.ContentManagement.Handlers; public class UpdateContentFieldContext : ContentFieldContextBase { - public UpdateContentFieldContext(ContentItem contentItem) : base(contentItem) + public UpdateContentFieldContext(ContentItem contentItem) + : base(contentItem) { UpdatingItem = contentItem; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ValidateContentFieldContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ValidateContentFieldContext.cs index 733bc2cbde7..40b7e2170c3 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ValidateContentFieldContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Fields/ValidateContentFieldContext.cs @@ -4,11 +4,8 @@ namespace OrchardCore.ContentManagement.Handlers; public class ValidateContentFieldContext : ContentFieldContextBase { - public ValidateContentFieldContext( - ContentItem contentItem) - : base(contentItem) - { - } + public ValidateContentFieldContext(ContentItem contentItem) + : base(contentItem) { } public ContentValidateResult ContentValidateResult { get; } = new ContentValidateResult(); } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ImportContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ImportContentContext.cs index a3f72406510..9fc698f4322 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ImportContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ImportContentContext.cs @@ -7,7 +7,8 @@ public class ImportContentContext : ContentContextBase /// public ContentItem OriginalContentItem { get; set; } - public ImportContentContext(ContentItem contentItem, ContentItem originalContentItem = null) : base(contentItem) + public ImportContentContext(ContentItem contentItem, ContentItem originalContentItem = null) + : base(contentItem) { OriginalContentItem = originalContentItem; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/InitializingContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/InitializingContentContext.cs index bece48c4305..53ba3899a4b 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/InitializingContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/InitializingContentContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.ContentManagement.Handlers { public class InitializingContentContext : ContentContextBase { - public InitializingContentContext(ContentItem contentItem) : base(contentItem) - { - } + public InitializingContentContext(ContentItem contentItem) + : base(contentItem) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/LoadContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/LoadContentContext.cs index f9147e3570c..7dd8bdc7cb5 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/LoadContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/LoadContentContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.ContentManagement.Handlers { public class LoadContentContext : ContentContextBase { - public LoadContentContext(ContentItem contentItem) : base(contentItem) - { - } + public LoadContentContext(ContentItem contentItem) + : base(contentItem) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Parts/ValidateContentPartContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Parts/ValidateContentPartContext.cs index 4e294f117c8..96bd4481ba5 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Parts/ValidateContentPartContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Parts/ValidateContentPartContext.cs @@ -6,9 +6,7 @@ namespace OrchardCore.ContentManagement.Handlers; public class ValidateContentPartContext : ValidateContentContext { public ValidateContentPartContext(ContentItem contentItem) - : base(contentItem) - { - } + : base(contentItem) { } public ContentTypePartDefinition ContentTypePartDefinition { get; set; } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/PublishContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/PublishContentContext.cs index 88a94aa3630..9d26244f9ff 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/PublishContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/PublishContentContext.cs @@ -2,7 +2,8 @@ namespace OrchardCore.ContentManagement.Handlers { public class PublishContentContext : ContentContextBase { - public PublishContentContext(ContentItem contentItem, ContentItem previousContentItem) : base(contentItem) + public PublishContentContext(ContentItem contentItem, ContentItem previousContentItem) + : base(contentItem) { PublishingItem = contentItem; PreviousItem = previousContentItem; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/RemoveContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/RemoveContentContext.cs index 6acd327047c..eb0d9701b3b 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/RemoveContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/RemoveContentContext.cs @@ -2,7 +2,8 @@ namespace OrchardCore.ContentManagement.Handlers { public class RemoveContentContext : ContentContextBase { - public RemoveContentContext(ContentItem contentItem, bool noActiveVersionLeft = false) : base(contentItem) + public RemoveContentContext(ContentItem contentItem, bool noActiveVersionLeft = false) + : base(contentItem) { NoActiveVersionLeft = noActiveVersionLeft; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/RestoreContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/RestoreContentContext.cs index d92f3e0b4ab..76fb2127256 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/RestoreContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/RestoreContentContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.ContentManagement.Handlers { public class RestoreContentContext : ContentContextBase { - public RestoreContentContext(ContentItem contentItem) : base(contentItem) - { - } + public RestoreContentContext(ContentItem contentItem) + : base(contentItem) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/SaveDraftContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/SaveDraftContentContext.cs index a77a1f3505d..f440b96c9ba 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/SaveDraftContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/SaveDraftContentContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.ContentManagement.Handlers { public class SaveDraftContentContext : ContentContextBase { - public SaveDraftContentContext(ContentItem contentItem) : base(contentItem) - { - } + public SaveDraftContentContext(ContentItem contentItem) + : base(contentItem) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/UpdateContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/UpdateContentContext.cs index 597e9935bec..2a675064112 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/UpdateContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/UpdateContentContext.cs @@ -2,7 +2,8 @@ namespace OrchardCore.ContentManagement.Handlers { public class UpdateContentContext : ContentContextBase { - public UpdateContentContext(ContentItem contentItem) : base(contentItem) + public UpdateContentContext(ContentItem contentItem) + : base(contentItem) { UpdatingItem = contentItem; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ValidateContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ValidateContentContext.cs index bbd08e9aec5..cf3828f3131 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ValidateContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ValidateContentContext.cs @@ -4,9 +4,8 @@ namespace OrchardCore.ContentManagement.Handlers { public class ValidateContentContext : ContentContextBase { - public ValidateContentContext(ContentItem contentItem) : base(contentItem) - { - } + public ValidateContentContext(ContentItem contentItem) + : base(contentItem) { } public ContentValidateResult ContentValidateResult { get; } = new ContentValidateResult(); } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/VersionContentContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/VersionContentContext.cs index 7bffba77f01..7b0d2470245 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/VersionContentContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/VersionContentContext.cs @@ -2,7 +2,8 @@ namespace OrchardCore.ContentManagement.Handlers { public class VersionContentContext : ContentContextBase { - public VersionContentContext(ContentItem contentItem, ContentItem buildingContentItem) : base(contentItem) + public VersionContentContext(ContentItem contentItem, ContentItem buildingContentItem) + : base(contentItem) { BuildingContentItem = buildingContentItem; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/IContentDefinitionManager.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/IContentDefinitionManager.cs index 1e42ca9873e..6ed4399a1cb 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/IContentDefinitionManager.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/IContentDefinitionManager.cs @@ -42,50 +42,38 @@ public interface IContentDefinitionManager Task GetIdentifierAsync(); [Obsolete($"Instead, utilize the {nameof(LoadTypeDefinitionsAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable LoadTypeDefinitions() - => LoadTypeDefinitionsAsync().GetAwaiter().GetResult(); + IEnumerable LoadTypeDefinitions() => LoadTypeDefinitionsAsync().GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(ListTypeDefinitionsAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable ListTypeDefinitions() - => ListTypeDefinitionsAsync().GetAwaiter().GetResult(); + IEnumerable ListTypeDefinitions() => ListTypeDefinitionsAsync().GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(LoadPartDefinitionsAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable LoadPartDefinitions() - => LoadPartDefinitionsAsync().GetAwaiter().GetResult(); + IEnumerable LoadPartDefinitions() => LoadPartDefinitionsAsync().GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(ListPartDefinitionsAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable ListPartDefinitions() - => ListPartDefinitionsAsync().GetAwaiter().GetResult(); + IEnumerable ListPartDefinitions() => ListPartDefinitionsAsync().GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(LoadTypeDefinitionAsync)} method. This current method is slated for removal in upcoming releases.")] - ContentTypeDefinition LoadTypeDefinition(string name) - => LoadTypeDefinitionAsync(name).GetAwaiter().GetResult(); + ContentTypeDefinition LoadTypeDefinition(string name) => LoadTypeDefinitionAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(GetTypeDefinitionAsync)} method. This current method is slated for removal in upcoming releases.")] - ContentTypeDefinition GetTypeDefinition(string name) - => GetTypeDefinitionAsync(name).GetAwaiter().GetResult(); + ContentTypeDefinition GetTypeDefinition(string name) => GetTypeDefinitionAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(LoadPartDefinitionAsync)} method. This current method is slated for removal in upcoming releases.")] - ContentPartDefinition LoadPartDefinition(string name) - => LoadPartDefinitionAsync(name).GetAwaiter().GetResult(); + ContentPartDefinition LoadPartDefinition(string name) => LoadPartDefinitionAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(GetPartDefinitionAsync)} method. This current method is slated for removal in upcoming releases.")] - ContentPartDefinition GetPartDefinition(string name) - => GetPartDefinitionAsync(name).GetAwaiter().GetResult(); + ContentPartDefinition GetPartDefinition(string name) => GetPartDefinitionAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(DeleteTypeDefinitionAsync)} method. This current method is slated for removal in upcoming releases.")] - void DeleteTypeDefinition(string name) - => DeleteTypeDefinitionAsync(name).GetAwaiter().GetResult(); + void DeleteTypeDefinition(string name) => DeleteTypeDefinitionAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(DeletePartDefinitionAsync)} method. This current method is slated for removal in upcoming releases.")] - void DeletePartDefinition(string name) - => DeletePartDefinitionAsync(name).GetAwaiter().GetResult(); + void DeletePartDefinition(string name) => DeletePartDefinitionAsync(name).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(StoreTypeDefinitionAsync)} method. This current method is slated for removal in upcoming releases.")] - void StoreTypeDefinition(ContentTypeDefinition contentTypeDefinition) - => StoreTypeDefinitionAsync(contentTypeDefinition).GetAwaiter().GetResult(); + void StoreTypeDefinition(ContentTypeDefinition contentTypeDefinition) => StoreTypeDefinitionAsync(contentTypeDefinition).GetAwaiter().GetResult(); [Obsolete($"Instead, utilize the {nameof(StorePartDefinitionAsync)} method. This current method is slated for removal in upcoming releases.")] - void StorePartDefinition(ContentPartDefinition contentPartDefinition) - => StorePartDefinitionAsync(contentPartDefinition).GetAwaiter().GetResult(); + void StorePartDefinition(ContentPartDefinition contentPartDefinition) => StorePartDefinitionAsync(contentPartDefinition).GetAwaiter().GetResult(); } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/IContentManager.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/IContentManager.cs index 395f2d9afec..c4f1deb23e3 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/IContentManager.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/IContentManager.cs @@ -34,7 +34,6 @@ public interface IContentManager /// The version to create the item with. Task CreateAsync(ContentItem contentItem, VersionOptions options); - /// /// Creates (puts) a new content item and manages removing and updating existing published or draft items. /// @@ -161,7 +160,8 @@ public static Task CreateAsync(this IContentManager contentManager, ContentItem return contentManager.CreateAsync(contentItem, VersionOptions.Published); } - public static Task PopulateAspectAsync(this IContentManager contentManager, IContent content) where TAspect : new() + public static Task PopulateAspectAsync(this IContentManager contentManager, IContent content) + where TAspect : new() { return contentManager.PopulateAspectAsync(content, new TAspect()); } @@ -215,7 +215,7 @@ public static async Task UpdateValidateAndCreateAsync(thi } /// - /// Gets either the published container content item with the specified id, or if the json path supplied gets the contained content item. + /// Gets either the published container content item with the specified id, or if the json path supplied gets the contained content item. /// /// The instance. /// The content item id to load. @@ -254,27 +254,42 @@ public class VersionOptions /// /// Gets the latest version. /// - public static VersionOptions Latest { get { return new VersionOptions { IsLatest = true }; } } + public static VersionOptions Latest + { + get { return new VersionOptions { IsLatest = true }; } + } /// /// Gets the latest published version. /// - public static VersionOptions Published { get { return new VersionOptions { IsPublished = true }; } } + public static VersionOptions Published + { + get { return new VersionOptions { IsPublished = true }; } + } /// /// Gets the latest draft version. /// - public static VersionOptions Draft { get { return new VersionOptions { IsDraft = true }; } } + public static VersionOptions Draft + { + get { return new VersionOptions { IsDraft = true }; } + } /// /// Gets the latest version and creates a new version draft based on it. /// - public static VersionOptions DraftRequired { get { return new VersionOptions { IsDraft = true, IsDraftRequired = true }; } } + public static VersionOptions DraftRequired + { + get { return new VersionOptions { IsDraft = true, IsDraftRequired = true }; } + } /// /// Gets all versions. /// - public static VersionOptions AllVersions { get { return new VersionOptions { IsAllVersions = true }; } } + public static VersionOptions AllVersions + { + get { return new VersionOptions { IsAllVersions = true }; } + } public bool IsLatest { get; private set; } public bool IsPublished { get; private set; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentBuilderSettings.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentBuilderSettings.cs index 9ba0085316a..7697631bdd9 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentBuilderSettings.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentBuilderSettings.cs @@ -9,21 +9,19 @@ public static class ContentBuilderSettings /// /// Replace current value, even for null values, union arrays. /// - public static readonly JsonMergeSettings JsonMergeSettings = new() - { - MergeArrayHandling = MergeArrayHandling.Union, - MergeNullValueHandling = MergeNullValueHandling.Merge, - }; + public static readonly JsonMergeSettings JsonMergeSettings = + new() { MergeArrayHandling = MergeArrayHandling.Union, MergeNullValueHandling = MergeNullValueHandling.Merge, }; /// /// A Json serializer that ignores properties which have their default values. /// To be able to have a default value : use [DefaultValue(true)] on a class property for example. /// - public static readonly JsonSerializerOptions IgnoreDefaultValuesSerializer = new() - { - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - ReferenceHandler = ReferenceHandler.IgnoreCycles, - PropertyNameCaseInsensitive = true, - }; + public static readonly JsonSerializerOptions IgnoreDefaultValuesSerializer = + new() + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + ReferenceHandler = ReferenceHandler.IgnoreCycles, + PropertyNameCaseInsensitive = true, + }; } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentPartDefinitionBuilder.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentPartDefinitionBuilder.cs index aad503c3da1..c51eefc3b30 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentPartDefinitionBuilder.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentPartDefinitionBuilder.cs @@ -18,9 +18,7 @@ public class ContentPartDefinitionBuilder public ContentPartDefinition Current { get; private set; } public ContentPartDefinitionBuilder() - : this(new ContentPartDefinition(null)) - { - } + : this(new ContentPartDefinition(null)) { } public ContentPartDefinitionBuilder(ContentPartDefinition existing) { @@ -84,7 +82,8 @@ public ContentPartDefinitionBuilder MergeSettings(JsonObject settings) return this; } - public ContentPartDefinitionBuilder MergeSettings(Action setting) where T : class, new() + public ContentPartDefinitionBuilder MergeSettings(Action setting) + where T : class, new() { var existingJObject = _settings[typeof(T).Name] as JsonObject; // If existing settings do not exist, create. @@ -111,8 +110,7 @@ public ContentPartDefinitionBuilder WithSettings(T settings) return this; } - public ContentPartDefinitionBuilder WithField(string fieldName) - => WithField(fieldName, configuration => { }); + public ContentPartDefinitionBuilder WithField(string fieldName) => WithField(fieldName, configuration => { }); public ContentPartDefinitionBuilder WithField(string fieldName, Action configuration) { @@ -153,24 +151,29 @@ public ContentPartDefinitionBuilder WithField(string fieldName, Action(string fieldName) - => WithField(fieldName, configuration => configuration.OfType(typeof(TField).Name)); + public ContentPartDefinitionBuilder WithField(string fieldName) => WithField(fieldName, configuration => configuration.OfType(typeof(TField).Name)); - public ContentPartDefinitionBuilder WithField(string fieldName, Action configuration) - => WithField(fieldName, field => - { - configuration(field); + public ContentPartDefinitionBuilder WithField(string fieldName, Action configuration) => + WithField( + fieldName, + field => + { + configuration(field); - field.OfType(typeof(TField).Name); - }); + field.OfType(typeof(TField).Name); + } + ); - public Task WithFieldAsync(string fieldName, Func configuration) - => WithFieldAsync(fieldName, async field => - { - await configuration(field); + public Task WithFieldAsync(string fieldName, Func configuration) => + WithFieldAsync( + fieldName, + async field => + { + await configuration(field); - field.OfType(typeof(TField).Name); - }); + field.OfType(typeof(TField).Name); + } + ); public async Task WithFieldAsync(string fieldName, Func configurationAsync) { @@ -240,15 +243,11 @@ public override ContentPartFieldDefinition Build() return new ContentPartFieldDefinition(_fieldDefinition, _fieldName, _settings); } - public override string Name - => _fieldName; - - public override string FieldType - => _fieldDefinition.Name; + public override string Name => _fieldName; + public override string FieldType => _fieldDefinition.Name; - public override string PartName - => _partDefinition.Name; + public override string PartName => _partDefinition.Name; public override ContentPartFieldDefinitionBuilder OfType(ContentFieldDefinition fieldDefinition) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentPartFieldDefinitionBuilder.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentPartFieldDefinitionBuilder.cs index 1a00252f85d..e102e21ec7f 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentPartFieldDefinitionBuilder.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentPartFieldDefinitionBuilder.cs @@ -40,7 +40,8 @@ public ContentPartFieldDefinitionBuilder MergeSettings(JsonObject settings) return this; } - public ContentPartFieldDefinitionBuilder MergeSettings(Action setting) where T : class, new() + public ContentPartFieldDefinitionBuilder MergeSettings(Action setting) + where T : class, new() { var existingJObject = _settings[typeof(T).Name] as JsonObject; // If existing settings do not exist, create. diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypeDefinitionBuilder.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypeDefinitionBuilder.cs index 7d4db8f2801..49700f220da 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypeDefinitionBuilder.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypeDefinitionBuilder.cs @@ -18,9 +18,7 @@ public class ContentTypeDefinitionBuilder public ContentTypeDefinition Current { get; } public ContentTypeDefinitionBuilder() - : this(new ContentTypeDefinition(null, null)) - { - } + : this(new ContentTypeDefinition(null, null)) { } public ContentTypeDefinitionBuilder(ContentTypeDefinition existing) { @@ -83,7 +81,8 @@ public ContentTypeDefinitionBuilder MergeSettings(JsonObject settings) return this; } - public ContentTypeDefinitionBuilder MergeSettings(Action setting) where T : class, new() + public ContentTypeDefinitionBuilder MergeSettings(Action setting) + where T : class, new() { var existingJObject = _settings[typeof(T).Name] as JsonObject; // If existing settings do not exist, create. @@ -119,14 +118,12 @@ public ContentTypeDefinitionBuilder RemovePart(string partName) return this; } - public ContentTypeDefinitionBuilder WithPart(string partName) - => WithPart(partName, configuration => { }); + public ContentTypeDefinitionBuilder WithPart(string partName) => WithPart(partName, configuration => { }); - public ContentTypeDefinitionBuilder WithPart(string name, string partName) - => WithPart(name, new ContentPartDefinition(partName), configuration => { }); + public ContentTypeDefinitionBuilder WithPart(string name, string partName) => WithPart(name, new ContentPartDefinition(partName), configuration => { }); - public ContentTypeDefinitionBuilder WithPart(string partName, Action configuration) - => WithPart(partName, new ContentPartDefinition(partName), configuration); + public ContentTypeDefinitionBuilder WithPart(string partName, Action configuration) => + WithPart(partName, new ContentPartDefinition(partName), configuration); public ContentTypeDefinitionBuilder WithPart(string name, ContentPartDefinition partDefinition, Action configuration) { @@ -137,10 +134,7 @@ public ContentTypeDefinitionBuilder WithPart(string name, ContentPartDefinition } else { - existingPart = new ContentTypePartDefinition(name, partDefinition, []) - { - ContentTypeDefinition = Current, - }; + existingPart = new ContentTypePartDefinition(name, partDefinition, []) { ContentTypeDefinition = Current, }; } var configurer = new PartConfigurerImpl(existingPart); @@ -149,25 +143,29 @@ public ContentTypeDefinitionBuilder WithPart(string name, ContentPartDefinition return this; } - public ContentTypeDefinitionBuilder WithPart(string name, string partName, Action configuration) - => WithPart(name, new ContentPartDefinition(partName), configuration); + public ContentTypeDefinitionBuilder WithPart(string name, string partName, Action configuration) => + WithPart(name, new ContentPartDefinition(partName), configuration); - public ContentTypeDefinitionBuilder WithPart() where TPart : ContentPart - => WithPart(typeof(TPart).Name, configuration => { }); + public ContentTypeDefinitionBuilder WithPart() + where TPart : ContentPart => WithPart(typeof(TPart).Name, configuration => { }); - public ContentTypeDefinitionBuilder WithPart(string name) where TPart : ContentPart - => WithPart(name, new ContentPartDefinition(typeof(TPart).Name), configuration => { }); + public ContentTypeDefinitionBuilder WithPart(string name) + where TPart : ContentPart => WithPart(name, new ContentPartDefinition(typeof(TPart).Name), configuration => { }); - public ContentTypeDefinitionBuilder WithPart(string name, Action configuration) where TPart : ContentPart - => WithPart(name, new ContentPartDefinition(typeof(TPart).Name), configuration); + public ContentTypeDefinitionBuilder WithPart(string name, Action configuration) + where TPart : ContentPart => WithPart(name, new ContentPartDefinition(typeof(TPart).Name), configuration); - public Task WithPartAsync(string name, string partName, Func configurationAsync) - => WithPartAsync(name, new ContentPartDefinition(partName), configurationAsync); + public Task WithPartAsync(string name, string partName, Func configurationAsync) => + WithPartAsync(name, new ContentPartDefinition(partName), configurationAsync); - public Task WithPartAsync(string partName, Func configurationAsync) - => WithPartAsync(partName, new ContentPartDefinition(partName), configurationAsync); + public Task WithPartAsync(string partName, Func configurationAsync) => + WithPartAsync(partName, new ContentPartDefinition(partName), configurationAsync); - public async Task WithPartAsync(string name, ContentPartDefinition partDefinition, Func configurationAsync) + public async Task WithPartAsync( + string name, + ContentPartDefinition partDefinition, + Func configurationAsync + ) { var existingPart = _parts.FirstOrDefault(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)); @@ -177,10 +175,7 @@ public async Task WithPartAsync(string name, Conte } else { - existingPart = new ContentTypePartDefinition(name, partDefinition, []) - { - ContentTypeDefinition = Current, - }; + existingPart = new ContentTypePartDefinition(name, partDefinition, []) { ContentTypeDefinition = Current, }; } var configurer = new PartConfigurerImpl(existingPart); @@ -215,10 +210,7 @@ public override ContentTypePartDefinition Build() throw new ArgumentException("Content part name contains invalid characters", "name"); } - return new ContentTypePartDefinition(Current.Name, _partDefinition, _settings) - { - ContentTypeDefinition = Current.ContentTypeDefinition, - }; + return new ContentTypePartDefinition(Current.Name, _partDefinition, _settings) { ContentTypeDefinition = Current.ContentTypeDefinition, }; } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypePartDefinitionBuilder.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypePartDefinitionBuilder.cs index 94c201e2b98..e72f43a61bf 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypePartDefinitionBuilder.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypePartDefinitionBuilder.cs @@ -52,7 +52,8 @@ public ContentTypePartDefinitionBuilder MergeSettings(JsonObject settings) return this; } - public ContentTypePartDefinitionBuilder MergeSettings(Action setting) where T : class, new() + public ContentTypePartDefinitionBuilder MergeSettings(Action setting) + where T : class, new() { var existingJObject = _settings[typeof(T).Name] as JsonObject; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentDefinition.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentDefinition.cs index 4474af4c02b..8bfb6585259 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentDefinition.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentDefinition.cs @@ -15,7 +15,8 @@ public abstract class ContentDefinition /// public JsonObject Settings { get; protected set; } - public T GetSettings() where T : new() + public T GetSettings() + where T : new() { if (Settings == null) { @@ -38,10 +39,7 @@ public abstract class ContentDefinition result = new T(); } - namedSettings = new Dictionary(_namedSettings) - { - [typeof(T)] = result, - }; + namedSettings = new Dictionary(_namedSettings) { [typeof(T)] = result, }; _namedSettings = namedSettings; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentPartFieldDefinitionExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentPartFieldDefinitionExtensions.cs index efeced01a83..5b7b95c22f6 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentPartFieldDefinitionExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentPartFieldDefinitionExtensions.cs @@ -4,7 +4,7 @@ namespace OrchardCore.ContentManagement.Metadata.Models { public static class ContentPartFieldDefinitionExtensions { - public static bool IsNamedPart(this ContentPartFieldDefinition fieldDefinition) - => fieldDefinition.PartDefinition.IsReusable() && fieldDefinition.ContentTypePartDefinition.Name != fieldDefinition.PartDefinition.Name; + public static bool IsNamedPart(this ContentPartFieldDefinition fieldDefinition) => + fieldDefinition.PartDefinition.IsReusable() && fieldDefinition.ContentTypePartDefinition.Name != fieldDefinition.PartDefinition.Name; } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypeDefinition.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypeDefinition.cs index de5a2023b66..1072f369d13 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypeDefinition.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypeDefinition.cs @@ -40,9 +40,7 @@ public ContentTypeDefinition(string name, string displayName) /// public override string ToString() { - return string.IsNullOrEmpty(DisplayName) - ? Name - : DisplayName; + return string.IsNullOrEmpty(DisplayName) ? Name : DisplayName; } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypeExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypeExtensions.cs index 3821e25eb1f..1028ec37a09 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypeExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypeExtensions.cs @@ -12,44 +12,33 @@ public static bool TryGetStereotype(this ContentTypeDefinition contentTypeDefini return !string.IsNullOrWhiteSpace(stereotype); } - public static bool HasStereotype(this ContentTypeDefinition contentTypeDefinition) - => !string.IsNullOrEmpty(contentTypeDefinition.GetStereotype()); + public static bool HasStereotype(this ContentTypeDefinition contentTypeDefinition) => !string.IsNullOrEmpty(contentTypeDefinition.GetStereotype()); - public static bool StereotypeEquals(this ContentTypeDefinition contentTypeDefinition, string stereotype) - => contentTypeDefinition.StereotypeEquals(stereotype, StringComparison.Ordinal); + public static bool StereotypeEquals(this ContentTypeDefinition contentTypeDefinition, string stereotype) => + contentTypeDefinition.StereotypeEquals(stereotype, StringComparison.Ordinal); public static bool StereotypeEquals(this ContentTypeDefinition contentTypeDefinition, string stereotype, StringComparison stringComparison) { ArgumentNullException.ThrowIfNull(stereotype); - return contentTypeDefinition.TryGetStereotype(out var st) - && string.Equals(st, stereotype, stringComparison); + return contentTypeDefinition.TryGetStereotype(out var st) && string.Equals(st, stereotype, stringComparison); } - public static string GetStereotype(this ContentTypeDefinition contentTypeDefinition) - => contentTypeDefinition.GetSettings().Stereotype; + public static string GetStereotype(this ContentTypeDefinition contentTypeDefinition) => contentTypeDefinition.GetSettings().Stereotype; - public static bool IsListable(this ContentTypeDefinition contentTypeDefinition) - => contentTypeDefinition.GetSettings().Listable; + public static bool IsListable(this ContentTypeDefinition contentTypeDefinition) => contentTypeDefinition.GetSettings().Listable; - public static bool IsCreatable(this ContentTypeDefinition contentTypeDefinition) - => contentTypeDefinition.GetSettings().Creatable; + public static bool IsCreatable(this ContentTypeDefinition contentTypeDefinition) => contentTypeDefinition.GetSettings().Creatable; - public static bool IsDraftable(this ContentTypeDefinition contentTypeDefinition) - => contentTypeDefinition.GetSettings().Draftable; + public static bool IsDraftable(this ContentTypeDefinition contentTypeDefinition) => contentTypeDefinition.GetSettings().Draftable; - public static bool IsVersionable(this ContentTypeDefinition contentTypeDefinition) - => contentTypeDefinition.GetSettings().Versionable; + public static bool IsVersionable(this ContentTypeDefinition contentTypeDefinition) => contentTypeDefinition.GetSettings().Versionable; - public static bool IsSecurable(this ContentTypeDefinition contentTypeDefinition) - => contentTypeDefinition.GetSettings().Securable; + public static bool IsSecurable(this ContentTypeDefinition contentTypeDefinition) => contentTypeDefinition.GetSettings().Securable; - public static bool HasDescription(this ContentTypeDefinition contentTypeDefinition) - => !string.IsNullOrWhiteSpace(contentTypeDefinition.GetSettings().Description); + public static bool HasDescription(this ContentTypeDefinition contentTypeDefinition) => !string.IsNullOrWhiteSpace(contentTypeDefinition.GetSettings().Description); - public static string GetDescription(this ContentTypeDefinition contentTypeDefinition) - => contentTypeDefinition.GetSettings().Description; + public static string GetDescription(this ContentTypeDefinition contentTypeDefinition) => contentTypeDefinition.GetSettings().Description; - public static ContentTypeSettings GetSettings(this ContentTypeDefinition contentTypeDefinition) - => contentTypeDefinition.GetSettings(); + public static ContentTypeSettings GetSettings(this ContentTypeDefinition contentTypeDefinition) => contentTypeDefinition.GetSettings(); } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypePartExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypePartExtensions.cs index c85dd3c0467..ff72e7242f2 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypePartExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentTypePartExtensions.cs @@ -47,7 +47,6 @@ public static string DisplayMode(this ContentTypePartDefinition typePart) return typePart.GetSettings().DisplayMode; } - public static bool IsNamedPart(this ContentTypePartDefinition typePart) - => typePart.PartDefinition.IsReusable() && typePart.Name != typePart.PartDefinition.Name; + public static bool IsNamedPart(this ContentTypePartDefinition typePart) => typePart.PartDefinition.IsReusable() && typePart.Name != typePart.PartDefinition.Name; } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs index ab0d81097b5..0d528645cf4 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs @@ -71,9 +71,7 @@ public static string Ellipsize(this string text, int characterCount, string elli public static LocalizedString OrDefault(this string text, LocalizedString defaultValue) { - return string.IsNullOrEmpty(text) - ? defaultValue - : new LocalizedString(null, text); + return string.IsNullOrEmpty(text) ? defaultValue : new LocalizedString(null, text); } public static string RemoveTags(this string html, bool htmlDecode = false) @@ -121,14 +119,12 @@ public static string RemoveTags(this string html, bool htmlDecode = false) public static string ReplaceNewLinesWith(this string text, string replacement) { return string.IsNullOrWhiteSpace(text) - ? string.Empty - : text - .Replace("\r\n", "\r\r") - .Replace("\n", string.Format(replacement, "\r\n")) - .Replace("\r\r", string.Format(replacement, "\r\n")); + ? string.Empty + : text.Replace("\r\n", "\r\r").Replace("\n", string.Format(replacement, "\r\n")).Replace("\r\r", string.Format(replacement, "\r\n")); } private static readonly char[] _validSegmentChars = "/?#[]@\"^{}|`<>\t\r\n\f ".ToCharArray(); + public static bool IsValidUrlSegment(this string segment) { // valid isegment from rfc3987 - http://tools.ietf.org/html/rfc3987#page-8 @@ -159,10 +155,7 @@ public static string ToSafeName(this string name) } name = RemoveDiacritics(name); - name = name.Strip(c => - !c.IsLetter() - && !char.IsDigit(c) - ); + name = name.Strip(c => !c.IsLetter() && !char.IsDigit(c)); name = name.Trim(); @@ -180,21 +173,22 @@ public static string ToSafeName(this string name) return name; } - private static readonly HashSet _reservedNames = new(StringComparer.OrdinalIgnoreCase) - { - nameof(ContentItem.Id), - nameof(ContentItem.ContentItemId), - nameof(ContentItem.ContentItemVersionId), - nameof(ContentItem.ContentType), - nameof(ContentItem.Published), - nameof(ContentItem.Latest), - nameof(ContentItem.ModifiedUtc), - nameof(ContentItem.PublishedUtc), - nameof(ContentItem.CreatedUtc), - nameof(ContentItem.Owner), - nameof(ContentItem.Author), - nameof(ContentItem.DisplayText), - }; + private static readonly HashSet _reservedNames = + new(StringComparer.OrdinalIgnoreCase) + { + nameof(ContentItem.Id), + nameof(ContentItem.ContentItemId), + nameof(ContentItem.ContentItemVersionId), + nameof(ContentItem.ContentType), + nameof(ContentItem.Published), + nameof(ContentItem.Latest), + nameof(ContentItem.ModifiedUtc), + nameof(ContentItem.PublishedUtc), + nameof(ContentItem.CreatedUtc), + nameof(ContentItem.Owner), + nameof(ContentItem.Author), + nameof(ContentItem.DisplayText), + }; public static bool IsReservedContentName(this string name) { @@ -369,9 +363,7 @@ public static string TrimEnd(this string rough, string trim = "") if (rough == null) return null; - return rough.EndsWith(trim, StringComparison.Ordinal) - ? rough[..^trim.Length] - : rough; + return rough.EndsWith(trim, StringComparison.Ordinal) ? rough[..^trim.Length] : rough; } public static string ReplaceLastOccurrence(this string source, string find, string replace) diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentDisplayOptions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentDisplayOptions.cs index dea08412dbd..be7e2d68f14 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentDisplayOptions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentDisplayOptions.cs @@ -13,11 +13,9 @@ public class ContentDisplayOptions private FrozenDictionary _contentPartOptions; private FrozenDictionary _contentFieldOptions; - public IReadOnlyDictionary ContentPartOptions - => _contentPartOptions ??= _contentParts.ToFrozenDictionary(k => k.Type.Name); + public IReadOnlyDictionary ContentPartOptions => _contentPartOptions ??= _contentParts.ToFrozenDictionary(k => k.Type.Name); - public IReadOnlyDictionary ContentFieldOptions - => _contentFieldOptions ??= _contentFields.ToFrozenDictionary(k => k.Type.Name); + public IReadOnlyDictionary ContentFieldOptions => _contentFieldOptions ??= _contentFields.ToFrozenDictionary(k => k.Type.Name); internal void ForContentPartDisplayMode(Type contentPartType, Type displayDriverType, Func predicate) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayDriver.cs index 396d2a8de69..f41d2784a25 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayDriver.cs @@ -9,7 +9,8 @@ namespace OrchardCore.ContentManagement.Display.ContentDisplay { - public abstract class ContentFieldDisplayDriver : DisplayDriverBase, IContentFieldDisplayDriver where TField : ContentField, new() + public abstract class ContentFieldDisplayDriver : DisplayDriverBase, IContentFieldDisplayDriver + where TField : ContentField, new() { private const string DisplayToken = "_Display"; private const string DisplaySeparator = "_Display__"; @@ -129,10 +130,14 @@ public override ShapeResult Factory(string shapeType, Func IContentFieldDisplayDriver.BuildDisplayAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, BuildDisplayContext context) + Task IContentFieldDisplayDriver.BuildDisplayAsync( + ContentPart contentPart, + ContentPartFieldDefinition partFieldDefinition, + ContentTypePartDefinition typePartDefinition, + BuildDisplayContext context + ) { - if (!string.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && - !string.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) + if (!string.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && !string.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) { return Task.FromResult(default(IDisplayResult)); } @@ -158,10 +163,14 @@ Task IContentFieldDisplayDriver.BuildDisplayAsync(ContentPart co return Task.FromResult(default(IDisplayResult)); } - Task IContentFieldDisplayDriver.BuildEditorAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, BuildEditorContext context) + Task IContentFieldDisplayDriver.BuildEditorAsync( + ContentPart contentPart, + ContentPartFieldDefinition partFieldDefinition, + ContentTypePartDefinition typePartDefinition, + BuildEditorContext context + ) { - if (!string.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && - !string.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) + if (!string.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && !string.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) { return Task.FromResult(default(IDisplayResult)); } @@ -188,10 +197,14 @@ Task IContentFieldDisplayDriver.BuildEditorAsync(ContentPart con return Task.FromResult(default(IDisplayResult)); } - async Task IContentFieldDisplayDriver.UpdateEditorAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, UpdateEditorContext context) + async Task IContentFieldDisplayDriver.UpdateEditorAsync( + ContentPart contentPart, + ContentPartFieldDefinition partFieldDefinition, + ContentTypePartDefinition typePartDefinition, + UpdateEditorContext context + ) { - if (!string.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && - !string.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) + if (!string.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && !string.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) { return null; } @@ -253,9 +266,7 @@ public virtual IDisplayResult Update(TField field, IUpdateModel updater, UpdateF protected string GetEditorShapeType(string shapeType, ContentPartFieldDefinition partFieldDefinition) { var editor = partFieldDefinition.Editor(); - return !string.IsNullOrEmpty(editor) - ? shapeType + "__" + editor - : shapeType; + return !string.IsNullOrEmpty(editor) ? shapeType + "__" + editor : shapeType; } protected string GetEditorShapeType(string shapeType, BuildFieldEditorContext context) @@ -276,9 +287,7 @@ protected string GetEditorShapeType(BuildFieldEditorContext context) protected string GetDisplayShapeType(string shapeType, BuildFieldDisplayContext context) { var displayMode = context.PartFieldDefinition.DisplayMode(); - return !string.IsNullOrEmpty(displayMode) - ? shapeType + DisplaySeparator + displayMode - : shapeType; + return !string.IsNullOrEmpty(displayMode) ? shapeType + DisplaySeparator + displayMode : shapeType; } protected string GetDisplayShapeType(BuildFieldDisplayContext context) diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayDriverResolver.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayDriverResolver.cs index cc2481bda9f..bcdbfae4931 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayDriverResolver.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayDriverResolver.cs @@ -10,10 +10,7 @@ public class ContentFieldDisplayDriverResolver : IContentFieldDisplayDriverResol private readonly IServiceProvider _serviceProvider; private readonly ContentDisplayOptions _contentDisplayOptions; - public ContentFieldDisplayDriverResolver( - IServiceProvider serviceProvider, - IOptions contentDisplayOptions - ) + public ContentFieldDisplayDriverResolver(IServiceProvider serviceProvider, IOptions contentDisplayOptions) { _serviceProvider = serviceProvider; _contentDisplayOptions = contentDisplayOptions.Value; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayOption.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayOption.cs index 25107b3b47d..5f243555971 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayOption.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayOption.cs @@ -8,9 +8,8 @@ public class ContentFieldDisplayOption : ContentFieldOptionBase { private readonly List _fieldDisplayDrivers = []; - public ContentFieldDisplayOption(Type contentFieldType) : base(contentFieldType) - { - } + public ContentFieldDisplayOption(Type contentFieldType) + : base(contentFieldType) { } private List _displayModeDrivers; public IReadOnlyList DisplayModeDrivers => _displayModeDrivers ??= _fieldDisplayDrivers.Where(d => d.DisplayMode != null).ToList(); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldServiceCollectionExtensions.cs index 513a040437d..e07d280fbe4 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldServiceCollectionExtensions.cs @@ -24,8 +24,7 @@ public static ContentFieldOptionBuilder UseDisplayDriver public static ContentFieldOptionBuilder UseDisplayDriver(this ContentFieldOptionBuilder builder, Type fieldDisplayDriverType) { - return builder.ForDisplayMode(fieldDisplayDriverType) - .ForEditor(fieldDisplayDriverType); + return builder.ForDisplayMode(fieldDisplayDriverType).ForEditor(fieldDisplayDriverType); } /// @@ -36,8 +35,7 @@ public static ContentFieldOptionBuilder UseDisplayDriver(this ContentFieldOption public static ContentFieldOptionBuilder UseDisplayDriver(this ContentFieldOptionBuilder builder, Func predicate) where TContentFieldDisplayDriver : class, IContentFieldDisplayDriver { - return builder.ForDisplayMode(typeof(TContentFieldDisplayDriver), predicate) - .ForEditor(typeof(TContentFieldDisplayDriver), predicate); + return builder.ForDisplayMode(typeof(TContentFieldDisplayDriver), predicate).ForEditor(typeof(TContentFieldDisplayDriver), predicate); } /// diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentItemDisplayCoordinator.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentItemDisplayCoordinator.cs index 9b252670d82..9fcfb1efc37 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentItemDisplayCoordinator.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentItemDisplayCoordinator.cs @@ -32,7 +32,8 @@ public ContentItemDisplayCoordinator( IContentDefinitionManager contentDefinitionManager, IEnumerable displayDrivers, ITypeActivatorFactory contentPartFactory, - ILogger logger) + ILogger logger + ) { _contentPartDisplayDriverResolver = contentPartDisplayDriverResolver; _contentFieldDisplayDriverResolver = contentFieldDisplayDriverResolver; @@ -107,7 +108,10 @@ public async Task BuildDisplayAsync(ContentItem contentItem, BuildDisplayContext { var shapeType = context.DisplayType != "Detail" ? "ContentPart_" + context.DisplayType : "ContentPart"; - var shapeResult = new ShapeResult(shapeType, ctx => ctx.ShapeFactory.CreateAsync(shapeType, () => new ValueTask(new ZoneHolding(() => ctx.ShapeFactory.CreateAsync("Zone"))))); + var shapeResult = new ShapeResult( + shapeType, + ctx => ctx.ShapeFactory.CreateAsync(shapeType, () => new ValueTask(new ZoneHolding(() => ctx.ShapeFactory.CreateAsync("Zone")))) + ); shapeResult.Differentiator(partName); shapeResult.Name(partName); shapeResult.Location("Content"); @@ -170,7 +174,10 @@ public async Task BuildDisplayAsync(ContentItem contentItem, BuildDisplayContext foreach (var contentPartFieldDefinition in contentTypePartDefinition.PartDefinition.Fields) { - var fieldDisplayDrivers = _contentFieldDisplayDriverResolver.GetDisplayModeDrivers(contentPartFieldDefinition.FieldDefinition.Name, contentPartFieldDefinition.DisplayMode()); + var fieldDisplayDrivers = _contentFieldDisplayDriverResolver.GetDisplayModeDrivers( + contentPartFieldDefinition.FieldDefinition.Name, + contentPartFieldDefinition.DisplayMode() + ); foreach (var fieldDisplayDriver in fieldDisplayDrivers) { try @@ -201,11 +208,7 @@ public async Task BuildEditorAsync(ContentItem contentItem, BuildEditorContext c } var contentShape = context.Shape as IZoneHolding; - var partsShape = await context.ShapeFactory.CreateAsync("ContentZone", - Arguments.From(new - { - Identifier = contentItem.ContentItemId - })); + var partsShape = await context.ShapeFactory.CreateAsync("ContentZone", Arguments.From(new { Identifier = contentItem.ContentItemId })); contentShape.Zones["Parts"] = partsShape; @@ -255,14 +258,20 @@ public async Task BuildEditorAsync(ContentItem contentItem, BuildEditorContext c context.DefaultPosition = partPosition; var partDisplayDrivers = _contentPartDisplayDriverResolver.GetEditorDrivers(partTypeName, typePartDefinition.Editor()); - await partDisplayDrivers.InvokeAsync(async (driver, part, typePartDefinition, context) => - { - var result = await driver.BuildEditorAsync(part, typePartDefinition, context); - if (result != null) + await partDisplayDrivers.InvokeAsync( + async (driver, part, typePartDefinition, context) => { - await result.ApplyAsync(context); - } - }, part, typePartDefinition, context, _logger); + var result = await driver.BuildEditorAsync(part, typePartDefinition, context); + if (result != null) + { + await result.ApplyAsync(context); + } + }, + part, + typePartDefinition, + context, + _logger + ); foreach (var partFieldDefinition in typePartDefinition.PartDefinition.Fields) { @@ -271,14 +280,21 @@ await partDisplayDrivers.InvokeAsync(async (driver, part, typePartDefinition, co context.DefaultZone = $"Parts.{partName}:{fieldPosition}"; var fieldDisplayDrivers = _contentFieldDisplayDriverResolver.GetEditorDrivers(partFieldDefinition.FieldDefinition.Name, partFieldDefinition.Editor()); - await fieldDisplayDrivers.InvokeAsync(async (driver, part, partFieldDefinition, typePartDefinition, context) => - { - var result = await driver.BuildEditorAsync(part, partFieldDefinition, typePartDefinition, context); - if (result != null) + await fieldDisplayDrivers.InvokeAsync( + async (driver, part, partFieldDefinition, typePartDefinition, context) => { - await result.ApplyAsync(context); - } - }, part, partFieldDefinition, typePartDefinition, context, _logger); + var result = await driver.BuildEditorAsync(part, partFieldDefinition, typePartDefinition, context); + if (result != null) + { + await result.ApplyAsync(context); + } + }, + part, + partFieldDefinition, + typePartDefinition, + context, + _logger + ); } } } @@ -290,11 +306,7 @@ public async Task UpdateEditorAsync(ContentItem contentItem, UpdateEditorContext return; var contentShape = context.Shape as IZoneHolding; - var partsShape = await context.ShapeFactory.CreateAsync("ContentZone", - Arguments.From(new - { - Identifier = contentItem.ContentItemId - })); + var partsShape = await context.ShapeFactory.CreateAsync("ContentZone", Arguments.From(new { Identifier = contentItem.ContentItemId })); contentShape.Zones["Parts"] = partsShape; @@ -342,14 +354,20 @@ public async Task UpdateEditorAsync(ContentItem contentItem, UpdateEditorContext context.DefaultZone = $"Parts.{partName}:{partPosition}"; var partDisplayDrivers = _contentPartDisplayDriverResolver.GetEditorDrivers(partTypeName, typePartDefinition.Editor()); - await partDisplayDrivers.InvokeAsync(async (driver, part, typePartDefinition, context) => - { - var result = await driver.UpdateEditorAsync(part, typePartDefinition, context); - if (result != null) + await partDisplayDrivers.InvokeAsync( + async (driver, part, typePartDefinition, context) => { - await result.ApplyAsync(context); - } - }, part, typePartDefinition, context, _logger); + var result = await driver.UpdateEditorAsync(part, typePartDefinition, context); + if (result != null) + { + await result.ApplyAsync(context); + } + }, + part, + typePartDefinition, + context, + _logger + ); foreach (var partFieldDefinition in typePartDefinition.PartDefinition.Fields) { @@ -358,14 +376,21 @@ await partDisplayDrivers.InvokeAsync(async (driver, part, typePartDefinition, co context.DefaultZone = $"Parts.{partName}:{fieldPosition}"; var fieldDisplayDrivers = _contentFieldDisplayDriverResolver.GetEditorDrivers(partFieldDefinition.FieldDefinition.Name, partFieldDefinition.Editor()); - await fieldDisplayDrivers.InvokeAsync(async (driver, part, partFieldDefinition, typePartDefinition, context) => - { - var result = await driver.UpdateEditorAsync(part, partFieldDefinition, typePartDefinition, context); - if (result != null) + await fieldDisplayDrivers.InvokeAsync( + async (driver, part, partFieldDefinition, typePartDefinition, context) => { - await result.ApplyAsync(context); - } - }, part, partFieldDefinition, typePartDefinition, context, _logger); + var result = await driver.UpdateEditorAsync(part, partFieldDefinition, typePartDefinition, context); + if (result != null) + { + await result.ApplyAsync(context); + } + }, + part, + partFieldDefinition, + typePartDefinition, + context, + _logger + ); } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayDriverResolver.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayDriverResolver.cs index 773309c3f61..10e09791da7 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayDriverResolver.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayDriverResolver.cs @@ -9,10 +9,8 @@ public class ContentPartDisplayDriverResolver : IContentPartDisplayDriverResolve { private readonly IServiceProvider _serviceProvider; private readonly ContentDisplayOptions _contentDisplayOptions; - public ContentPartDisplayDriverResolver( - IServiceProvider serviceProvider, - IOptions contentDisplayOptions - ) + + public ContentPartDisplayDriverResolver(IServiceProvider serviceProvider, IOptions contentDisplayOptions) { _serviceProvider = serviceProvider; _contentDisplayOptions = contentDisplayOptions.Value; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayDriverTPart.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayDriverTPart.cs index ec1bd4ea464..20f9d5bfc3b 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayDriverTPart.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayDriverTPart.cs @@ -14,7 +14,8 @@ namespace OrchardCore.ContentManagement.Display.ContentDisplay /// Any concrete implementation of this class can provide shapes for any content item which has a specific Part. /// /// - public abstract class ContentPartDisplayDriver : DisplayDriverBase, IContentPartDisplayDriver where TPart : ContentPart, new() + public abstract class ContentPartDisplayDriver : DisplayDriverBase, IContentPartDisplayDriver + where TPart : ContentPart, new() { private const string DisplayToken = "_Display"; private const string DisplaySeparator = "_Display__"; @@ -295,9 +296,7 @@ public virtual Task UpdateAsync(TPart part, IUpdateModel updater protected string GetEditorShapeType(string shapeType, ContentTypePartDefinition typePartDefinition) { var editor = typePartDefinition.Editor(); - return !string.IsNullOrEmpty(editor) - ? shapeType + "__" + editor - : shapeType; + return !string.IsNullOrEmpty(editor) ? shapeType + "__" + editor : shapeType; } protected string GetEditorShapeType(string shapeType, BuildPartEditorContext context) @@ -318,9 +317,7 @@ protected string GetEditorShapeType(BuildPartEditorContext context) protected string GetDisplayShapeType(string shapeType, BuildPartDisplayContext context) { var displayMode = context.TypePartDefinition.DisplayMode(); - return !string.IsNullOrEmpty(displayMode) - ? shapeType + DisplaySeparator + displayMode - : shapeType; + return !string.IsNullOrEmpty(displayMode) ? shapeType + DisplaySeparator + displayMode : shapeType; } protected string GetDisplayShapeType(BuildPartDisplayContext context) diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayOption.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayOption.cs index b244045022e..f4f88ef9e41 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayOption.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayOption.cs @@ -8,18 +8,15 @@ public class ContentPartDisplayOption : ContentPartOptionBase { private readonly List _partDisplayDrivers = []; - public ContentPartDisplayOption(Type contentPartType) : base(contentPartType) - { - } + public ContentPartDisplayOption(Type contentPartType) + : base(contentPartType) { } private IReadOnlyList _displayDrivers; private IReadOnlyList _editorDrivers; - public IReadOnlyList DisplayDrivers - => _displayDrivers ??= _partDisplayDrivers.Where(d => d.DisplayMode != null).ToList(); + public IReadOnlyList DisplayDrivers => _displayDrivers ??= _partDisplayDrivers.Where(d => d.DisplayMode != null).ToList(); - public IReadOnlyList EditorDrivers - => _editorDrivers ??= _partDisplayDrivers.Where(d => d.Editor != null).ToList(); + public IReadOnlyList EditorDrivers => _editorDrivers ??= _partDisplayDrivers.Where(d => d.Editor != null).ToList(); internal void ForDisplayMode(Type displayDriverType, Func predicate) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartServiceCollectionExtensions.cs index 3ad879bdaaa..8ef1883e7ae 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartServiceCollectionExtensions.cs @@ -24,8 +24,7 @@ public static ContentPartOptionBuilder UseDisplayDriver public static ContentPartOptionBuilder UseDisplayDriver(this ContentPartOptionBuilder builder, Type partDisplayDriverType) { - return builder.ForDisplayMode(partDisplayDriverType) - .ForEditor(partDisplayDriverType); + return builder.ForDisplayMode(partDisplayDriverType).ForEditor(partDisplayDriverType); } /// diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/IContentDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/IContentDisplayDriver.cs index c75b71071bc..a0f605778f2 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/IContentDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/IContentDisplayDriver.cs @@ -2,7 +2,5 @@ namespace OrchardCore.ContentManagement.Display.ContentDisplay { - public interface IContentDisplayDriver : IDisplayDriver - { - } + public interface IContentDisplayDriver : IDisplayDriver { } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/IContentFieldDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/IContentFieldDisplayDriver.cs index ea15576350e..914344d6ecb 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/IContentFieldDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/IContentFieldDisplayDriver.cs @@ -7,8 +7,23 @@ namespace OrchardCore.ContentManagement.Display.ContentDisplay { public interface IContentFieldDisplayDriver { - Task BuildDisplayAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, BuildDisplayContext context); - Task BuildEditorAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, BuildEditorContext context); - Task UpdateEditorAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, UpdateEditorContext context); + Task BuildDisplayAsync( + ContentPart contentPart, + ContentPartFieldDefinition partFieldDefinition, + ContentTypePartDefinition typePartDefinition, + BuildDisplayContext context + ); + Task BuildEditorAsync( + ContentPart contentPart, + ContentPartFieldDefinition partFieldDefinition, + ContentTypePartDefinition typePartDefinition, + BuildEditorContext context + ); + Task UpdateEditorAsync( + ContentPart contentPart, + ContentPartFieldDefinition partFieldDefinition, + ContentTypePartDefinition typePartDefinition, + UpdateEditorContext context + ); } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentItemDisplayManager.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentItemDisplayManager.cs index 81f378cd29b..e8202910ed6 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentItemDisplayManager.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentItemDisplayManager.cs @@ -39,7 +39,8 @@ public ContentItemDisplayManager( IEnumerable placementProviders, ILogger logger, ILayoutAccessor layoutAccessor - ) : base(shapeFactory, placementProviders) + ) + : base(shapeFactory, placementProviders) { _handlers = handlers; _contentHandlers = contentHandlers; @@ -53,7 +54,8 @@ public async Task BuildDisplayAsync(ContentItem contentItem, IUpdateMode { ArgumentNullException.ThrowIfNull(contentItem); - var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType) + var contentTypeDefinition = + await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType) ?? throw new NullReferenceException($"Content Type {contentItem.ContentType} does not exist."); var actualDisplayType = string.IsNullOrEmpty(displayType) ? "Detail" : displayType; @@ -91,7 +93,7 @@ public async Task BuildDisplayAsync(ContentItem contentItem, IUpdateMode } else { - // Add fallback/default alternate i.e. Content + // Add fallback/default alternate i.e. Content metadata.Alternates.Add("Stereotype"); // Add alternate to make the type [Stereotype] e.g. Menu @@ -122,7 +124,8 @@ public async Task BuildEditorAsync(ContentItem contentItem, IUpdateModel { ArgumentNullException.ThrowIfNull(contentItem); - var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType) + var contentTypeDefinition = + await _contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType) ?? throw new NullReferenceException($"Content Type {contentItem.ContentType} does not exist."); var hasStereotype = contentTypeDefinition.TryGetStereotype(out var stereotype); @@ -170,7 +173,8 @@ public async Task UpdateEditorAsync(ContentItem contentItem, IUpdateMode { ArgumentNullException.ThrowIfNull(contentItem); - var contentTypeDefinition = await _contentDefinitionManager.LoadTypeDefinitionAsync(contentItem.ContentType) + var contentTypeDefinition = + await _contentDefinitionManager.LoadTypeDefinitionAsync(contentItem.ContentType) ?? throw new NullReferenceException($"Content Type {contentItem.ContentType} does not exist."); var hasStereotype = contentTypeDefinition.TryGetStereotype(out var stereotype); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/BuildFieldDisplayContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/BuildFieldDisplayContext.cs index f5e8ea58c36..a761cd80e15 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/BuildFieldDisplayContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/BuildFieldDisplayContext.cs @@ -5,7 +5,12 @@ namespace OrchardCore.ContentManagement.Display.Models { public class BuildFieldDisplayContext : BuildDisplayContext { - public BuildFieldDisplayContext(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, ContentPartFieldDefinition partFieldDefinition, BuildDisplayContext context) + public BuildFieldDisplayContext( + ContentPart contentPart, + ContentTypePartDefinition typePartDefinition, + ContentPartFieldDefinition partFieldDefinition, + BuildDisplayContext context + ) : base(context.Shape, context.DisplayType, context.GroupId, context.ShapeFactory, context.Layout, context.Updater) { ContentPart = contentPart; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/BuildFieldEditorContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/BuildFieldEditorContext.cs index 02766bd7ee6..17fac900e8f 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/BuildFieldEditorContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/BuildFieldEditorContext.cs @@ -5,7 +5,12 @@ namespace OrchardCore.ContentManagement.Display.Models { public class BuildFieldEditorContext : BuildEditorContext { - public BuildFieldEditorContext(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, ContentPartFieldDefinition partFieldDefinition, BuildEditorContext context) + public BuildFieldEditorContext( + ContentPart contentPart, + ContentTypePartDefinition typePartDefinition, + ContentPartFieldDefinition partFieldDefinition, + BuildEditorContext context + ) : base(context.Shape, context.GroupId, context.IsNew, "", context.ShapeFactory, context.Layout, context.Updater) { ContentPart = contentPart; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/UpdateFieldEditorContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/UpdateFieldEditorContext.cs index d7d5f166b3e..ccf44a27593 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/UpdateFieldEditorContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/UpdateFieldEditorContext.cs @@ -5,9 +5,12 @@ namespace OrchardCore.ContentManagement.Display.Models { public class UpdateFieldEditorContext : BuildFieldEditorContext { - public UpdateFieldEditorContext(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, ContentPartFieldDefinition partFieldDefinition, UpdateEditorContext context) - : base(contentPart, typePartDefinition, partFieldDefinition, context) - { - } + public UpdateFieldEditorContext( + ContentPart contentPart, + ContentTypePartDefinition typePartDefinition, + ContentPartFieldDefinition partFieldDefinition, + UpdateEditorContext context + ) + : base(contentPart, typePartDefinition, partFieldDefinition, context) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/UpdatePartEditorContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/UpdatePartEditorContext.cs index 7c5d098881b..9ed04ee9f86 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/UpdatePartEditorContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/Models/UpdatePartEditorContext.cs @@ -5,11 +5,7 @@ namespace OrchardCore.ContentManagement.Display.Models { public class UpdatePartEditorContext : BuildPartEditorContext { - public UpdatePartEditorContext(ContentTypePartDefinition typePartDefinition, UpdateEditorContext context) - : base(typePartDefinition, context) - { - } - + : base(typePartDefinition, context) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/Placement/ContentPartPlacementNodeFilterProvider.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/Placement/ContentPartPlacementNodeFilterProvider.cs index 05a10be0cc1..8aa0223be26 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/Placement/ContentPartPlacementNodeFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/Placement/ContentPartPlacementNodeFilterProvider.cs @@ -11,7 +11,10 @@ namespace OrchardCore.ContentManagement.Display.Placement { public class ContentPartPlacementNodeFilterProvider : ContentPlacementParseFilterProviderBase, IPlacementNodeFilterProvider { - public string Key { get { return "contentPart"; } } + public string Key + { + get { return "contentPart"; } + } public bool IsMatch(ShapePlacementContext context, object expression) { @@ -35,7 +38,10 @@ public bool IsMatch(ShapePlacementContext context, object expression) public class ContentTypePlacementNodeFilterProvider : ContentPlacementParseFilterProviderBase, IPlacementNodeFilterProvider { - public string Key { get { return "contentType"; } } + public string Key + { + get { return "contentType"; } + } public bool IsMatch(ShapePlacementContext context, object expression) { @@ -63,7 +69,8 @@ public bool IsMatch(ShapePlacementContext context, object expression) { var prefix = ct[..^1]; - return (contentItem.ContentType ?? "").StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || (GetStereotype(context) ?? "").StartsWith(prefix, StringComparison.OrdinalIgnoreCase); + return (contentItem.ContentType ?? "").StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + || (GetStereotype(context) ?? "").StartsWith(prefix, StringComparison.OrdinalIgnoreCase); } return contentItem.ContentType == ct || GetStereotype(context) == ct; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/Razor/OrchardRazorHelperExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/Razor/OrchardRazorHelperExtensions.cs index 5fe1f5808b7..284a3881879 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/Razor/OrchardRazorHelperExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/Razor/OrchardRazorHelperExtensions.cs @@ -15,7 +15,13 @@ public static class OrchardRazorHelperExtensions #pragma warning restore CA1050 // Declare types in namespaces { - public static async Task DisplayAsync(this IOrchardDisplayHelper orchardDisplayHelper, ContentItem content, string displayType = "", string groupId = "", IUpdateModel updater = null) + public static async Task DisplayAsync( + this IOrchardDisplayHelper orchardDisplayHelper, + ContentItem content, + string displayType = "", + string groupId = "", + IUpdateModel updater = null + ) { var displayManager = orchardDisplayHelper.HttpContext.RequestServices.GetService(); var shape = await displayManager.BuildDisplayAsync(content, updater, displayType, groupId); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ViewModels/ContentItemViewModel.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ViewModels/ContentItemViewModel.cs index 2f15d4e1214..726f5c1704d 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ViewModels/ContentItemViewModel.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ViewModels/ContentItemViewModel.cs @@ -4,9 +4,7 @@ namespace OrchardCore.ContentManagement.Display.ViewModels { public class ContentItemViewModel : ShapeViewModel { - public ContentItemViewModel() - { - } + public ContentItemViewModel() { } public ContentItemViewModel(ContentItem contentItem) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ViewModels/ContentPartViewModel.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ViewModels/ContentPartViewModel.cs index 28c3ae87856..50c72edf9d1 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ViewModels/ContentPartViewModel.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ViewModels/ContentPartViewModel.cs @@ -4,9 +4,7 @@ namespace OrchardCore.ContentManagement.Display.ViewModels { public class ContentPartViewModel : ShapeViewModel { - public ContentPartViewModel() - { - } + public ContentPartViewModel() { } public ContentPartViewModel(ContentPart contentPart) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Extensions/FieldTypeExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Extensions/FieldTypeExtensions.cs index 6bd87f3ec3d..d1e39ed9e83 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Extensions/FieldTypeExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Extensions/FieldTypeExtensions.cs @@ -4,11 +4,9 @@ namespace OrchardCore.ContentManagement.GraphQL; public static class FieldTypeExtensions { - public static FieldType WithPartCollapsedMetaData(this FieldType fieldType, bool collapsed = true) - => fieldType.WithMetaData("PartCollapsed", collapsed); + public static FieldType WithPartCollapsedMetaData(this FieldType fieldType, bool collapsed = true) => fieldType.WithMetaData("PartCollapsed", collapsed); - public static FieldType WithPartNameMetaData(this FieldType fieldType, string partName) - => fieldType.WithMetaData("PartName", partName); + public static FieldType WithPartNameMetaData(this FieldType fieldType, string partName) => fieldType.WithMetaData("PartName", partName); private static FieldType WithMetaData(this FieldType fieldType, string name, object value) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentOptions.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentOptions.cs index f890610d32e..542dcbd3bbd 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentOptions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentOptions.cs @@ -55,7 +55,8 @@ public GraphQLContentOptions ConfigurePart(string partName, Action(string fieldName) where TGraphType : IObjectGraphType + public GraphQLContentOptions IgnoreField(string fieldName) + where TGraphType : IObjectGraphType { HiddenFields = HiddenFields.Union([new GraphQLField(fieldName)]); @@ -180,8 +181,7 @@ public bool ShouldHide(ContentTypeDefinition definition) internal bool ShouldSkip(Type fieldType, string fieldName) { - return HiddenFields - .Any(x => x.FieldType == fieldType && x.FieldName.Equals(fieldName, StringComparison.OrdinalIgnoreCase)); + return HiddenFields.Any(x => x.FieldType == fieldType && x.FieldName.Equals(fieldName, StringComparison.OrdinalIgnoreCase)); } public bool IsHiddenByDefault(ContentTypePartDefinition definition) diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentPartOption.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentPartOption.cs index 3f8bece59c0..e74edafcd58 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentPartOption.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentPartOption.cs @@ -2,11 +2,11 @@ namespace OrchardCore.ContentManagement.GraphQL.Options { - public class GraphQLContentPartOption : GraphQLContentPartOption where TContentPart : ContentPart + public class GraphQLContentPartOption : GraphQLContentPartOption + where TContentPart : ContentPart { - public GraphQLContentPartOption() : base(typeof(TContentPart).Name) - { - } + public GraphQLContentPartOption() + : base(typeof(TContentPart).Name) { } } public class GraphQLContentPartOption diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentTypeOption.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentTypeOption.cs index fb6b36fe0d7..96d0f086ac9 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentTypeOption.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentTypeOption.cs @@ -19,8 +19,7 @@ public GraphQLContentTypeOption(string contentType) public bool Hidden { get; set; } - public IEnumerable PartOptions { get; set; } - = []; + public IEnumerable PartOptions { get; set; } = []; public GraphQLContentTypeOption ConfigurePart(Action action) where TContentPart : ContentPart diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLField.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLField.cs index 984ab55909f..0ff40fd5882 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLField.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLField.cs @@ -3,11 +3,11 @@ namespace OrchardCore.ContentManagement.GraphQL.Options { - public class GraphQLField : GraphQLField where TGraphType : IObjectGraphType + public class GraphQLField : GraphQLField + where TGraphType : IObjectGraphType { - public GraphQLField(string fieldName) : base(typeof(TGraphType), fieldName) - { - } + public GraphQLField(string fieldName) + : base(typeof(TGraphType), fieldName) { } } public class GraphQLField diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Permissions.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Permissions.cs index efedc48431a..46d08a98f14 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Permissions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Permissions.cs @@ -8,20 +8,9 @@ public class Permissions : IPermissionProvider { public static readonly Permission ApiViewContent = new("ApiViewContent", "Access view content endpoints"); - private readonly IEnumerable _allPermissions = - [ - ApiViewContent, - ]; + private readonly IEnumerable _allPermissions = [ApiViewContent,]; - public Task> GetPermissionsAsync() - => Task.FromResult(_allPermissions); + public Task> GetPermissionsAsync() => Task.FromResult(_allPermissions); - public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = _allPermissions, - }, - ]; + public IEnumerable GetDefaultStereotypes() => [new PermissionStereotype { Name = "Administrator", Permissions = _allPermissions, },]; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemFilters.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemFilters.cs index ab0f80fc75b..683ba8e88d4 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemFilters.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemFilters.cs @@ -18,9 +18,7 @@ public class ContentItemFilters : GraphQLFilter private readonly IContentDefinitionManager _contentDefinitionManager; private readonly IAuthorizationService _authorizationService; - public ContentItemFilters(IHttpContextAccessor httpContextAccessor, - IContentDefinitionManager contentDefinitionManager, - IAuthorizationService authorizationService) + public ContentItemFilters(IHttpContextAccessor httpContextAccessor, IContentDefinitionManager contentDefinitionManager, IAuthorizationService authorizationService) { _httpContextAccessor = httpContextAccessor; _contentDefinitionManager = contentDefinitionManager; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemQuery.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemQuery.cs index bec5c82c157..d0913a59af6 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemQuery.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemQuery.cs @@ -15,8 +15,7 @@ public class ContentItemQuery : ISchemaBuilder private readonly IHttpContextAccessor _httpContextAccessor; protected readonly IStringLocalizer S; - public ContentItemQuery(IHttpContextAccessor httpContextAccessor, - IStringLocalizer localizer) + public ContentItemQuery(IHttpContextAccessor httpContextAccessor, IStringLocalizer localizer) { _httpContextAccessor = httpContextAccessor; @@ -32,13 +31,7 @@ public Task BuildAsync(ISchema schema) Name = "ContentItem", Description = S["Content items are instances of content types, just like objects are instances of classes."], Type = typeof(ContentItemInterface), - Arguments = new QueryArguments( - new QueryArgument> - { - Name = "contentItemId", - Description = S["Content item id"] - } - ), + Arguments = new QueryArguments(new QueryArgument> { Name = "contentItemId", Description = S["Content item id"] }), Resolver = new FuncFieldResolver(ResolveAsync) }; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemsFieldType.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemsFieldType.cs index 7a682b0268e..f123364f093 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemsFieldType.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemsFieldType.cs @@ -49,11 +49,37 @@ public ContentItemsFieldType(string contentItemName, ISchema schema, IOptions { Name = "where", Description = "filters the content items", ResolvedType = whereInput }, - new QueryArgument { Name = "orderBy", Description = "sort order", ResolvedType = orderByInput }, - new QueryArgument { Name = "first", Description = "the first n content items", ResolvedType = new IntGraphType() }, - new QueryArgument { Name = "skip", Description = "the number of content items to skip", ResolvedType = new IntGraphType() }, - new QueryArgument { Name = "status", Description = "publication status of the content item", ResolvedType = new PublicationStatusGraphType(), DefaultValue = PublicationStatusEnum.Published } + new QueryArgument + { + Name = "where", + Description = "filters the content items", + ResolvedType = whereInput + }, + new QueryArgument + { + Name = "orderBy", + Description = "sort order", + ResolvedType = orderByInput + }, + new QueryArgument + { + Name = "first", + Description = "the first n content items", + ResolvedType = new IntGraphType() + }, + new QueryArgument + { + Name = "skip", + Description = "the number of content items to skip", + ResolvedType = new IntGraphType() + }, + new QueryArgument + { + Name = "status", + Description = "publication status of the content item", + ResolvedType = new PublicationStatusGraphType(), + DefaultValue = PublicationStatusEnum.Published + } ); Resolver = new LockedAsyncFieldResolver>(Resolve); @@ -66,7 +92,6 @@ public ContentItemsFieldType(string contentItemName, ISchema schema, IOptions> Resolve(IResolveFieldContext context) - { var versionOption = VersionOptions.Published; @@ -112,11 +137,7 @@ private async ValueTask> Resolve(IResolveFieldContext c return contentItems; } - private IQuery FilterWhereArguments( - IQuery query, - JsonObject where, - IResolveFieldContext fieldContext, - ISession session) + private IQuery FilterWhereArguments(IQuery query, JsonObject where, IResolveFieldContext fieldContext, ISession session) { if (where == null) { @@ -127,7 +148,8 @@ private IQuery FilterWhereArguments( var predicateQuery = new PredicateQuery( configuration: session.Store.Configuration, - propertyProviders: fieldContext.RequestServices.GetServices()); + propertyProviders: fieldContext.RequestServices.GetServices() + ); // Create the default table alias. predicateQuery.CreateAlias("", nameof(ContentItemIndex)); @@ -166,7 +188,6 @@ private IQuery FilterWhereArguments( var whereSqlClause = expressions.ToSqlString(predicateQuery); - query = query.Where(whereSqlClause); // Add all parameters that were used in the predicate query. @@ -255,7 +276,13 @@ private void BuildWhereExpressions(JsonNode where, Junction expressions, string } } - private void BuildExpressionsInternal(JsonObject where, Junction expressions, string tableAlias, IResolveFieldContext fieldContext, IDictionary indexAliases) + private void BuildExpressionsInternal( + JsonObject where, + Junction expressions, + string tableAlias, + IResolveFieldContext fieldContext, + IDictionary indexAliases + ) { foreach (var entry in where) { @@ -284,8 +311,10 @@ private void BuildExpressionsInternal(JsonObject where, Junction expressions, st foreach (var field in whereInput.Fields.Where(x => x.GetMetadata("PartName") != null)) { var partName = field.GetMetadata("PartName"); - if ((tableAlias == null && field.GetMetadata("PartCollapsed") && field.Name.Equals(property, StringComparison.OrdinalIgnoreCase)) || - (tableAlias != null && partName.ToFieldName().Equals(tableAlias, StringComparison.OrdinalIgnoreCase))) + if ( + (tableAlias == null && field.GetMetadata("PartCollapsed") && field.Name.Equals(property, StringComparison.OrdinalIgnoreCase)) + || (tableAlias != null && partName.ToFieldName().Equals(tableAlias, StringComparison.OrdinalIgnoreCase)) + ) { tableAlias = indexAliases.TryGetValue(partName, out var indexTableAlias) ? indexTableAlias : tableAlias; break; @@ -359,8 +388,7 @@ private void BuildExpressionsInternal(JsonObject where, Junction expressions, st } } - private static IQuery OrderBy(IQuery query, - IResolveFieldContext context) + private static IQuery OrderBy(IQuery query, IResolveFieldContext context) { if (context.HasPopulatedArgument("orderBy")) { @@ -378,33 +406,47 @@ private static IQuery OrderBy(IQuery x.ContentItemId; break; - case "contentItemVersionId": selector = x => x.ContentItemVersionId; break; - case "displayText": selector = x => x.DisplayText; break; - case "published": selector = x => x.Published; break; - case "latest": selector = x => x.Latest; break; - case "createdUtc": selector = x => x.CreatedUtc; break; - case "modifiedUtc": selector = x => x.ModifiedUtc; break; - case "publishedUtc": selector = x => x.PublishedUtc; break; - case "owner": selector = x => x.Owner; break; - case "author": selector = x => x.Author; break; + case "contentItemId": + selector = x => x.ContentItemId; + break; + case "contentItemVersionId": + selector = x => x.ContentItemVersionId; + break; + case "displayText": + selector = x => x.DisplayText; + break; + case "published": + selector = x => x.Published; + break; + case "latest": + selector = x => x.Latest; + break; + case "createdUtc": + selector = x => x.CreatedUtc; + break; + case "modifiedUtc": + selector = x => x.ModifiedUtc; + break; + case "publishedUtc": + selector = x => x.PublishedUtc; + break; + case "owner": + selector = x => x.Owner; + break; + case "author": + selector = x => x.Author; + break; } if (selector != null) { if (!thenBy) { - query = direction == OrderByDirection.Ascending - ? query.OrderBy(selector) - : query.OrderByDescending(selector) - ; + query = direction == OrderByDirection.Ascending ? query.OrderBy(selector) : query.OrderByDescending(selector); } else { - query = direction == OrderByDirection.Ascending - ? query.ThenBy(selector) - : query.ThenByDescending(selector) - ; + query = direction == OrderByDirection.Ascending ? query.ThenBy(selector) : query.ThenByDescending(selector); } thenBy = true; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentTypeQuery.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentTypeQuery.cs index 4c4b80e1c83..143e41bfb43 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentTypeQuery.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentTypeQuery.cs @@ -23,10 +23,12 @@ public class ContentTypeQuery : ISchemaBuilder private readonly IOptions _settingsAccessor; protected readonly IStringLocalizer S; - public ContentTypeQuery(IHttpContextAccessor httpContextAccessor, + public ContentTypeQuery( + IHttpContextAccessor httpContextAccessor, IOptions contentOptionsAccessor, IOptions settingsAccessor, - IStringLocalizer localizer) + IStringLocalizer localizer + ) { _httpContextAccessor = httpContextAccessor; _contentOptionsAccessor = contentOptionsAccessor; @@ -54,11 +56,7 @@ public async Task BuildAsync(ISchema schema) continue; } - var typeType = new ContentItemType(_contentOptionsAccessor) - { - Name = typeDefinition.Name, - Description = S["Represents a {0}.", typeDefinition.DisplayName] - }; + var typeType = new ContentItemType(_contentOptionsAccessor) { Name = typeDefinition.Name, Description = S["Represents a {0}.", typeDefinition.DisplayName] }; var query = new ContentItemsFieldType(typeDefinition.Name, schema, _contentOptionsAccessor, _settingsAccessor) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/GraphQLFilter.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/GraphQLFilter.cs index ccd9c1362e0..89abb270666 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/GraphQLFilter.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/GraphQLFilter.cs @@ -5,7 +5,8 @@ namespace OrchardCore.ContentManagement.GraphQL.Queries { - public abstract class GraphQLFilter : IGraphQLFilter where TSourceType : class + public abstract class GraphQLFilter : IGraphQLFilter + where TSourceType : class { public virtual Task> PreQueryAsync(IQuery query, IResolveFieldContext context) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IGraphQLFilter.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IGraphQLFilter.cs index af7a0c5254d..a406d8aa330 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IGraphQLFilter.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IGraphQLFilter.cs @@ -5,7 +5,8 @@ namespace OrchardCore.ContentManagement.GraphQL.Queries { - public interface IGraphQLFilter where TSourceType : class + public interface IGraphQLFilter + where TSourceType : class { Task> PreQueryAsync(IQuery query, IResolveFieldContext context); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexAlias.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexAlias.cs index 838a7cfa82c..37f5cae1f96 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexAlias.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexAlias.cs @@ -11,4 +11,3 @@ public class IndexAlias public Type IndexType { get; set; } } } - diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexPropertyProvider.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexPropertyProvider.cs index c2eec78ffc9..256433f27af 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexPropertyProvider.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexPropertyProvider.cs @@ -5,7 +5,8 @@ namespace OrchardCore.ContentManagement.GraphQL.Queries { - public class IndexPropertyProvider : IIndexPropertyProvider where T : MapIndex + public class IndexPropertyProvider : IIndexPropertyProvider + where T : MapIndex { private static readonly Dictionary _indexProperties = new(StringComparer.OrdinalIgnoreCase); private static readonly string _indexName; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/AndExpression.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/AndExpression.cs index c5b10420112..86c922ca5be 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/AndExpression.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/AndExpression.cs @@ -12,9 +12,8 @@ public class AndExpression : LogicalExpression /// /// The left hand side . /// The right hand side . - public AndExpression(IPredicate left, IPredicate right) : base(left, right) - { - } + public AndExpression(IPredicate left, IPredicate right) + : base(left, right) { } /// /// Returns "and". diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Expression.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Expression.cs index 23eaa85344c..af450147a68 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Expression.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Expression.cs @@ -7,9 +7,7 @@ namespace OrchardCore.ContentManagement.GraphQL.Queries.Predicates public class Expression { /// Constructs a new instance of . - protected Expression() - { - } + protected Expression() { } /// /// Apply an "equal" constraint to the named property. diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/InExpression.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/InExpression.cs index 75013084534..05c1aa242f8 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/InExpression.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/InExpression.cs @@ -25,7 +25,8 @@ public void SearchUsedAlias(IPredicateQuery predicateQuery) public string ToSqlString(IPredicateQuery predicateQuery) { // 'columnName in ()' is always false - if (Values.Length == 0) return "1=0"; + if (Values.Length == 0) + return "1=0"; // Generates: // columnName in (@p1, @p2, @p3) @@ -35,7 +36,8 @@ public string ToSqlString(IPredicateQuery predicateQuery) { var parameter = predicateQuery.NewQueryParameter(Values[i]); - if (i > 0) array.Append(", "); + if (i > 0) + array.Append(", "); array.Append(parameter); } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Junction.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Junction.cs index 01d79ad4809..67021fa8d27 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Junction.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Junction.cs @@ -23,19 +23,19 @@ public abstract class Junction : IPredicate public void SearchUsedAlias(IPredicateQuery predicateQuery) { - if (_predicates.Count == 0) return; - + if (_predicates.Count == 0) + return; for (var i = 0; i < _predicates.Count; i++) { _predicates[i].SearchUsedAlias(predicateQuery); } - } public string ToSqlString(IPredicateQuery predicateQuery) { - if (_predicates.Count == 0) return EmptyExpression; + if (_predicates.Count == 0) + return EmptyExpression; var sqlBuilder = new StringBuilder(); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/LikeExpression.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/LikeExpression.cs index 1ef8d49b054..def8c3523b8 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/LikeExpression.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/LikeExpression.cs @@ -9,9 +9,7 @@ public class LikeExpression : IPredicate private readonly string _value; public LikeExpression(string propertyName, string value, MatchOptions matchOptions) - : this(propertyName, matchOptions.ToMatchString(value)) - { - } + : this(propertyName, matchOptions.ToMatchString(value)) { } public LikeExpression(string propertyName, string value) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/OrExpression.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/OrExpression.cs index 95275e2ba48..da5b36c16a7 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/OrExpression.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/OrExpression.cs @@ -12,9 +12,8 @@ public class OrExpression : LogicalExpression /// /// The left hand side . /// The right hand side . - public OrExpression(IPredicate left, IPredicate right) : base(left, right) - { - } + public OrExpression(IPredicate left, IPredicate right) + : base(left, right) { } /// /// Returns "or". diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/PredicateQuery.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/PredicateQuery.cs index e4acee87f10..804562ffb86 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/PredicateQuery.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/PredicateQuery.cs @@ -14,9 +14,7 @@ public class PredicateQuery : IPredicateQuery private readonly Dictionary _aliases = []; private readonly Dictionary _tableAliases = []; - public PredicateQuery( - IConfiguration configuration, - IEnumerable propertyProviders) + public PredicateQuery(IConfiguration configuration, IEnumerable propertyProviders) { Dialect = configuration.SqlDialect; _configuration = configuration; @@ -27,7 +25,6 @@ public PredicateQuery( public IDictionary Parameters { get; } = new Dictionary(); - public string NewQueryParameter(object value) { var count = Parameters.Count; @@ -46,6 +43,7 @@ public void CreateAlias(string path, string alias) _aliases[path] = alias; } + public void CreateTableAlias(string path, string tableAlias) { ArgumentNullException.ThrowIfNull(path); @@ -55,7 +53,6 @@ public void CreateTableAlias(string path, string tableAlias) _tableAliases[path] = tableAlias; } - public void SearchUsedAlias(string propertyPath) { ArgumentNullException.ThrowIfNull(propertyPath); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/PublicationStatusGraphType.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/PublicationStatusGraphType.cs index 8dcefd2e92d..9c24cadc0f4 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/PublicationStatusGraphType.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/PublicationStatusGraphType.cs @@ -4,7 +4,6 @@ namespace OrchardCore.ContentManagement.GraphQL.Queries; public class PublicationStatusGraphType : EnumerationGraphType { - public PublicationStatusGraphType() { Name = "Status"; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/ContentItemType.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/ContentItemType.cs index 61baf94f252..fa60b9e5094 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/ContentItemType.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/ContentItemType.cs @@ -35,8 +35,7 @@ public ContentItemType(IOptions optionsAccessor) Field(ci => ci.Owner).Description("The owner of the content item"); Field(ci => ci.Author).Description("The author of the content item"); - Field("render") - .ResolveLockedAsync(RenderShapeAsync); + Field("render").ResolveLockedAsync(RenderShapeAsync); Interface(); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/DynamicContentTypeBuilder.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/DynamicContentTypeBuilder.cs index 279cfab714c..52b22efdadd 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/DynamicContentTypeBuilder.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/DynamicContentTypeBuilder.cs @@ -17,9 +17,11 @@ public class DynamicContentTypeBuilder : IContentTypeBuilder protected readonly IStringLocalizer S; private readonly Dictionary _dynamicPartFields; - public DynamicContentTypeBuilder(IHttpContextAccessor httpContextAccessor, + public DynamicContentTypeBuilder( + IHttpContextAccessor httpContextAccessor, IOptions contentOptionsAccessor, - IStringLocalizer localizer) + IStringLocalizer localizer + ) { _httpContextAccessor = httpContextAccessor; _contentOptions = contentOptionsAccessor.Value; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/TypedContentTypeBuilder.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/TypedContentTypeBuilder.cs index e4a72031eee..eeb0dc99e58 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/TypedContentTypeBuilder.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/TypedContentTypeBuilder.cs @@ -21,8 +21,7 @@ public class TypedContentTypeBuilder : IContentTypeBuilder private readonly IHttpContextAccessor _httpContextAccessor; private readonly GraphQLContentOptions _contentOptions; - public TypedContentTypeBuilder(IHttpContextAccessor httpContextAccessor, - IOptions contentOptionsAccessor) + public TypedContentTypeBuilder(IHttpContextAccessor httpContextAccessor, IOptions contentOptionsAccessor) { _httpContextAccessor = httpContextAccessor; _contentOptions = contentOptionsAccessor.Value; @@ -57,13 +56,13 @@ public void Build(FieldType contentQuery, ContentTypeDefinition contentTypeDefin } var partType = _partTypes.GetOrAdd(part.PartDefinition.Name, key => typeActivator.GetTypeActivator(key).Type); - var queryGraphType = _partObjectGraphTypes - .GetOrAdd(part.PartDefinition.Name, - partName => - { - return queryObjectGraphTypes.FirstOrDefault(x => x.GetType().BaseType.GetGenericArguments().First().Name == partName); - } - ); + var queryGraphType = _partObjectGraphTypes.GetOrAdd( + part.PartDefinition.Name, + partName => + { + return queryObjectGraphTypes.FirstOrDefault(x => x.GetType().BaseType.GetGenericArguments().First().Name == partName); + } + ); var collapsePart = _contentOptions.ShouldCollapse(part); @@ -90,14 +89,16 @@ public void Build(FieldType contentQuery, ContentTypeDefinition contentTypeDefin var nameToResolve = partName; var resolvedPart = context.Source.Get(partType, nameToResolve); - return field.Resolver.ResolveAsync(new ResolveFieldContext - { - Arguments = context.Arguments, - Source = resolvedPart, - FieldDefinition = field, - UserContext = context.UserContext, - RequestServices = context.RequestServices - }); + return field.Resolver.ResolveAsync( + new ResolveFieldContext + { + Arguments = context.Arguments, + Source = resolvedPart, + FieldDefinition = field, + UserContext = context.UserContext, + RequestServices = context.RequestServices + } + ); }) }; @@ -112,22 +113,26 @@ public void Build(FieldType contentQuery, ContentTypeDefinition contentTypeDefin Type = queryGraphType.GetType(), Description = queryGraphType.Description, }; - contentItemType.Field(partName.ToFieldName(), queryGraphType.GetType()) - .Description(queryGraphType.Description) - .Resolve(context => - { - var nameToResolve = partName; - var typeToResolve = context.FieldDefinition.ResolvedType.GetType().BaseType.GetGenericArguments().First(); - - return context.Source.Get(typeToResolve, nameToResolve); - }); + contentItemType + .Field(partName.ToFieldName(), queryGraphType.GetType()) + .Description(queryGraphType.Description) + .Resolve(context => + { + var nameToResolve = partName; + var typeToResolve = context.FieldDefinition.ResolvedType.GetType().BaseType.GetGenericArguments().First(); + + return context.Source.Get(typeToResolve, nameToResolve); + }); } } - var inputGraphTypeResolved = _partInputObjectGraphTypes.GetOrAdd(part.PartDefinition.Name, partName => - { - return queryInputGraphTypes.FirstOrDefault(x => x.GetType().BaseType.GetGenericArguments().FirstOrDefault()?.Name == part.PartDefinition.Name); - }); + var inputGraphTypeResolved = _partInputObjectGraphTypes.GetOrAdd( + part.PartDefinition.Name, + partName => + { + return queryInputGraphTypes.FirstOrDefault(x => x.GetType().BaseType.GetGenericArguments().FirstOrDefault()?.Name == part.PartDefinition.Name); + } + ); if (inputGraphTypeResolved != null) { @@ -148,12 +153,14 @@ public void Build(FieldType contentQuery, ContentTypeDefinition contentTypeDefin } else { - whereInput.AddField(new FieldType - { - Type = inputGraphTypeResolved.GetType(), - Name = partName.ToFieldName(), - Description = inputGraphTypeResolved.Description - }.WithPartNameMetaData(partName)); + whereInput.AddField( + new FieldType + { + Type = inputGraphTypeResolved.GetType(), + Name = partName.ToFieldName(), + Description = inputGraphTypeResolved.Description + }.WithPartNameMetaData(partName) + ); } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement/CompiledQueries/PublishedContentItemById.cs b/src/OrchardCore/OrchardCore.ContentManagement/CompiledQueries/PublishedContentItemById.cs index 5dbbb4bc717..99e3f9b3d07 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/CompiledQueries/PublishedContentItemById.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/CompiledQueries/PublishedContentItemById.cs @@ -16,9 +16,7 @@ public PublishedContentItemById(string contentItemId) public Expression, IQuery>> Query() { - return query => query - .With() - .Where(x => x.ContentItemId == ContentItemId && x.Published == true); + return query => query.With().Where(x => x.ContentItemId == ContentItemId && x.Published == true); } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement/ContentDefinitionManager.cs b/src/OrchardCore/OrchardCore.ContentManagement/ContentDefinitionManager.cs index 96b5ded5d7c..85108f6f2dc 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/ContentDefinitionManager.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/ContentDefinitionManager.cs @@ -25,15 +25,19 @@ public class ContentDefinitionManager : IContentDefinitionManager private readonly Dictionary _scopedTypeDefinitions = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _scopedPartDefinitions = new(StringComparer.OrdinalIgnoreCase); - public ContentDefinitionManager( - IContentDefinitionStore contentDefinitionStore, - IMemoryCache memoryCache) + public ContentDefinitionManager(IContentDefinitionStore contentDefinitionStore, IMemoryCache memoryCache) { _contentDefinitionStore = contentDefinitionStore; _memoryCache = memoryCache; - _cachedTypeDefinitions = _memoryCache.GetOrCreate("TypeDefinitions", entry => new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase)); - _cachedPartDefinitions = _memoryCache.GetOrCreate("PartDefinitions", entry => new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase)); + _cachedTypeDefinitions = _memoryCache.GetOrCreate( + "TypeDefinitions", + entry => new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase) + ); + _cachedPartDefinitions = _memoryCache.GetOrCreate( + "PartDefinitions", + entry => new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase) + ); } public async Task> LoadTypeDefinitionsAsync() @@ -141,12 +145,9 @@ public async Task DeletePartDefinitionAsync(string name) var document = await _contentDefinitionStore.LoadContentDefinitionAsync(); // Remove parts from current types. - var typeDefinitions = document.ContentTypeDefinitionRecords - .Select(type => LoadTypeDefinition(document, type.Name)).ToList(); + var typeDefinitions = document.ContentTypeDefinitionRecords.Select(type => LoadTypeDefinition(document, type.Name)).ToList(); - var typesWithPart = typeDefinitions - .Where(typeDefinition => typeDefinition.Parts - .Any(part => part.PartDefinition.Name.EqualsOrdinalIgnoreCase(name))); + var typesWithPart = typeDefinitions.Where(typeDefinition => typeDefinition.Parts.Any(part => part.PartDefinition.Name.EqualsOrdinalIgnoreCase(name))); foreach (var typeDefinition in typesWithPart) { @@ -184,40 +185,33 @@ public async Task StorePartDefinitionAsync(ContentPartDefinition contentPartDefi private ContentTypeDefinition LoadTypeDefinition(ContentDefinitionRecord document, string name) => !_scopedTypeDefinitions.TryGetValue(name, out var typeDefinition) - ? _scopedTypeDefinitions[name] = Build( - document.ContentTypeDefinitionRecords.FirstOrDefault(type => type.Name.EqualsOrdinalIgnoreCase(name)), - document.ContentPartDefinitionRecords) - : typeDefinition; + ? _scopedTypeDefinitions[name] = Build( + document.ContentTypeDefinitionRecords.FirstOrDefault(type => type.Name.EqualsOrdinalIgnoreCase(name)), + document.ContentPartDefinitionRecords + ) + : typeDefinition; private ContentTypeDefinition GetTypeDefinition(ContentDefinitionRecord document, string name) => - _cachedTypeDefinitions.GetOrAdd(name, name => Build( - document.ContentTypeDefinitionRecords.FirstOrDefault(type => type.Name.EqualsOrdinalIgnoreCase(name)), - document.ContentPartDefinitionRecords)); + _cachedTypeDefinitions.GetOrAdd( + name, + name => Build(document.ContentTypeDefinitionRecords.FirstOrDefault(type => type.Name.EqualsOrdinalIgnoreCase(name)), document.ContentPartDefinitionRecords) + ); private ContentPartDefinition LoadPartDefinition(ContentDefinitionRecord document, string name) => !_scopedPartDefinitions.TryGetValue(name, out var partDefinition) - ? _scopedPartDefinitions[name] = Build( - document.ContentPartDefinitionRecords.FirstOrDefault(part => part.Name.EqualsOrdinalIgnoreCase(name))) - : partDefinition; + ? _scopedPartDefinitions[name] = Build(document.ContentPartDefinitionRecords.FirstOrDefault(part => part.Name.EqualsOrdinalIgnoreCase(name))) + : partDefinition; private ContentPartDefinition GetPartDefinition(ContentDefinitionRecord document, string name) => - _cachedPartDefinitions.GetOrAdd(name, name => Build( - document.ContentPartDefinitionRecords.FirstOrDefault(record => record.Name.EqualsOrdinalIgnoreCase(name)))); + _cachedPartDefinitions.GetOrAdd(name, name => Build(document.ContentPartDefinitionRecords.FirstOrDefault(record => record.Name.EqualsOrdinalIgnoreCase(name)))); - private static ContentTypeDefinitionRecord Acquire( - ContentDefinitionRecord document, - ContentTypeDefinition contentTypeDefinition) + private static ContentTypeDefinitionRecord Acquire(ContentDefinitionRecord document, ContentTypeDefinition contentTypeDefinition) { - var result = document.ContentTypeDefinitionRecords - .FirstOrDefault(type => type.Name.EqualsOrdinalIgnoreCase(contentTypeDefinition.Name)); + var result = document.ContentTypeDefinitionRecords.FirstOrDefault(type => type.Name.EqualsOrdinalIgnoreCase(contentTypeDefinition.Name)); if (result is null) { - result = new ContentTypeDefinitionRecord - { - Name = contentTypeDefinition.Name, - DisplayName = contentTypeDefinition.DisplayName, - }; + result = new ContentTypeDefinitionRecord { Name = contentTypeDefinition.Name, DisplayName = contentTypeDefinition.DisplayName, }; document.ContentTypeDefinitionRecords.Add(result); } @@ -225,19 +219,13 @@ private static ContentTypeDefinitionRecord Acquire( return result; } - private static ContentPartDefinitionRecord Acquire( - ContentDefinitionRecord document, - ContentPartDefinition contentPartDefinition) + private static ContentPartDefinitionRecord Acquire(ContentDefinitionRecord document, ContentPartDefinition contentPartDefinition) { - var result = document.ContentPartDefinitionRecords - .FirstOrDefault(part => part.Name.EqualsOrdinalIgnoreCase(contentPartDefinition.Name)); + var result = document.ContentPartDefinitionRecords.FirstOrDefault(part => part.Name.EqualsOrdinalIgnoreCase(contentPartDefinition.Name)); if (result is null) { - result = new ContentPartDefinitionRecord - { - Name = contentPartDefinition.Name, - }; + result = new ContentPartDefinitionRecord { Name = contentPartDefinition.Name, }; document.ContentPartDefinitionRecords.Add(result); } @@ -250,9 +238,10 @@ private static void Apply(ContentTypeDefinition model, ContentTypeDefinitionReco record.DisplayName = model.DisplayName; record.Settings = model.Settings; - var toRemove = record.ContentTypePartDefinitionRecords - .Where(typePartDefinitionRecord => !model.Parts - .Any(typePart => typePart.Name.EqualsOrdinalIgnoreCase(typePartDefinitionRecord.Name))) + var toRemove = record + .ContentTypePartDefinitionRecords.Where(typePartDefinitionRecord => + !model.Parts.Any(typePart => typePart.Name.EqualsOrdinalIgnoreCase(typePartDefinitionRecord.Name)) + ) .ToList(); foreach (var remove in toRemove) @@ -262,8 +251,7 @@ private static void Apply(ContentTypeDefinition model, ContentTypeDefinitionReco foreach (var part in model.Parts) { - var typePartRecord = record.ContentTypePartDefinitionRecords - .FirstOrDefault(typePart => typePart.Name.EqualsOrdinalIgnoreCase(part.Name)); + var typePartRecord = record.ContentTypePartDefinitionRecords.FirstOrDefault(typePart => typePart.Name.EqualsOrdinalIgnoreCase(part.Name)); if (typePartRecord is null) { @@ -281,16 +269,16 @@ private static void Apply(ContentTypeDefinition model, ContentTypeDefinitionReco } } - private static void Apply(ContentTypePartDefinition model, ContentTypePartDefinitionRecord record) - => record.Settings = model.Settings; + private static void Apply(ContentTypePartDefinition model, ContentTypePartDefinitionRecord record) => record.Settings = model.Settings; private static void Apply(ContentPartDefinition model, ContentPartDefinitionRecord record) { record.Settings = model.Settings; - var toRemove = record.ContentPartFieldDefinitionRecords - .Where(partFieldDefinitionRecord => !model.Fields - .Any(partField => partField.Name.EqualsOrdinalIgnoreCase(partFieldDefinitionRecord.Name))) + var toRemove = record + .ContentPartFieldDefinitionRecords.Where(partFieldDefinitionRecord => + !model.Fields.Any(partField => partField.Name.EqualsOrdinalIgnoreCase(partFieldDefinitionRecord.Name)) + ) .ToList(); foreach (var remove in toRemove) @@ -300,23 +288,19 @@ private static void Apply(ContentPartDefinition model, ContentPartDefinitionReco foreach (var field in model.Fields) { - var partFieldRecord = record.ContentPartFieldDefinitionRecords - .FirstOrDefault(partField => partField.Name.EqualsOrdinalIgnoreCase(field.Name)); + var partFieldRecord = record.ContentPartFieldDefinitionRecords.FirstOrDefault(partField => partField.Name.EqualsOrdinalIgnoreCase(field.Name)); if (partFieldRecord is null) { if (field.FieldDefinition is null) { throw new InvalidOperationException( - $"The '{field.Name}' field in '{model.Name}' part was defined without a specified type." + - " Please review the migration and explicitly specify the field type."); + $"The '{field.Name}' field in '{model.Name}' part was defined without a specified type." + + " Please review the migration and explicitly specify the field type." + ); } - partFieldRecord = new ContentPartFieldDefinitionRecord - { - FieldName = field.FieldDefinition.Name, - Name = field.Name, - }; + partFieldRecord = new ContentPartFieldDefinitionRecord { FieldName = field.FieldDefinition.Name, Name = field.Name, }; record.ContentPartFieldDefinitionRecords.Add(partFieldRecord); } @@ -325,53 +309,32 @@ private static void Apply(ContentPartDefinition model, ContentPartDefinitionReco } } - private static void Apply(ContentPartFieldDefinition model, ContentPartFieldDefinitionRecord record) - => record.Settings = model.Settings; + private static void Apply(ContentPartFieldDefinition model, ContentPartFieldDefinitionRecord record) => record.Settings = model.Settings; - private static ContentTypeDefinition Build( - ContentTypeDefinitionRecord source, - IList partDefinitionRecords) => + private static ContentTypeDefinition Build(ContentTypeDefinitionRecord source, IList partDefinitionRecords) => source is not null - ? new ContentTypeDefinition( - source.Name, - source.DisplayName, - source.ContentTypePartDefinitionRecords.Select(typePart => Build( - typePart, - partDefinitionRecords.FirstOrDefault(part => part.Name.EqualsOrdinalIgnoreCase(typePart.PartName)))), - source.Settings) - : null; - - private static ContentTypePartDefinition Build( - ContentTypePartDefinitionRecord source, - ContentPartDefinitionRecord partDefinitionRecord) => + ? new ContentTypeDefinition( + source.Name, + source.DisplayName, + source.ContentTypePartDefinitionRecords.Select(typePart => + Build(typePart, partDefinitionRecords.FirstOrDefault(part => part.Name.EqualsOrdinalIgnoreCase(typePart.PartName))) + ), + source.Settings + ) + : null; + + private static ContentTypePartDefinition Build(ContentTypePartDefinitionRecord source, ContentPartDefinitionRecord partDefinitionRecord) => source is not null - ? new ContentTypePartDefinition( - source.Name, - Build(partDefinitionRecord) ?? new ContentPartDefinition(source.PartName, [], []), - source.Settings) - : null; + ? new ContentTypePartDefinition(source.Name, Build(partDefinitionRecord) ?? new ContentPartDefinition(source.PartName, [], []), source.Settings) + : null; private static ContentPartDefinition Build(ContentPartDefinitionRecord source) => - source is not null - ? new ContentPartDefinition( - source.Name, - source.ContentPartFieldDefinitionRecords.Select(Build), - source.Settings) - : null; + source is not null ? new ContentPartDefinition(source.Name, source.ContentPartFieldDefinitionRecords.Select(Build), source.Settings) : null; private static ContentPartFieldDefinition Build(ContentPartFieldDefinitionRecord source) => - source is not null - ? new ContentPartFieldDefinition( - Build(new ContentFieldDefinitionRecord - { - Name = source.FieldName, - }), - source.Name, - source.Settings) - : null; + source is not null ? new ContentPartFieldDefinition(Build(new ContentFieldDefinitionRecord { Name = source.FieldName, }), source.Name, source.Settings) : null; - private static ContentFieldDefinition Build(ContentFieldDefinitionRecord source) - => source is null ? null : new ContentFieldDefinition(source.Name); + private static ContentFieldDefinition Build(ContentFieldDefinitionRecord source) => source is null ? null : new ContentFieldDefinition(source.Name); private async Task UpdateContentDefinitionRecordAsync(ContentDefinitionRecord document) { @@ -389,10 +352,7 @@ private void CheckDocumentIdentifier(ContentDefinitionRecord document) { if (!_memoryCache.TryGetValue(CacheKey, out var cacheEntry) || cacheEntry.Identifier != document.Identifier) { - cacheEntry = new Document() - { - Identifier = document.Identifier, - }; + cacheEntry = new Document() { Identifier = document.Identifier, }; _cachedTypeDefinitions.Clear(); _cachedPartDefinitions.Clear(); diff --git a/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManager.cs b/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManager.cs index cb1bd57ac49..2e90a191e91 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManager.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManager.cs @@ -38,7 +38,8 @@ public DefaultContentManager( ISession session, IContentItemIdGenerator idGenerator, ILogger logger, - IClock clock) + IClock clock + ) { _contentDefinitionManager = contentDefinitionManager; Handlers = handlers; @@ -92,10 +93,7 @@ public async Task> GetAsync(IEnumerable content { ArgumentNullException.ThrowIfNull(contentItemIds); - var itemIds = contentItemIds - .Where(id => id is not null) - .Distinct() - .ToArray(); + var itemIds = contentItemIds.Where(id => id is not null).Distinct().ToArray(); if (itemIds.Length == 0) { @@ -106,11 +104,7 @@ public async Task> GetAsync(IEnumerable content List storedItems = null; if (latest) { - contentItems = (await _session - .Query() - .Where(i => i.ContentItemId.IsIn(itemIds) && i.Latest == true) - .ListAsync() - ).ToList(); + contentItems = (await _session.Query().Where(i => i.ContentItemId.IsIn(itemIds) && i.Latest == true).ListAsync()).ToList(); } else { @@ -125,17 +119,13 @@ public async Task> GetAsync(IEnumerable content } // Only query the ids not already stored. - var itemIdsToQuery = storedItems is not null - ? itemIds.Except(storedItems.Select(c => c.ContentItemId)).ToArray() - : itemIds; + var itemIdsToQuery = storedItems is not null ? itemIds.Except(storedItems.Select(c => c.ContentItemId)).ToArray() : itemIds; if (itemIdsToQuery.Length > 0) { - contentItems = (await _session - .Query() - .Where(i => i.ContentItemId.IsIn(itemIdsToQuery) && i.Published == true) - .ListAsync() - ).ToList(); + contentItems = ( + await _session.Query().Where(i => i.ContentItemId.IsIn(itemIdsToQuery) && i.Published == true).ListAsync() + ).ToList(); } } @@ -174,30 +164,19 @@ public async Task GetAsync(string contentItemId, VersionOptions opt if (options.IsLatest) { - contentItem = await _session - .Query() - .Where(x => x.ContentItemId == contentItemId && x.Latest == true) - .FirstOrDefaultAsync(); + contentItem = await _session.Query().Where(x => x.ContentItemId == contentItemId && x.Latest == true).FirstOrDefaultAsync(); } else if (options.IsDraft && !options.IsDraftRequired) { contentItem = await _session .Query() - .Where(x => - x.ContentItemId == contentItemId && - x.Published == false && - x.Latest == true) + .Where(x => x.ContentItemId == contentItemId && x.Published == false && x.Latest == true) .FirstOrDefaultAsync(); } else if (options.IsDraft || options.IsDraftRequired) { // Loaded whatever is the latest as it will be cloned - contentItem = await _session - .Query() - .Where(x => - x.ContentItemId == contentItemId && - x.Latest == true) - .FirstOrDefaultAsync(); + contentItem = await _session.Query().Where(x => x.ContentItemId == contentItemId && x.Latest == true).FirstOrDefaultAsync(); } else if (options.IsPublished) { @@ -260,26 +239,16 @@ public async Task> GetAsync(IEnumerable content if (options.IsLatest) { - contentItems = (await _session - .Query() - .Where(x => x.ContentItemId.IsIn(ids) && x.Latest) - .ListAsync() - ).ToList(); + contentItems = (await _session.Query().Where(x => x.ContentItemId.IsIn(ids) && x.Latest).ListAsync()).ToList(); } else if (options.IsDraft && !options.IsDraftRequired) { - contentItems = (await _session - .Query() - .Where(x => x.ContentItemId.IsIn(ids) && !x.Published && x.Latest).ListAsync() - ).ToList(); + contentItems = (await _session.Query().Where(x => x.ContentItemId.IsIn(ids) && !x.Published && x.Latest).ListAsync()).ToList(); } else if (options.IsDraft || options.IsDraftRequired) { // Loaded whatever is the latest as it will be cloned - contentItems = (await _session - .Query() - .Where(x => x.ContentItemId.IsIn(ids) && x.Latest) - .ListAsync()).ToList(); + contentItems = (await _session.Query().Where(x => x.ContentItemId.IsIn(ids) && x.Latest).ListAsync()).ToList(); } else if (options.IsPublished) { @@ -382,9 +351,7 @@ public async Task LoadAsync(ContentItem contentItem) public async Task GetVersionAsync(string contentItemVersionId) { - var contentItem = await _session - .Query(x => x.ContentItemVersionId == contentItemVersionId) - .FirstOrDefaultAsync(); + var contentItem = await _session.Query(x => x.ContentItemVersionId == contentItemVersionId).FirstOrDefaultAsync(); if (contentItem == null) { @@ -420,10 +387,7 @@ public async Task PublishAsync(ContentItem contentItem) // Create a context for the item and it's previous published record // Because of this query the content item will need to be re-enlisted // to be saved. - var previous = await _session - .Query(x => - x.ContentItemId == contentItem.ContentItemId && x.Published) - .FirstOrDefaultAsync(); + var previous = await _session.Query(x => x.ContentItemId == contentItem.ContentItemId && x.Published).FirstOrDefaultAsync(); var context = new PublishContentContext(contentItem, previous); @@ -476,10 +440,7 @@ public async Task UnpublishAsync(ContentItem contentItem) // Create a context for the item. the publishing version is null in this case // and the previous version is the one active prior to unpublishing. handlers // should take this null check into account - var context = new PublishContentContext(contentItem, publishedItem) - { - PublishingItem = null - }; + var context = new PublishContentContext(contentItem, publishedItem) { PublishingItem = null }; await Handlers.InvokeAsync((handler, context) => handler.UnpublishingAsync(context), context, _logger); @@ -500,11 +461,7 @@ protected async Task BuildNewVersionAsync(ContentItem existingConte } else { - latestVersion = await _session - .Query(x => - x.ContentItemId == existingContentItem.ContentItemId && - x.Latest) - .FirstOrDefaultAsync(); + latestVersion = await _session.Query(x => x.ContentItemId == existingContentItem.ContentItemId && x.Latest).FirstOrDefaultAsync(); if (latestVersion != null) { @@ -556,11 +513,7 @@ protected async Task> BuildNewVersionsAsync(IEnumerable if (needingLatestVersion.Count > 0) { - var foundLatestVersions = await _session - .Query(x => - x.ContentItemId.IsIn(needingLatestVersion) && - x.Latest) - .ListAsync(); + var foundLatestVersions = await _session.Query(x => x.ContentItemId.IsIn(needingLatestVersion) && x.Latest).ListAsync(); latestVersions.AddRange(foundLatestVersions); } @@ -656,18 +609,12 @@ public async Task ImportAsync(IEnumerable contentItems) while (batchedContentItems.Any()) { // Preload all the versions for this batch from the database. - var versionIds = batchedContentItems - .Where(x => !string.IsNullOrEmpty(x.ContentItemVersionId)) - .Select(x => x.ContentItemVersionId); + var versionIds = batchedContentItems.Where(x => !string.IsNullOrEmpty(x.ContentItemVersionId)).Select(x => x.ContentItemVersionId); - var itemIds = batchedContentItems - .Where(x => !string.IsNullOrEmpty(x.ContentItemId)) - .Select(x => x.ContentItemId); + var itemIds = batchedContentItems.Where(x => !string.IsNullOrEmpty(x.ContentItemId)).Select(x => x.ContentItemId); var existingContentItems = await _session - .Query(x => - x.ContentItemId.IsIn(itemIds) && - (x.Latest || x.Published || x.ContentItemVersionId.IsIn(versionIds))) + .Query(x => x.ContentItemId.IsIn(itemIds) && (x.Latest || x.Published || x.ContentItemVersionId.IsIn(versionIds))) .ListAsync(); var versionsToUpdate = existingContentItems.Where(c => versionIds.Any(v => string.Equals(v, c.ContentItemVersionId, StringComparison.OrdinalIgnoreCase))); @@ -691,7 +638,9 @@ public async Task ImportAsync(IEnumerable contentItems) importedVersionIds.Add(importingItem.ContentItemVersionId); - originalVersion = versionsToUpdate.FirstOrDefault(x => string.Equals(x.ContentItemVersionId, importingItem.ContentItemVersionId, StringComparison.OrdinalIgnoreCase)); + originalVersion = versionsToUpdate.FirstOrDefault(x => + string.Equals(x.ContentItemVersionId, importingItem.ContentItemVersionId, StringComparison.OrdinalIgnoreCase) + ); } if (originalVersion == null) @@ -707,7 +656,11 @@ public async Task ImportAsync(IEnumerable contentItems) { if (_logger.IsEnabled(LogLevel.Error)) { - _logger.LogError("Error importing content item version id '{ContentItemVersionId}' : '{Errors}'", importingItem?.ContentItemVersionId, string.Join(", ", result.Errors)); + _logger.LogError( + "Error importing content item version id '{ContentItemVersionId}' : '{Errors}'", + importingItem?.ContentItemVersionId, + string.Join(", ", result.Errors) + ); } throw new ValidationException(string.Join(", ", result.Errors)); @@ -760,7 +713,11 @@ public async Task ImportAsync(IEnumerable contentItems) { if (_logger.IsEnabled(LogLevel.Error)) { - _logger.LogError("Error importing content item version id '{ContentItemVersionId}' : '{Errors}'", importingItem.ContentItemVersionId, string.Join(", ", result.Errors)); + _logger.LogError( + "Error importing content item version id '{ContentItemVersionId}' : '{Errors}'", + importingItem.ContentItemVersionId, + string.Join(", ", result.Errors) + ); } throw new ValidationException(string.Join(", ", result.Errors)); @@ -827,7 +784,8 @@ public async Task RestoreAsync(ContentItem contentItem) } // Remove an existing draft but keep an existing published version. - var latestVersion = await _session.Query() + var latestVersion = await _session + .Query() .Where(index => index.ContentItemId == contentItem.ContentItemId && index.Latest) .FirstOrDefaultAsync(); @@ -846,11 +804,7 @@ public async Task RestoreAsync(ContentItem contentItem) public async Task PopulateAspectAsync(IContent content, TAspect aspect) { - var context = new ContentItemAspectContext - { - ContentItem = content.ContentItem, - Aspect = aspect - }; + var context = new ContentItemAspectContext { ContentItem = content.ContentItem, Aspect = aspect }; await Handlers.InvokeAsync((handler, context) => handler.GetContentItemAspectAsync(context), context, _logger); @@ -859,10 +813,10 @@ public async Task PopulateAspectAsync(IContent content, TAspec public async Task RemoveAsync(ContentItem contentItem) { - var activeVersions = await _session.Query() - .Where(x => - x.ContentItemId == contentItem.ContentItemId && - (x.Published || x.Latest)).ListAsync(); + var activeVersions = await _session + .Query() + .Where(x => x.ContentItemId == contentItem.ContentItemId && (x.Published || x.Latest)) + .ListAsync(); if (!activeVersions.Any()) { @@ -1022,7 +976,11 @@ private async Task CreateContentItemVersionAsync(ContentI return result; } - private async Task UpdateContentItemVersionAsync(ContentItem updatingVersion, ContentItem updatedVersion, IEnumerable evictionVersions = null) + private async Task UpdateContentItemVersionAsync( + ContentItem updatingVersion, + ContentItem updatedVersion, + IEnumerable evictionVersions = null + ) { // Replaces the id to force the current item to be updated updatingVersion.Id = updatedVersion.Id; @@ -1111,9 +1069,7 @@ private async Task RemoveLatestVersionAsync(ContentItem contentItem, IEnumerable ContentItem latestVersion; if (evictionVersions == null) { - latestVersion = await _session.Query() - .Where(x => x.ContentItemId == contentItem.ContentItemId && x.Latest) - .FirstOrDefaultAsync(); + latestVersion = await _session.Query().Where(x => x.ContentItemId == contentItem.ContentItemId && x.Latest).FirstOrDefaultAsync(); } else { @@ -1140,7 +1096,8 @@ private async Task RemovePublishedVersionAsync(ContentItem contentItem, IEnumera ContentItem publishedVersion; if (evictionVersions == null) { - publishedVersion = await _session.Query() + publishedVersion = await _session + .Query() .Where(x => x.ContentItemId == contentItem.ContentItemId && x.Published) .FirstOrDefaultAsync(); } @@ -1167,10 +1124,10 @@ private async Task RemoveVersionsAsync(ContentItem contentItem, IEnumerable activeVersions; if (evictionVersions == null) { - activeVersions = await _session.Query() - .Where(x => - x.ContentItemId == contentItem.ContentItemId && - (x.Published || x.Latest)).ListAsync(); + activeVersions = await _session + .Query() + .Where(x => x.ContentItemId == contentItem.ContentItemId && (x.Published || x.Latest)) + .ListAsync(); } else { diff --git a/src/OrchardCore/OrchardCore.ContentManagement/GenericTypeActivator.cs b/src/OrchardCore/OrchardCore.ContentManagement/GenericTypeActivator.cs index 8e076e701c2..7f4a465a598 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/GenericTypeActivator.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/GenericTypeActivator.cs @@ -2,7 +2,8 @@ namespace OrchardCore.ContentManagement { - internal class GenericTypeActivator : ITypeActivator where T : TInstance, new() + internal class GenericTypeActivator : ITypeActivator + where T : TInstance, new() { /// public Type Type => typeof(T); diff --git a/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentFieldHandlerResolver.cs b/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentFieldHandlerResolver.cs index 142a097aa9e..0a9a5564913 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentFieldHandlerResolver.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentFieldHandlerResolver.cs @@ -10,10 +10,7 @@ public class ContentFieldHandlerResolver : IContentFieldHandlerResolver private readonly IServiceProvider _serviceProvider; private readonly ContentOptions _contentOptions; - public ContentFieldHandlerResolver( - IServiceProvider serviceProvider, - IOptions contentDisplayOptions - ) + public ContentFieldHandlerResolver(IServiceProvider serviceProvider, IOptions contentDisplayOptions) { _serviceProvider = serviceProvider; _contentOptions = contentDisplayOptions.Value; diff --git a/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentPartHandlerCoordinator.cs b/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentPartHandlerCoordinator.cs index e87d803e331..4f24a77ae1f 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentPartHandlerCoordinator.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentPartHandlerCoordinator.cs @@ -24,7 +24,8 @@ public ContentPartHandlerCoordinator( ITypeActivatorFactory contentPartFactory, ITypeActivatorFactory contentFieldFactory, IContentDefinitionManager contentDefinitionManager, - ILogger logger) + ILogger logger + ) { _contentPartHandlerResolver = contentPartHandlerResolver; _contentFieldHandlerResolver = contentFieldHandlerResolver; @@ -41,74 +42,98 @@ public override Task ActivatingAsync(ActivatingContentContext context) // When a part/field does not exists, we create the part from it's known type or from a generic one var fieldContext = new ActivatingContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.ActivatingAsync(context, part), (handler, context, field) => handler.ActivatingAsync(fieldContext, field), createPartIfNotExists: true, - createFieldIfNotExists: true); + createFieldIfNotExists: true + ); } public override Task ActivatedAsync(ActivatedContentContext context) { var fieldContext = new ActivatedContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.ActivatedAsync(context, part), - (handler, context, field) => handler.ActivatedAsync(fieldContext, field)); + (handler, context, field) => handler.ActivatedAsync(fieldContext, field) + ); } public override Task CreatingAsync(CreateContentContext context) { var fieldContext = new CreateContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.CreatingAsync(context, part), - (handler, context, field) => handler.CreatingAsync(fieldContext, field)); + (handler, context, field) => handler.CreatingAsync(fieldContext, field) + ); } public override Task CreatedAsync(CreateContentContext context) { var fieldContext = new CreateContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.CreatedAsync(context, part), - (handler, context, field) => handler.CreatedAsync(fieldContext, field)); + (handler, context, field) => handler.CreatedAsync(fieldContext, field) + ); } public override Task ImportingAsync(ImportContentContext context) { var fieldContext = new ImportContentFieldContext(context.ContentItem, context.OriginalContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.ImportingAsync(context, part), - (handler, context, field) => handler.ImportingAsync(fieldContext, field)); + (handler, context, field) => handler.ImportingAsync(fieldContext, field) + ); } public override Task ImportedAsync(ImportContentContext context) { var fieldContext = new ImportContentFieldContext(context.ContentItem, context.OriginalContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.ImportedAsync(context, part), - (handler, context, field) => handler.ImportedAsync(fieldContext, field)); + (handler, context, field) => handler.ImportedAsync(fieldContext, field) + ); } public override Task InitializingAsync(InitializingContentContext context) { var fieldContext = new InitializingContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.InitializingAsync(context, part), - (handler, context, field) => handler.InitializingAsync(fieldContext, field)); + (handler, context, field) => handler.InitializingAsync(fieldContext, field) + ); } public override Task InitializedAsync(InitializingContentContext context) { var fieldContext = new InitializingContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.InitializedAsync(context, part), - (handler, context, field) => handler.InitializedAsync(fieldContext, field)); + (handler, context, field) => handler.InitializedAsync(fieldContext, field) + ); } public override Task LoadingAsync(LoadContentContext context) @@ -119,142 +144,188 @@ public override Task LoadingAsync(LoadContentContext context) // like edited. var fieldContext = new LoadContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.LoadingAsync(context, part), (handler, context, field) => handler.LoadingAsync(fieldContext, field), createPartIfNotExists: true, - createFieldIfNotExists: true); + createFieldIfNotExists: true + ); } public override Task LoadedAsync(LoadContentContext context) { var fieldContext = new LoadContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.LoadedAsync(context, part), - (handler, context, field) => handler.LoadedAsync(fieldContext, field)); + (handler, context, field) => handler.LoadedAsync(fieldContext, field) + ); } public override Task ValidatingAsync(ValidateContentContext context) { - return InvokeHandlers(context, + return InvokeHandlers( + context, (handler, context, part) => handler.ValidatingAsync(context, part), - (handler, context, field) => handler.ValidatingAsync(context, field)); + (handler, context, field) => handler.ValidatingAsync(context, field) + ); } public override Task ValidatedAsync(ValidateContentContext context) { - return InvokeHandlers(context, + return InvokeHandlers( + context, (handler, context, part) => handler.ValidatedAsync(context, part), - (handler, context, field) => handler.ValidatedAsync(new ValidateContentFieldContext(context.ContentItem), field)); + (handler, context, field) => handler.ValidatedAsync(new ValidateContentFieldContext(context.ContentItem), field) + ); } public override Task DraftSavingAsync(SaveDraftContentContext context) { var fieldContext = new SaveDraftContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.DraftSavingAsync(context, part), - (handler, context, field) => handler.DraftSavingAsync(fieldContext, field)); + (handler, context, field) => handler.DraftSavingAsync(fieldContext, field) + ); } public override Task DraftSavedAsync(SaveDraftContentContext context) { var fieldContext = new SaveDraftContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.DraftSavedAsync(context, part), - (handler, context, field) => handler.DraftSavedAsync(fieldContext, field)); + (handler, context, field) => handler.DraftSavedAsync(fieldContext, field) + ); } public override Task PublishingAsync(PublishContentContext context) { var fieldContext = new PublishContentFieldContext(context.ContentItem, context.PreviousItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.PublishingAsync(context, part), - (handler, context, field) => handler.PublishingAsync(fieldContext, field)); + (handler, context, field) => handler.PublishingAsync(fieldContext, field) + ); } public override Task PublishedAsync(PublishContentContext context) { var fieldContext = new PublishContentFieldContext(context.ContentItem, context.PreviousItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.PublishedAsync(context, part), - (handler, context, field) => handler.PublishedAsync(fieldContext, field)); + (handler, context, field) => handler.PublishedAsync(fieldContext, field) + ); } public override Task RemovingAsync(RemoveContentContext context) { var fieldContext = new RemoveContentFieldContext(context.ContentItem, context.NoActiveVersionLeft); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.RemovingAsync(context, part), - (handler, context, field) => handler.RemovingAsync(fieldContext, field)); + (handler, context, field) => handler.RemovingAsync(fieldContext, field) + ); } public override Task RemovedAsync(RemoveContentContext context) { var fieldContext = new RemoveContentFieldContext(context.ContentItem, context.NoActiveVersionLeft); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.RemovedAsync(context, part), - (handler, context, field) => handler.RemovedAsync(fieldContext, field)); + (handler, context, field) => handler.RemovedAsync(fieldContext, field) + ); } public override Task UnpublishingAsync(PublishContentContext context) { var fieldContext = new PublishContentFieldContext(context.ContentItem, context.PreviousItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.UnpublishingAsync(context, part), - (handler, context, field) => handler.UnpublishingAsync(fieldContext, field)); + (handler, context, field) => handler.UnpublishingAsync(fieldContext, field) + ); } public override Task UnpublishedAsync(PublishContentContext context) { var fieldContext = new PublishContentFieldContext(context.ContentItem, context.PreviousItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.UnpublishedAsync(context, part), - (handler, context, field) => handler.UnpublishedAsync(fieldContext, field)); + (handler, context, field) => handler.UnpublishedAsync(fieldContext, field) + ); } public override Task UpdatingAsync(UpdateContentContext context) { var fieldContext = new UpdateContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.UpdatingAsync(context, part), - (handler, context, field) => handler.UpdatingAsync(fieldContext, field)); + (handler, context, field) => handler.UpdatingAsync(fieldContext, field) + ); } public override Task UpdatedAsync(UpdateContentContext context) { var fieldContext = new UpdateContentFieldContext(context.ContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.UpdatedAsync(context, part), - (handler, context, field) => handler.UpdatedAsync(fieldContext, field)); + (handler, context, field) => handler.UpdatedAsync(fieldContext, field) + ); } public override Task VersioningAsync(VersionContentContext context) { var fieldContext = new VersionContentFieldContext(context.ContentItem, context.BuildingContentItem); - return InvokeHandlers(context, fieldContext, - (handler, context, existingPart, buildingPart) => handler.VersioningAsync(context, existingPart, buildingPart), - (handler, context, existingField, buildingField) => handler.VersioningAsync(fieldContext, existingField, buildingField)); + return InvokeHandlers( + context, + fieldContext, + (handler, context, existingPart, buildingPart) => handler.VersioningAsync(context, existingPart, buildingPart), + (handler, context, existingField, buildingField) => handler.VersioningAsync(fieldContext, existingField, buildingField) + ); } public override Task VersionedAsync(VersionContentContext context) { var fieldContext = new VersionContentFieldContext(context.ContentItem, context.BuildingContentItem); - return InvokeHandlers(context, fieldContext, - (handler, context, existingPart, buildingPart) => handler.VersionedAsync(context, existingPart, buildingPart), - (handler, context, existingField, buildingField) => handler.VersionedAsync(fieldContext, existingField, buildingField)); + return InvokeHandlers( + context, + fieldContext, + (handler, context, existingPart, buildingPart) => handler.VersionedAsync(context, existingPart, buildingPart), + (handler, context, existingField, buildingField) => handler.VersionedAsync(fieldContext, existingField, buildingField) + ); } public override async Task GetContentItemAspectAsync(ContentItemAspectContext context) @@ -305,17 +376,24 @@ public override Task ClonedAsync(CloneContentContext context) { var fieldContext = new CloneContentFieldContext(context.ContentItem, context.CloneContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.ClonedAsync(context, part), - (handler, context, field) => handler.ClonedAsync(fieldContext, field)); + (handler, context, field) => handler.ClonedAsync(fieldContext, field) + ); } + public override Task CloningAsync(CloneContentContext context) { var fieldContext = new CloneContentFieldContext(context.ContentItem, context.CloneContentItem); - return InvokeHandlers(context, fieldContext, + return InvokeHandlers( + context, + fieldContext, (handler, context, part) => handler.CloningAsync(context, part), - (handler, context, field) => handler.CloningAsync(fieldContext, field)); + (handler, context, field) => handler.CloningAsync(fieldContext, field) + ); } private async Task InvokeHandlers( @@ -324,7 +402,8 @@ private async Task InvokeHandlers( Func partHandlerAction, Func fieldHandlerAction, bool createPartIfNotExists = false, - bool createFieldIfNotExists = false) + bool createFieldIfNotExists = false + ) where TContext : ContentContextBase where TFieldContext : ContentFieldContextBase { @@ -392,10 +471,10 @@ private async Task InvokeHandlers( TContext context, TFieldContext fieldContext, Func partHandlerAction, - Func fieldHandlerAction) + Func fieldHandlerAction + ) where TContext : VersionContentContext where TFieldContext : VersionContentFieldContext - { var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(context.ContentItem.ContentType); if (contentTypeDefinition == null) @@ -450,7 +529,8 @@ private async Task InvokeHandlers( private async Task InvokeHandlers( TContext context, Func partHandlerAction, - Func fieldHandlerAction) + Func fieldHandlerAction + ) where TContext : ValidateContentContext { var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(context.ContentItem.ContentType); @@ -472,10 +552,7 @@ private async Task InvokeHandlers( var partHandlers = _contentPartHandlerResolver.GetHandlers(partName); - var partValidationContext = new ValidateContentPartContext(context.ContentItem) - { - ContentTypePartDefinition = typePartDefinition, - }; + var partValidationContext = new ValidateContentPartContext(context.ContentItem) { ContentTypePartDefinition = typePartDefinition, }; await partHandlers.InvokeAsync(partHandlerAction, partValidationContext, part, _logger); diff --git a/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentPartHandlerResolver.cs b/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentPartHandlerResolver.cs index 128eb57bda6..3224e00b9bf 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentPartHandlerResolver.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentPartHandlerResolver.cs @@ -10,10 +10,7 @@ public class ContentPartHandlerResolver : IContentPartHandlerResolver private readonly IServiceProvider _serviceProvider; private readonly ContentOptions _contentOptions; - public ContentPartHandlerResolver( - IServiceProvider serviceProvider, - IOptions contentDisplayOptions - ) + public ContentPartHandlerResolver(IServiceProvider serviceProvider, IOptions contentDisplayOptions) { _serviceProvider = serviceProvider; _contentOptions = contentDisplayOptions.Value; diff --git a/src/OrchardCore/OrchardCore.ContentManagement/Records/ContentItemIndex.cs b/src/OrchardCore/OrchardCore.ContentManagement/Records/ContentItemIndex.cs index c16f7c064fc..03c141e4925 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/Records/ContentItemIndex.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/Records/ContentItemIndex.cs @@ -30,7 +30,8 @@ public class ContentItemIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(contentItem => { var contentItemIndex = new ContentItemIndex diff --git a/src/OrchardCore/OrchardCore.ContentManagement/Records/Migrations.cs b/src/OrchardCore/OrchardCore.ContentManagement/Records/Migrations.cs index 7f543586908..98f73d86463 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/Records/Migrations.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/Records/Migrations.cs @@ -11,6 +11,7 @@ namespace OrchardCore.ContentManagement.Records public class Migrations : DataMigration { private readonly IContentDefinitionManager _contentDefinitionManager; + public Migrations(IContentDefinitionManager contentDefinitionManager) { _contentDefinitionManager = contentDefinitionManager; @@ -18,62 +19,39 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public async Task CreateAsync() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", c => c.WithLength(26)) - .Column("ContentItemVersionId", c => c.WithLength(26)) - .Column("Latest") - .Column("Published") - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ModifiedUtc", column => column.Nullable()) - .Column("PublishedUtc", column => column.Nullable()) - .Column("CreatedUtc", column => column.Nullable()) - .Column("Owner", column => column.Nullable().WithLength(ContentItemIndex.MaxOwnerSize)) - .Column("Author", column => column.Nullable().WithLength(ContentItemIndex.MaxAuthorSize)) - .Column("DisplayText", column => column.Nullable().WithLength(ContentItemIndex.MaxDisplayTextSize)) + await SchemaBuilder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", c => c.WithLength(26)) + .Column("ContentItemVersionId", c => c.WithLength(26)) + .Column("Latest") + .Column("Published") + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ModifiedUtc", column => column.Nullable()) + .Column("PublishedUtc", column => column.Nullable()) + .Column("CreatedUtc", column => column.Nullable()) + .Column("Owner", column => column.Nullable().WithLength(ContentItemIndex.MaxOwnerSize)) + .Column("Author", column => column.Nullable().WithLength(ContentItemIndex.MaxAuthorSize)) + .Column("DisplayText", column => column.Nullable().WithLength(ContentItemIndex.MaxDisplayTextSize)) ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentItemIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentItemIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentItemIndex_DocumentId_ContentType", - "DocumentId", - "ContentType", - "CreatedUtc", - "ModifiedUtc", - "PublishedUtc", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentItemIndex_DocumentId_ContentType", "DocumentId", "ContentType", "CreatedUtc", "ModifiedUtc", "PublishedUtc", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentItemIndex_DocumentId_Owner", - "DocumentId", - "Owner", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentItemIndex_DocumentId_Owner", "DocumentId", "Owner", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentItemIndex_DocumentId_Author", - "DocumentId", - "Author", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentItemIndex_DocumentId_Author", "DocumentId", "Author", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentItemIndex_DocumentId_DisplayText", - "DocumentId", - "DisplayText", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentItemIndex_DocumentId_DisplayText", "DocumentId", "DisplayText", "Published", "Latest") ); // Shortcut other migration steps on new content definition schemas. @@ -82,17 +60,15 @@ await SchemaBuilder.AlterIndexTableAsync(table => table public async Task UpdateFrom1Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("ContentItemVersionId", c => c.WithLength(26)) - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("ContentItemVersionId", c => c.WithLength(26))); return 2; } public async Task UpdateFrom2Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("DisplayText", column => column.Nullable().WithLength(ContentItemIndex.MaxDisplayTextSize)) + await SchemaBuilder.AlterIndexTableAsync(table => + table.AddColumn("DisplayText", column => column.Nullable().WithLength(ContentItemIndex.MaxDisplayTextSize)) ); return 3; @@ -115,27 +91,34 @@ public async Task UpdateFrom3Async() contentTypeDefinition.Settings.Remove(property.Name); } - await _contentDefinitionManager.AlterTypeDefinitionAsync(contentTypeDefinition.Name, builder => - { - builder.WithSettings(existingContentTypeSettings); - - foreach (var contentTypePartDefinition in contentTypeDefinition.Parts) + await _contentDefinitionManager.AlterTypeDefinitionAsync( + contentTypeDefinition.Name, + builder => { - var existingTypePartSettings = contentTypePartDefinition.Settings.ToObject(); + builder.WithSettings(existingContentTypeSettings); - // Remove existing properties from JObject - var contentTypePartSettingsProperties = existingTypePartSettings.GetType().GetProperties(); - foreach (var property in contentTypePartSettingsProperties) + foreach (var contentTypePartDefinition in contentTypeDefinition.Parts) { - contentTypePartDefinition.Settings.Remove(property.Name); + var existingTypePartSettings = contentTypePartDefinition.Settings.ToObject(); + + // Remove existing properties from JObject + var contentTypePartSettingsProperties = existingTypePartSettings.GetType().GetProperties(); + foreach (var property in contentTypePartSettingsProperties) + { + contentTypePartDefinition.Settings.Remove(property.Name); + } + + builder.WithPart( + contentTypePartDefinition.Name, + contentTypePartDefinition.PartDefinition, + partBuilder => + { + partBuilder.WithSettings(existingTypePartSettings); + } + ); } - - builder.WithPart(contentTypePartDefinition.Name, contentTypePartDefinition.PartDefinition, partBuilder => - { - partBuilder.WithSettings(existingTypePartSettings); - }); } - }); + ); } return 4; @@ -158,27 +141,33 @@ public async Task UpdateFrom4Async() partDefinition.Settings.Remove(property.Name); } - await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, partBuilder => - { - partBuilder.WithSettings(existingPartSettings); - foreach (var fieldDefinition in partDefinition.Fields) + await _contentDefinitionManager.AlterPartDefinitionAsync( + partDefinition.Name, + partBuilder => { - var existingFieldSettings = fieldDefinition.Settings.ToObject(); - - // Do this before creating builder, so settings are removed from the builder settings object. - // Remove existing properties from JObject - var fieldSettingsProperties = existingFieldSettings.GetType().GetProperties(); - foreach (var property in fieldSettingsProperties) + partBuilder.WithSettings(existingPartSettings); + foreach (var fieldDefinition in partDefinition.Fields) { - fieldDefinition.Settings.Remove(property.Name); + var existingFieldSettings = fieldDefinition.Settings.ToObject(); + + // Do this before creating builder, so settings are removed from the builder settings object. + // Remove existing properties from JObject + var fieldSettingsProperties = existingFieldSettings.GetType().GetProperties(); + foreach (var property in fieldSettingsProperties) + { + fieldDefinition.Settings.Remove(property.Name); + } + + partBuilder.WithField( + fieldDefinition.Name, + fieldBuilder => + { + fieldBuilder.WithSettings(existingFieldSettings); + } + ); } - - partBuilder.WithField(fieldDefinition.Name, fieldBuilder => - { - fieldBuilder.WithSettings(existingFieldSettings); - }); } - }); + ); } return 5; @@ -187,48 +176,24 @@ await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, pa // This code can be removed in a later version. public async Task UpdateFrom5Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentItemIndex_DocumentId", - "DocumentId", - "ContentItemId", - "ContentItemVersionId", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentItemIndex_DocumentId", "DocumentId", "ContentItemId", "ContentItemVersionId", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentItemIndex_DocumentId_ContentType", - "DocumentId", - "ContentType", - "CreatedUtc", - "ModifiedUtc", - "PublishedUtc", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentItemIndex_DocumentId_ContentType", "DocumentId", "ContentType", "CreatedUtc", "ModifiedUtc", "PublishedUtc", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentItemIndex_DocumentId_Owner", - "DocumentId", - "Owner", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentItemIndex_DocumentId_Owner", "DocumentId", "Owner", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentItemIndex_DocumentId_Author", - "DocumentId", - "Author", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentItemIndex_DocumentId_Author", "DocumentId", "Author", "Published", "Latest") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_ContentItemIndex_DocumentId_DisplayText", - "DocumentId", - "DisplayText", - "Published", - "Latest") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_ContentItemIndex_DocumentId_DisplayText", "DocumentId", "DisplayText", "Published", "Latest") ); return 6; diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentPartDefinitionDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentPartDefinitionDisplayDriver.cs index 5e2028680de..d4840093d9d 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentPartDefinitionDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentPartDefinitionDisplayDriver.cs @@ -3,7 +3,9 @@ namespace OrchardCore.ContentTypes.Editors { - public abstract class ContentPartDefinitionDisplayDriver : DisplayDriver, IContentPartDefinitionDisplayDriver + public abstract class ContentPartDefinitionDisplayDriver + : DisplayDriver, + IContentPartDefinitionDisplayDriver { public override bool CanHandleModel(ContentPartDefinition model) { diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentPartFieldDefinitionDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentPartFieldDefinitionDisplayDriver.cs index 48604539fca..88463cba7ae 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentPartFieldDefinitionDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentPartFieldDefinitionDisplayDriver.cs @@ -7,7 +7,9 @@ namespace OrchardCore.ContentTypes.Editors /// /// A concrete implementation of provides a driver for all field definitions. /// - public abstract class ContentPartFieldDefinitionDisplayDriver : DisplayDriver, IContentPartFieldDefinitionDisplayDriver + public abstract class ContentPartFieldDefinitionDisplayDriver + : DisplayDriver, + IContentPartFieldDefinitionDisplayDriver { protected override void BuildPrefix(ContentPartFieldDefinition model, string htmlFieldPrefix) { @@ -33,7 +35,8 @@ public override bool CanHandleModel(ContentPartFieldDefinition model) /// A concrete implementation of provides a driver for field definitions /// of the type TField. /// - public abstract class ContentPartFieldDefinitionDisplayDriver : ContentPartFieldDefinitionDisplayDriver where TField : ContentField + public abstract class ContentPartFieldDefinitionDisplayDriver : ContentPartFieldDefinitionDisplayDriver + where TField : ContentField { public override bool CanHandleModel(ContentPartFieldDefinition model) { diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentTypeDefinitionDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentTypeDefinitionDisplayDriver.cs index e26b67ee225..dbf0c44c984 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentTypeDefinitionDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentTypeDefinitionDisplayDriver.cs @@ -3,7 +3,9 @@ namespace OrchardCore.ContentTypes.Editors { - public abstract class ContentTypeDefinitionDisplayDriver : DisplayDriver, IContentTypeDefinitionDisplayDriver + public abstract class ContentTypeDefinitionDisplayDriver + : DisplayDriver, + IContentTypeDefinitionDisplayDriver { public override bool CanHandleModel(ContentTypeDefinition model) { diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentTypePartDefinitionDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentTypePartDefinitionDisplayDriver.cs index 481a49cadb2..d77a6e5cc7c 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentTypePartDefinitionDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/ContentTypePartDefinitionDisplayDriver.cs @@ -4,7 +4,9 @@ namespace OrchardCore.ContentTypes.Editors { - public abstract class ContentTypePartDefinitionDisplayDriver : DisplayDriver, IContentTypePartDefinitionDisplayDriver + public abstract class ContentTypePartDefinitionDisplayDriver + : DisplayDriver, + IContentTypePartDefinitionDisplayDriver { protected override void BuildPrefix(ContentTypePartDefinition model, string htmlFielPrefix) { @@ -29,7 +31,8 @@ public override bool CanHandleModel(ContentTypePartDefinition model) /// A concrete implementation of provides a driver for part definitions /// of the type TPart. /// - public abstract class ContentTypePartDefinitionDisplayDriver : ContentTypePartDefinitionDisplayDriver where TPart : ContentPart + public abstract class ContentTypePartDefinitionDisplayDriver : ContentTypePartDefinitionDisplayDriver + where TPart : ContentPart { public override bool CanHandleModel(ContentTypePartDefinition model) { diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentPartDefinitionDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentPartDefinitionDisplayDriver.cs index 6e45f5a4ab7..055b99245d1 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentPartDefinitionDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentPartDefinitionDisplayDriver.cs @@ -3,7 +3,5 @@ namespace OrchardCore.ContentTypes.Editors { - public interface IContentPartDefinitionDisplayDriver : IDisplayDriver - { - } + public interface IContentPartDefinitionDisplayDriver : IDisplayDriver { } } diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentPartFieldDefinitionDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentPartFieldDefinitionDisplayDriver.cs index 4e9b26b150e..37802bd61aa 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentPartFieldDefinitionDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentPartFieldDefinitionDisplayDriver.cs @@ -3,7 +3,6 @@ namespace OrchardCore.ContentTypes.Editors { - public interface IContentPartFieldDefinitionDisplayDriver : IDisplayDriver - { - } + public interface IContentPartFieldDefinitionDisplayDriver + : IDisplayDriver { } } diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentTypeDefinitionDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentTypeDefinitionDisplayDriver.cs index 86c4b5b4e2c..2897732b35f 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentTypeDefinitionDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentTypeDefinitionDisplayDriver.cs @@ -3,7 +3,5 @@ namespace OrchardCore.ContentTypes.Editors { - public interface IContentTypeDefinitionDisplayDriver : IDisplayDriver - { - } + public interface IContentTypeDefinitionDisplayDriver : IDisplayDriver { } } diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentTypePartDefinitionDisplayDriver.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentTypePartDefinitionDisplayDriver.cs index 8b242b5725a..e7a59b9a4b6 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentTypePartDefinitionDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/IContentTypePartDefinitionDisplayDriver.cs @@ -3,7 +3,5 @@ namespace OrchardCore.ContentTypes.Editors { - public interface IContentTypePartDefinitionDisplayDriver : IDisplayDriver - { - } + public interface IContentTypePartDefinitionDisplayDriver : IDisplayDriver { } } diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateContentDefinitionEditorContext.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateContentDefinitionEditorContext.cs index 0e7c21ef5ae..b720f4b1393 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateContentDefinitionEditorContext.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateContentDefinitionEditorContext.cs @@ -14,7 +14,8 @@ public UpdateContentDefinitionEditorContext( bool isNew, IShapeFactory shapeFactory, IZoneHolding layout, - IUpdateModel updater) + IUpdateModel updater + ) : base(model, groupId, isNew, "", shapeFactory, layout, updater) { Builder = builder; diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdatePartEditorContext.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdatePartEditorContext.cs index b812020e8f4..b00676bf424 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdatePartEditorContext.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdatePartEditorContext.cs @@ -8,15 +8,14 @@ namespace OrchardCore.ContentTypes.Editors public class UpdatePartEditorContext : UpdateContentDefinitionEditorContext { public UpdatePartEditorContext( - ContentPartDefinitionBuilder builder, - IShape model, - string groupId, - bool isNew, - IShapeFactory shapeFactory, - IZoneHolding layout, - IUpdateModel updater) - : base(builder, model, groupId, isNew, shapeFactory, layout, updater) - { - } + ContentPartDefinitionBuilder builder, + IShape model, + string groupId, + bool isNew, + IShapeFactory shapeFactory, + IZoneHolding layout, + IUpdateModel updater + ) + : base(builder, model, groupId, isNew, shapeFactory, layout, updater) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdatePartFieldEditorContext.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdatePartFieldEditorContext.cs index 317de394585..35e2a0eed82 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdatePartFieldEditorContext.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdatePartFieldEditorContext.cs @@ -8,15 +8,14 @@ namespace OrchardCore.ContentTypes.Editors public class UpdatePartFieldEditorContext : UpdateContentDefinitionEditorContext { public UpdatePartFieldEditorContext( - ContentPartFieldDefinitionBuilder builder, - IShape model, - string groupId, - bool isNew, - IShapeFactory shapeFactory, - IZoneHolding layout, - IUpdateModel updater) - : base(builder, model, groupId, isNew, shapeFactory, layout, updater) - { - } + ContentPartFieldDefinitionBuilder builder, + IShape model, + string groupId, + bool isNew, + IShapeFactory shapeFactory, + IZoneHolding layout, + IUpdateModel updater + ) + : base(builder, model, groupId, isNew, shapeFactory, layout, updater) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateTypeEditorContext.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateTypeEditorContext.cs index c988b7317c9..d84aa46d38b 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateTypeEditorContext.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateTypeEditorContext.cs @@ -8,15 +8,14 @@ namespace OrchardCore.ContentTypes.Editors public class UpdateTypeEditorContext : UpdateContentDefinitionEditorContext { public UpdateTypeEditorContext( - ContentTypeDefinitionBuilder builder, - IShape model, - string groupId, - bool isNew, - IShapeFactory shapeFactory, - IZoneHolding layout, - IUpdateModel updater) - : base(builder, model, groupId, isNew, shapeFactory, layout, updater) - { - } + ContentTypeDefinitionBuilder builder, + IShape model, + string groupId, + bool isNew, + IShapeFactory shapeFactory, + IZoneHolding layout, + IUpdateModel updater + ) + : base(builder, model, groupId, isNew, shapeFactory, layout, updater) { } } } diff --git a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateTypePartEditorContext.cs b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateTypePartEditorContext.cs index 1f9f45e65dd..daf1fc5db42 100644 --- a/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateTypePartEditorContext.cs +++ b/src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateTypePartEditorContext.cs @@ -8,15 +8,14 @@ namespace OrchardCore.ContentTypes.Editors public class UpdateTypePartEditorContext : UpdateContentDefinitionEditorContext { public UpdateTypePartEditorContext( - ContentTypePartDefinitionBuilder builder, - IShape model, - string groupId, - bool isNew, - IShapeFactory shapeFactory, - IZoneHolding layout, - IUpdateModel updater) - : base(builder, model, groupId, isNew, shapeFactory, layout, updater) - { - } + ContentTypePartDefinitionBuilder builder, + IShape model, + string groupId, + bool isNew, + IShapeFactory shapeFactory, + IZoneHolding layout, + IUpdateModel updater + ) + : base(builder, model, groupId, isNew, shapeFactory, layout, updater) { } } } diff --git a/src/OrchardCore/OrchardCore.Contents.Core/AuthorizationServiceExtensions.cs b/src/OrchardCore/OrchardCore.Contents.Core/AuthorizationServiceExtensions.cs index c03789f64c6..288a5bf0994 100644 --- a/src/OrchardCore/OrchardCore.Contents.Core/AuthorizationServiceExtensions.cs +++ b/src/OrchardCore/OrchardCore.Contents.Core/AuthorizationServiceExtensions.cs @@ -12,14 +12,26 @@ namespace Microsoft.AspNetCore.Authorization { public static class AuthorizationServiceExtensions { - public static Task AuthorizeContentTypeAsync(this IAuthorizationService service, ClaimsPrincipal user, Permission requiredPermission, ContentTypeDefinition contentTypeDefinition, string owner = null) + public static Task AuthorizeContentTypeAsync( + this IAuthorizationService service, + ClaimsPrincipal user, + Permission requiredPermission, + ContentTypeDefinition contentTypeDefinition, + string owner = null + ) { ArgumentNullException.ThrowIfNull(contentTypeDefinition); return service.AuthorizeContentTypeAsync(user, requiredPermission, contentTypeDefinition.Name, owner); } - public static Task AuthorizeContentTypeAsync(this IAuthorizationService service, ClaimsPrincipal user, Permission requiredPermission, string contentType, string owner = null) + public static Task AuthorizeContentTypeAsync( + this IAuthorizationService service, + ClaimsPrincipal user, + Permission requiredPermission, + string contentType, + string owner = null + ) { ArgumentNullException.ThrowIfNull(user); @@ -30,11 +42,7 @@ public static Task AuthorizeContentTypeAsync(this IAuthorizationService se throw new ArgumentException($"{nameof(contentType)} cannot be empty."); } - var item = new ContentItem() - { - ContentType = contentType, - Owner = owner, - }; + var item = new ContentItem() { ContentType = contentType, Owner = owner, }; return service.AuthorizeAsync(user, requiredPermission, item); } @@ -42,7 +50,13 @@ public static Task AuthorizeContentTypeAsync(this IAuthorizationService se /// /// Evaluate if we have a specific owner variation permission to at least one content type. /// - public static async Task AuthorizeContentTypeDefinitionsAsync(this IAuthorizationService service, ClaimsPrincipal user, Permission requiredPermission, IEnumerable contentTypeDefinitions, IContentManager contentManager) + public static async Task AuthorizeContentTypeDefinitionsAsync( + this IAuthorizationService service, + ClaimsPrincipal user, + Permission requiredPermission, + IEnumerable contentTypeDefinitions, + IContentManager contentManager + ) { ArgumentNullException.ThrowIfNull(user); ArgumentNullException.ThrowIfNull(requiredPermission); diff --git a/src/OrchardCore/OrchardCore.Contents.Core/ContentTypePermissionsHelper.cs b/src/OrchardCore/OrchardCore.Contents.Core/ContentTypePermissionsHelper.cs index c2b950c412d..cc30292adc3 100644 --- a/src/OrchardCore/OrchardCore.Contents.Core/ContentTypePermissionsHelper.cs +++ b/src/OrchardCore/OrchardCore.Contents.Core/ContentTypePermissionsHelper.cs @@ -4,7 +4,6 @@ using OrchardCore.ContentManagement.Metadata.Models; using OrchardCore.Security.Permissions; - namespace OrchardCore.Contents.Security { /// @@ -27,23 +26,24 @@ public class ContentTypePermissionsHelper private static readonly Permission _listContent = new("ListContent_{0}", "List {0} content items", new[] { CommonPermissions.ListContent }); private static readonly Permission _editContentOwner = new("EditContentOwner_{0}", "Edit the owner of a {0} content item", new[] { CommonPermissions.EditContentOwner }); - public static readonly Dictionary PermissionTemplates = new() - { - { CommonPermissions.PublishContent.Name, _publishContent }, - { CommonPermissions.PublishOwnContent.Name, _publishOwnContent }, - { CommonPermissions.EditContent.Name, _editContent }, - { CommonPermissions.EditOwnContent.Name, _editOwnContent }, - { CommonPermissions.DeleteContent.Name, _deleteContent }, - { CommonPermissions.DeleteOwnContent.Name, _deleteOwnContent }, - { CommonPermissions.ViewContent.Name, _viewContent }, - { CommonPermissions.ViewOwnContent.Name, _viewOwnContent }, - { CommonPermissions.PreviewContent.Name, _previewContent }, - { CommonPermissions.PreviewOwnContent.Name, _previewOwnContent }, - { CommonPermissions.CloneContent.Name, _cloneContent }, - { CommonPermissions.CloneOwnContent.Name, _cloneOwnContent }, - { CommonPermissions.ListContent.Name, _listContent }, - { CommonPermissions.EditContentOwner.Name, _editContentOwner }, - }; + public static readonly Dictionary PermissionTemplates = + new() + { + { CommonPermissions.PublishContent.Name, _publishContent }, + { CommonPermissions.PublishOwnContent.Name, _publishOwnContent }, + { CommonPermissions.EditContent.Name, _editContent }, + { CommonPermissions.EditOwnContent.Name, _editOwnContent }, + { CommonPermissions.DeleteContent.Name, _deleteContent }, + { CommonPermissions.DeleteOwnContent.Name, _deleteOwnContent }, + { CommonPermissions.ViewContent.Name, _viewContent }, + { CommonPermissions.ViewOwnContent.Name, _viewOwnContent }, + { CommonPermissions.PreviewContent.Name, _previewContent }, + { CommonPermissions.PreviewOwnContent.Name, _previewOwnContent }, + { CommonPermissions.CloneContent.Name, _cloneContent }, + { CommonPermissions.CloneOwnContent.Name, _cloneOwnContent }, + { CommonPermissions.ListContent.Name, _listContent }, + { CommonPermissions.EditContentOwner.Name, _editContentOwner }, + }; private static Dictionary, Permission> _permissionsByType = []; @@ -97,10 +97,7 @@ public static Permission CreateDynamicPermission(Permission template, string con (template.ImpliedBy ?? Array.Empty()).Select(t => CreateDynamicPermission(t, contentType)) ); - var localPermissions = new Dictionary, Permission>(_permissionsByType) - { - [key] = permission, - }; + var localPermissions = new Dictionary, Permission>(_permissionsByType) { [key] = permission, }; _permissionsByType = localPermissions; diff --git a/src/OrchardCore/OrchardCore.Contents.Core/Services/ContentQueryContext.cs b/src/OrchardCore/OrchardCore.Contents.Core/Services/ContentQueryContext.cs index 53c7ae419fd..4a3b329f494 100644 --- a/src/OrchardCore/OrchardCore.Contents.Core/Services/ContentQueryContext.cs +++ b/src/OrchardCore/OrchardCore.Contents.Core/Services/ContentQueryContext.cs @@ -7,7 +7,8 @@ namespace OrchardCore.Contents.Services { public class ContentQueryContext : QueryExecutionContext { - public ContentQueryContext(IServiceProvider serviceProvider, IQuery query) : base(query) + public ContentQueryContext(IServiceProvider serviceProvider, IQuery query) + : base(query) { ServiceProvider = serviceProvider; } diff --git a/src/OrchardCore/OrchardCore.Contents.Core/Services/IContentsAdminListFilterParser.cs b/src/OrchardCore/OrchardCore.Contents.Core/Services/IContentsAdminListFilterParser.cs index 1de1a1dd431..16affe137f8 100644 --- a/src/OrchardCore/OrchardCore.Contents.Core/Services/IContentsAdminListFilterParser.cs +++ b/src/OrchardCore/OrchardCore.Contents.Core/Services/IContentsAdminListFilterParser.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Contents.Services { - public interface IContentsAdminListFilterParser : IQueryParser - { - } + public interface IContentsAdminListFilterParser : IQueryParser { } } diff --git a/src/OrchardCore/OrchardCore.Contents.Core/ViewModels/ContentOptionsViewModel.cs b/src/OrchardCore/OrchardCore.Contents.Core/ViewModels/ContentOptionsViewModel.cs index 5ead6ce5d4d..50f0f96e2ee 100644 --- a/src/OrchardCore/OrchardCore.Contents.Core/ViewModels/ContentOptionsViewModel.cs +++ b/src/OrchardCore/OrchardCore.Contents.Core/ViewModels/ContentOptionsViewModel.cs @@ -17,6 +17,7 @@ public ContentOptionsViewModel() BulkAction = ViewModels.ContentsBulkAction.None; ContentsStatus = ContentsStatus.Latest; } + public string SearchText { get; set; } public string OriginalSearchText { get; set; } diff --git a/src/OrchardCore/OrchardCore.Contents.TagHelpers/ContentLinkTagHelper.cs b/src/OrchardCore/OrchardCore.Contents.TagHelpers/ContentLinkTagHelper.cs index 1483b201653..896cab199f6 100644 --- a/src/OrchardCore/OrchardCore.Contents.TagHelpers/ContentLinkTagHelper.cs +++ b/src/OrchardCore/OrchardCore.Contents.TagHelpers/ContentLinkTagHelper.cs @@ -29,10 +29,7 @@ public class ContentLinkTagHelper : TagHelper private readonly IUrlHelperFactory _urlHelperFactory; private readonly IContentDefinitionManager _contentDefinitionManager; - public ContentLinkTagHelper( - IContentManager contentManager, - IUrlHelperFactory urlHelperFactory, - IContentDefinitionManager contentDefinitionManager) + public ContentLinkTagHelper(IContentManager contentManager, IUrlHelperFactory urlHelperFactory, IContentDefinitionManager contentDefinitionManager) { _contentDefinitionManager = contentDefinitionManager; _urlHelperFactory = urlHelperFactory; diff --git a/src/OrchardCore/OrchardCore.Data.Abstractions/DbConnectionValidatorResult.cs b/src/OrchardCore/OrchardCore.Data.Abstractions/DbConnectionValidatorResult.cs index 73b5c6218d7..db64a470dee 100644 --- a/src/OrchardCore/OrchardCore.Data.Abstractions/DbConnectionValidatorResult.cs +++ b/src/OrchardCore/OrchardCore.Data.Abstractions/DbConnectionValidatorResult.cs @@ -41,7 +41,7 @@ public enum DbConnectionValidatorResult UnsupportedProvider, /// - /// The connection was valid but the SSL certificate is invalid. The certificate + /// The connection was valid but the SSL certificate is invalid. The certificate /// is from a non-trusted source (the certificate issuing authority isn't listed as a /// trusted authority in Trusted Root Certification Authorities on the client machine). /// diff --git a/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/DocumentStoreCommitException.cs b/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/DocumentStoreCommitException.cs index 49ae8abfcae..228cb031175 100644 --- a/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/DocumentStoreCommitException.cs +++ b/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/DocumentStoreCommitException.cs @@ -12,9 +12,8 @@ public class DocumentStoreCommitException : Exception /// exception message. /// /// The message that describes the error. - public DocumentStoreCommitException(string message) : base(message) - { - } + public DocumentStoreCommitException(string message) + : base(message) { } /// /// Creates a new instance of with the specified @@ -22,8 +21,7 @@ public DocumentStoreCommitException(string message) : base(message) /// /// The message that describes the error. /// The inner . - public DocumentStoreCommitException(string message, Exception innerException) : base(message, innerException) - { - } + public DocumentStoreCommitException(string message, Exception innerException) + : base(message, innerException) { } } } diff --git a/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/IDocumentStore.cs b/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/IDocumentStore.cs index d1168f942aa..a2a753e74be 100644 --- a/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/IDocumentStore.cs +++ b/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/IDocumentStore.cs @@ -13,14 +13,16 @@ public interface IDocumentStore /// Loads a single document (or create a new one) for updating and that should not be cached. /// For a full isolation, it needs to be used in pair with . /// - Task GetOrCreateMutableAsync(Func> factoryAsync = null) where T : class, new(); + Task GetOrCreateMutableAsync(Func> factoryAsync = null) + where T : class, new(); /// /// Gets a single document (or create a new one) for caching and that should not be updated, /// and a bool indicating if it can be cached, not if it has been already loaded for update. /// For a full isolation, it needs to be used in pair with . /// - Task<(bool, T)> GetOrCreateImmutableAsync(Func> factoryAsync = null) where T : class, new(); + Task<(bool, T)> GetOrCreateImmutableAsync(Func> factoryAsync = null) + where T : class, new(); /// /// Updates the store with the provided document and then uses the delegate to update the cache. diff --git a/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/IFileDocumentStore.cs b/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/IFileDocumentStore.cs index e9820312901..1352c9111a0 100644 --- a/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/IFileDocumentStore.cs +++ b/src/OrchardCore/OrchardCore.Data.Abstractions/Documents/IFileDocumentStore.cs @@ -4,7 +4,5 @@ namespace OrchardCore.Data.Documents /// A singleton service using the file system to store document files under the tenant folder, and that is in sync /// with the ambient transaction, any file is updated after a successful . /// - public interface IFileDocumentStore : IDocumentStore - { - } + public interface IFileDocumentStore : IDocumentStore { } } diff --git a/src/OrchardCore/OrchardCore.Data.Abstractions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Data.Abstractions/ServiceCollectionExtensions.cs index a2a290af74a..e5fa3977a1f 100644 --- a/src/OrchardCore/OrchardCore.Data.Abstractions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Data.Abstractions/ServiceCollectionExtensions.cs @@ -20,7 +20,15 @@ public static class ServiceCollectionExtensions /// Whether the data provider is the default one. /// A sample connection string, e.g. Server={Server Name};Database={Database Name};IntegratedSecurity=true. /// - public static IServiceCollection TryAddDataProvider(this IServiceCollection services, string name, string value, bool hasConnectionString, bool hasTablePrefix, bool isDefault, string sampleConnectionString = "") + public static IServiceCollection TryAddDataProvider( + this IServiceCollection services, + string name, + string value, + bool hasConnectionString, + bool hasTablePrefix, + bool isDefault, + string sampleConnectionString = "" + ) { for (var i = services.Count - 1; i >= 0; i--) { @@ -36,7 +44,17 @@ public static IServiceCollection TryAddDataProvider(this IServiceCollection serv } } - services.AddSingleton(new DatabaseProvider { Name = name, Value = value, HasConnectionString = hasConnectionString, HasTablePrefix = hasTablePrefix, IsDefault = isDefault, SampleConnectionString = sampleConnectionString }); + services.AddSingleton( + new DatabaseProvider + { + Name = name, + Value = value, + HasConnectionString = hasConnectionString, + HasTablePrefix = hasTablePrefix, + IsDefault = isDefault, + SampleConnectionString = sampleConnectionString + } + ); return services; } diff --git a/src/OrchardCore/OrchardCore.Data.Abstractions/ShellSettingsExtensions.cs b/src/OrchardCore/OrchardCore.Data.Abstractions/ShellSettingsExtensions.cs index 896d64e1efe..83b695a42a6 100644 --- a/src/OrchardCore/OrchardCore.Data.Abstractions/ShellSettingsExtensions.cs +++ b/src/OrchardCore/OrchardCore.Data.Abstractions/ShellSettingsExtensions.cs @@ -11,7 +11,7 @@ public static class ShellSettingsExtensions private const string DefaultTableNameSeparator = $"{DatabaseTableOptions}:DefaultTableNameSeparator"; private const string DefaultIdentityColumnSize = $"{DatabaseTableOptions}:DefaultIdentityColumnSize"; - private readonly static string[] _identityColumnSizes = [nameof(Int64), nameof(Int32)]; + private static readonly string[] _identityColumnSizes = [nameof(Int64), nameof(Int32)]; public static DatabaseTableOptions GetDatabaseTableOptions(this ShellSettings shellSettings) => new() @@ -35,10 +35,7 @@ public static ShellSettings ConfigureDatabaseTableOptions(this ShellSettings she public static string GetDocumentTable(this ShellSettings shellSettings) { - var documentTable = (!shellSettings.IsInitialized() - ? shellSettings[DefaultDocumentTable] - : shellSettings["DocumentTable"]) - ?.Trim(); + var documentTable = (!shellSettings.IsInitialized() ? shellSettings[DefaultDocumentTable] : shellSettings["DocumentTable"])?.Trim(); if (string.IsNullOrEmpty(documentTable)) { @@ -50,10 +47,7 @@ public static string GetDocumentTable(this ShellSettings shellSettings) public static string GetTableNameSeparator(this ShellSettings shellSettings) { - var tableNameSeparator = (!shellSettings.IsInitialized() - ? shellSettings[DefaultTableNameSeparator] - : shellSettings["TableNameSeparator"]) - ?.Trim(); + var tableNameSeparator = (!shellSettings.IsInitialized() ? shellSettings[DefaultTableNameSeparator] : shellSettings["TableNameSeparator"])?.Trim(); if (string.IsNullOrEmpty(tableNameSeparator)) { @@ -73,10 +67,7 @@ public static string GetTableNameSeparator(this ShellSettings shellSettings) public static string GetIdentityColumnSize(this ShellSettings shellSettings) { - var identityColumnSize = (!shellSettings.IsInitialized() - ? shellSettings[DefaultIdentityColumnSize] - : shellSettings["IdentityColumnSize"]) - ?.Trim(); + var identityColumnSize = (!shellSettings.IsInitialized() ? shellSettings[DefaultIdentityColumnSize] : shellSettings["IdentityColumnSize"])?.Trim(); if (string.IsNullOrEmpty(identityColumnSize)) { diff --git a/src/OrchardCore/OrchardCore.Data.YesSql.Abstractions/DataMigrationExtensions.cs b/src/OrchardCore/OrchardCore.Data.YesSql.Abstractions/DataMigrationExtensions.cs index 4a81726f978..ed23f699a41 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql.Abstractions/DataMigrationExtensions.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql.Abstractions/DataMigrationExtensions.cs @@ -9,7 +9,7 @@ namespace OrchardCore.Data.Migration; public static class DataMigrationExtensions { /// - /// Executes the create method of the provided data migration. + /// Executes the create method of the provided data migration. /// public static async Task ExecuteCreateMethodAsync(this IDataMigration migration) { @@ -31,7 +31,7 @@ public static async Task ExecuteCreateMethodAsync(this IDataMigration migra } /// - /// Executes the update methods of the provided data migration. + /// Executes the update methods of the provided data migration. /// public static async Task ExecuteUpdateMethodsAsync(this IDataMigration migration, int version) { @@ -86,8 +86,7 @@ private static Dictionary GetUpdateMethods(IDataMigration dataM private static (int Version, MethodInfo MethodInfo) GetUpdateMethod(MethodInfo methodInfo) { - if (methodInfo.Name.StartsWith("UpdateFrom", StringComparison.Ordinal) && - (methodInfo.ReturnType == typeof(int) || methodInfo.ReturnType == typeof(Task))) + if (methodInfo.Name.StartsWith("UpdateFrom", StringComparison.Ordinal) && (methodInfo.ReturnType == typeof(int) || methodInfo.ReturnType == typeof(Task))) { var version = methodInfo.Name.EndsWith("Async", StringComparison.Ordinal) ? methodInfo.Name["UpdateFrom".Length..^"Async".Length] diff --git a/src/OrchardCore/OrchardCore.Data.YesSql.Abstractions/IScopedIndexProvider.cs b/src/OrchardCore/OrchardCore.Data.YesSql.Abstractions/IScopedIndexProvider.cs index 2bf3e62ed2d..e5da4878fed 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql.Abstractions/IScopedIndexProvider.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql.Abstractions/IScopedIndexProvider.cs @@ -7,7 +7,5 @@ namespace OrchardCore.Data /// Represents a contract that used to denote an that needs to be resolved by the DI and registered /// at the level. /// - public interface IScopedIndexProvider : IIndexProvider - { - } + public interface IScopedIndexProvider : IIndexProvider { } } diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/DbConnectionValidator.cs b/src/OrchardCore/OrchardCore.Data.YesSql/DbConnectionValidator.cs index dc3860e0449..eeff4f7a436 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/DbConnectionValidator.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/DbConnectionValidator.cs @@ -38,7 +38,8 @@ public DbConnectionValidator( IOptions sqliteOptions, IOptions shellOptions, ITableNameConventionFactory tableNameConventionFactory, - ILogger logger) + ILogger logger + ) { _databaseProviders = databaseProviders; _tableNameConventionFactory = tableNameConventionFactory; @@ -83,9 +84,7 @@ public async Task ValidateAsync(DbConnectionValidat await using var connection = factory.CreateConnection(); // Prevent from creating an empty locked 'Sqlite' file. - if (provider.Value == DatabaseProviderValue.Sqlite && - connection is SqliteConnection sqliteConnection && - !File.Exists(sqliteConnection.DataSource)) + if (provider.Value == DatabaseProviderValue.Sqlite && connection is SqliteConnection sqliteConnection && !File.Exists(sqliteConnection.DataSource)) { return DbConnectionValidatorResult.DocumentTableNotFound; } @@ -100,8 +99,7 @@ connection is SqliteConnection sqliteConnection && { _logger.LogWarning(ex, "Unable to validate connection string."); - if (ex is SqlException sqlException - && sqlException.InnerException?.Message == "The certificate chain was issued by an authority that is not trusted.") + if (ex is SqlException sqlException && sqlException.InnerException?.Message == "The certificate chain was issued by an authority that is not trusted.") { return DbConnectionValidatorResult.InvalidCertificate; } @@ -129,7 +127,8 @@ connection is SqliteConnection sqliteConnection && return DbConnectionValidatorResult.DocumentTableFound; } - var requiredColumnsCount = Enumerable.Range(0, result.FieldCount) + var requiredColumnsCount = Enumerable + .Range(0, result.FieldCount) .Select(result.GetName) .Where(c => _requiredDocumentTableColumns.Contains(c, StringComparer.OrdinalIgnoreCase)) .Count(); @@ -158,9 +157,7 @@ connection is SqliteConnection sqliteConnection && return DbConnectionValidatorResult.ShellDescriptorDocumentNotFound; } } - catch - { - } + catch { } // The 'Document' table exists. return DbConnectionValidatorResult.DocumentTableFound; @@ -181,9 +178,8 @@ private static string GetDocumentCommandText(SqlBuilder sqlBuilder, string docum return sqlBuilder.ToString(); } - private static (IConnectionFactory connectionFactory, ISqlDialect sqlDialect) GetFactoryAndSqlDialect( - string databaseProvider, - string connectionString) => databaseProvider switch + private static (IConnectionFactory connectionFactory, ISqlDialect sqlDialect) GetFactoryAndSqlDialect(string databaseProvider, string connectionString) => + databaseProvider switch { DatabaseProviderValue.SqlConnection => (new DbConnectionFactory(connectionString), new SqlServerDialect()), DatabaseProviderValue.MySql => (new DbConnectionFactory(connectionString), new MySqlDialect()), diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/DefaultJsonContentSerializer.cs b/src/OrchardCore/OrchardCore.Data.YesSql/DefaultJsonContentSerializer.cs index 1758f2834b6..50a179853b5 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/DefaultJsonContentSerializer.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/DefaultJsonContentSerializer.cs @@ -31,8 +31,7 @@ public DefaultJsonContentSerializer(IEnumerable typeInfoR public DefaultJsonContentSerializer(JsonSerializerOptions options) => _options = options; - public object Deserialize(string content, Type type) - => JsonSerializer.Deserialize(content, type, _options); + public object Deserialize(string content, Type type) => JsonSerializer.Deserialize(content, type, _options); public dynamic DeserializeDynamic(string content) => JsonSerializer.Deserialize(content, _options); diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/Documents/DocumentStore.cs b/src/OrchardCore/OrchardCore.Data.YesSql/Documents/DocumentStore.cs index 2b8282f443c..70bb153eddb 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/Documents/DocumentStore.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/Documents/DocumentStore.cs @@ -28,16 +28,15 @@ public DocumentStore(ISession session) } /// - public async Task GetOrCreateMutableAsync(Func> factoryAsync = null) where T : class, new() + public async Task GetOrCreateMutableAsync(Func> factoryAsync = null) + where T : class, new() { if (_loaded.TryGetValue(typeof(T), out var loaded)) { return loaded as T; } - var document = await _session.Query().FirstOrDefaultAsync() - ?? await (factoryAsync?.Invoke() ?? Task.FromResult((T)null)) - ?? new T(); + var document = await _session.Query().FirstOrDefaultAsync() ?? await (factoryAsync?.Invoke() ?? Task.FromResult((T)null)) ?? new T(); _loaded[typeof(T)] = document; @@ -45,7 +44,8 @@ public DocumentStore(ISession session) } /// - public async Task<(bool, T)> GetOrCreateImmutableAsync(Func> factoryAsync = null) where T : class, new() + public async Task<(bool, T)> GetOrCreateImmutableAsync(Func> factoryAsync = null) + where T : class, new() { if (_loaded.TryGetValue(typeof(T), out var loaded)) { @@ -75,9 +75,7 @@ public async Task UpdateAsync(T document, Func updateCache, bool che AfterCommitFailure(exception => { - throw new DocumentStoreCommitException( - $"The '{typeof(T).Name}' could not be persisted and cached as it has been changed by another process.", - exception); + throw new DocumentStoreCommitException($"The '{typeof(T).Name}' could not be persisted and cached as it has been changed by another process.", exception); }); } diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/Migration/DataMigrationManager.cs b/src/OrchardCore/OrchardCore.Data.YesSql/Migration/DataMigrationManager.cs index 37ea441ba5c..0c042ec5623 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/Migration/DataMigrationManager.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/Migration/DataMigrationManager.cs @@ -42,7 +42,8 @@ public DataMigrationManager( ISession session, IStore store, IExtensionManager extensionManager, - ILogger logger) + ILogger logger + ) { _typeFeatureProvider = typeFeatureProvider; _dataMigrations = dataMigrations; @@ -72,8 +73,7 @@ public async Task GetDataMigrationRecordAsync() public async Task> GetFeaturesThatNeedUpdateAsync() { - var currentVersions = (await GetDataMigrationRecordAsync()).DataMigrations - .ToDictionary(r => r.DataMigrationClass); + var currentVersions = (await GetDataMigrationRecordAsync()).DataMigrations.ToDictionary(r => r.DataMigrationClass); var outOfDateMigrations = _dataMigrations.Where(dataMigration => { @@ -150,11 +150,7 @@ public async Task UpdateAsync(string featureId) } // proceed with dependent features first, whatever the module it's in - var dependencies = _extensionManager - .GetFeatureDependencies( - featureId) - .Where(x => x.Id != featureId) - .Select(x => x.Id); + var dependencies = _extensionManager.GetFeatureDependencies(featureId).Where(x => x.Id != featureId).Select(x => x.Id); await UpdateAsync(dependencies); @@ -251,9 +247,7 @@ public async Task UpdateAsync(string featureId) private async Task GetDataMigrationRecordAsync(IDataMigration tempMigration) { var dataMigrationRecord = await GetDataMigrationRecordAsync(); - return dataMigrationRecord - .DataMigrations - .FirstOrDefault(dm => dm.DataMigrationClass == tempMigration.GetType().FullName); + return dataMigrationRecord.DataMigrations.FirstOrDefault(dm => dm.DataMigrationClass == tempMigration.GetType().FullName); } /// @@ -261,9 +255,7 @@ public async Task UpdateAsync(string featureId) /// private List GetDataMigrations(string featureId) { - var migrations = _dataMigrations - .Where(dm => _typeFeatureProvider.GetFeatureForDependency(dm.GetType()).Id == featureId) - .ToList(); + var migrations = _dataMigrations.Where(dm => _typeFeatureProvider.GetFeatureForDependency(dm.GetType()).Id == featureId).ToList(); return migrations; } diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/Options/SqliteOptions.cs b/src/OrchardCore/OrchardCore.Data.YesSql/Options/SqliteOptions.cs index d300dc0f592..8d560df502a 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/Options/SqliteOptions.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/Options/SqliteOptions.cs @@ -1,16 +1,16 @@ namespace OrchardCore.Data { /// - /// Sqlite-specific configuration for the Orchard Core database. + /// Sqlite-specific configuration for the Orchard Core database. /// See . /// public class SqliteOptions { /// - /// By default in .Net 6, Microsoft.Data.Sqlite pools connections to the database. + /// By default in .Net 6, Microsoft.Data.Sqlite pools connections to the database. /// It achieves this by putting a lock on the database file and leaving connections open to be reused. /// If the lock is preventing tasks like backups, this functionality can be disabled. - /// + /// /// There may be a performance penalty associated with disabling connection pooling. /// . /// diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/OrchardCoreBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Data.YesSql/OrchardCoreBuilderExtensions.cs index 3c80b76df40..9b7ea6b2888 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/OrchardCoreBuilderExtensions.cs @@ -49,10 +49,31 @@ public static OrchardCoreBuilder AddDataAccess(this OrchardCoreBuilder builder) services.AddTransient, SqliteOptionsConfiguration>(); // Adding supported databases - services.TryAddDataProvider(name: "Sql Server", value: DatabaseProviderValue.SqlConnection, hasConnectionString: true, sampleConnectionString: "Server=localhost;Database=Orchard;User Id=username;Password=password", hasTablePrefix: true, isDefault: false); + services.TryAddDataProvider( + name: "Sql Server", + value: DatabaseProviderValue.SqlConnection, + hasConnectionString: true, + sampleConnectionString: "Server=localhost;Database=Orchard;User Id=username;Password=password", + hasTablePrefix: true, + isDefault: false + ); services.TryAddDataProvider(name: "Sqlite", value: DatabaseProviderValue.Sqlite, hasConnectionString: false, hasTablePrefix: false, isDefault: true); - services.TryAddDataProvider(name: "MySql", value: DatabaseProviderValue.MySql, hasConnectionString: true, sampleConnectionString: "Server=localhost;Database=Orchard;Uid=username;Pwd=password", hasTablePrefix: true, isDefault: false); - services.TryAddDataProvider(name: "Postgres", value: DatabaseProviderValue.Postgres, hasConnectionString: true, sampleConnectionString: "Server=localhost;Port=5432;Database=Orchard;User Id=username;Password=password", hasTablePrefix: true, isDefault: false); + services.TryAddDataProvider( + name: "MySql", + value: DatabaseProviderValue.MySql, + hasConnectionString: true, + sampleConnectionString: "Server=localhost;Database=Orchard;Uid=username;Pwd=password", + hasTablePrefix: true, + isDefault: false + ); + services.TryAddDataProvider( + name: "Postgres", + value: DatabaseProviderValue.Postgres, + hasConnectionString: true, + sampleConnectionString: "Server=localhost;Port=5432;Database=Orchard;User Id=username;Password=password", + hasTablePrefix: true, + isDefault: false + ); // Configuring data access services.AddSingleton(sp => @@ -72,9 +93,7 @@ public static OrchardCoreBuilder AddDataAccess(this OrchardCoreBuilder builder) switch (shellSettings["DatabaseProvider"]) { case DatabaseProviderValue.SqlConnection: - storeConfiguration - .UseSqlServer(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted, shellSettings["Schema"]) - .UseBlockIdGenerator(); + storeConfiguration.UseSqlServer(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted, shellSettings["Schema"]).UseBlockIdGenerator(); break; case DatabaseProviderValue.Sqlite: var shellOptions = sp.GetService>().Value; @@ -86,19 +105,13 @@ public static OrchardCoreBuilder AddDataAccess(this OrchardCoreBuilder builder) // Only allow creating a file DB when a tenant is in the Initializing state var connectionString = SqliteHelper.GetConnectionString(sqliteOptions, databaseFolder, shellSettings); - storeConfiguration - .UseSqLite(connectionString, IsolationLevel.ReadUncommitted) - .UseDefaultIdGenerator(); + storeConfiguration.UseSqLite(connectionString, IsolationLevel.ReadUncommitted).UseDefaultIdGenerator(); break; case DatabaseProviderValue.MySql: - storeConfiguration - .UseMySql(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted, shellSettings["Schema"]) - .UseBlockIdGenerator(); + storeConfiguration.UseMySql(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted, shellSettings["Schema"]).UseBlockIdGenerator(); break; case DatabaseProviderValue.Postgres: - storeConfiguration - .UsePostgreSql(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted, shellSettings["Schema"]) - .UseBlockIdGenerator(); + storeConfiguration.UsePostgreSql(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted, shellSettings["Schema"]).UseBlockIdGenerator(); break; default: throw new ArgumentException("Unknown database provider: " + shellSettings["DatabaseProvider"]); @@ -152,19 +165,17 @@ public static OrchardCoreBuilder AddDataAccess(this OrchardCoreBuilder builder) session.RegisterIndexes(scopedServices.ToArray()); - ShellScope.Current - .RegisterBeforeDispose(scope => + ShellScope + .Current.RegisterBeforeDispose(scope => { - return scope.ServiceProvider - .GetRequiredService() - .CommitAsync(); + return scope.ServiceProvider.GetRequiredService().CommitAsync(); }) - .AddExceptionHandler((scope, e) => - { - return scope.ServiceProvider - .GetRequiredService() - .CancelAsync(); - }); + .AddExceptionHandler( + (scope, e) => + { + return scope.ServiceProvider.GetRequiredService().CancelAsync(); + } + ); return session; }); diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesInfo.cs b/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesInfo.cs index 4ec7ecc8ee5..feaf193f762 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesInfo.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesInfo.cs @@ -25,11 +25,9 @@ internal class ShellDbTablesInfo : ISchemaBuilder public bool ThrowOnError { get; private set; } public ILogger _logger { get; set; } = NullLogger.Instance; - public HashSet<(string Name, Type Type, string Collection)> MapIndexTables { get; private set; } = - []; + public HashSet<(string Name, Type Type, string Collection)> MapIndexTables { get; private set; } = []; - public HashSet<(string Name, Type Type, string Collection)> ReduceIndexTables { get; private set; } = - []; + public HashSet<(string Name, Type Type, string Collection)> ReduceIndexTables { get; private set; } = []; public HashSet BridgeTables { get; private set; } = []; public HashSet DocumentTables { get; private set; } = []; @@ -57,7 +55,8 @@ public ShellDbTablesInfo Configure(DbTransaction transaction, ILogger logger, bo public IEnumerable GetTableNames() { - return MapIndexTables.Select(i => Prefix(i.Name)) + return MapIndexTables + .Select(i => Prefix(i.Name)) .Union(ReduceIndexTables.Select(i => Prefix(i.Name))) .Union(BridgeTables.Select(Prefix)) .Append(Prefix(DbBlockIdGenerator.TableName)) @@ -117,17 +116,13 @@ public Task CreateTableAsync(string name, Action table) return Task.CompletedTask; } - public ISchemaBuilder AlterIndexTable(Type indexType, Action table, string collection) - => this; + public ISchemaBuilder AlterIndexTable(Type indexType, Action table, string collection) => this; - public Task AlterIndexTableAsync(Type indexType, Action table, string collection) - => Task.CompletedTask; + public Task AlterIndexTableAsync(Type indexType, Action table, string collection) => Task.CompletedTask; - public ISchemaBuilder AlterTable(string name, Action table) - => this; + public ISchemaBuilder AlterTable(string name, Action table) => this; - public Task AlterTableAsync(string name, Action table) - => Task.CompletedTask; + public Task AlterTableAsync(string name, Action table) => Task.CompletedTask; public ISchemaBuilder DropMapIndexTable(Type indexType, string collection = null) { @@ -260,11 +255,9 @@ public void RemoveTable(string name) } } - public ISchemaBuilder CreateForeignKey(string name, string srcTable, string[] srcColumns, string destTable, string[] destColumns) - => this; + public ISchemaBuilder CreateForeignKey(string name, string srcTable, string[] srcColumns, string destTable, string[] destColumns) => this; - public Task CreateForeignKeyAsync(string name, string srcTable, string[] srcColumns, string destTable, string[] destColumns) - => Task.CompletedTask; + public Task CreateForeignKeyAsync(string name, string srcTable, string[] srcColumns, string destTable, string[] destColumns) => Task.CompletedTask; public ISchemaBuilder DropForeignKey(string srcTable, string name) { @@ -293,11 +286,9 @@ public Task DropForeignKeyAsync(string srcTable, string name) return Task.CompletedTask; } - public ISchemaBuilder CreateSchema(string schema) - => this; + public ISchemaBuilder CreateSchema(string schema) => this; - public Task CreateSchemaAsync(string schema) - => Task.CompletedTask; + public Task CreateSchemaAsync(string schema) => Task.CompletedTask; private void Execute(IEnumerable statements) { diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesRemovingHandler.cs b/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesRemovingHandler.cs index 58fde039887..383badd4673 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesRemovingHandler.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesRemovingHandler.cs @@ -26,7 +26,8 @@ public class ShellDbTablesRemovingHandler : IShellRemovingHandler public ShellDbTablesRemovingHandler( IShellContextFactory shellContextFactory, IStringLocalizer localizer, - ILogger logger) + ILogger logger + ) { _shellContextFactory = shellContextFactory; S = localizer; @@ -146,12 +147,7 @@ private async Task GetTablesToRemoveAsync(ShellSettings shell { var type = migration.GetType().FullName; - _logger.LogError( - ex, - "Failed to replay the migration '{MigrationType}' from version '{Version}' on tenant '{TenantName}'.", - type, - version, - shellSettings.Name); + _logger.LogError(ex, "Failed to replay the migration '{MigrationType}' from version '{Version}' on tenant '{TenantName}'.", type, version, shellSettings.Name); // Replaying a migration may fail for the same reason that a setup or any migration failed. // So the tenant removal is not interrupted, the already enlisted tables may be sufficient. diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/SqliteHelper.cs b/src/OrchardCore/OrchardCore.Data.YesSql/SqliteHelper.cs index c29335176cd..cac0cd44cc3 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/SqliteHelper.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/SqliteHelper.cs @@ -7,8 +7,8 @@ namespace OrchardCore.Data; public static class SqliteHelper { - public static string GetConnectionString(SqliteOptions sqliteOptions, ShellOptions shellOptions, ShellSettings shellSettings) - => GetConnectionString(sqliteOptions, GetDatabaseFolder(shellOptions, shellSettings.Name), shellSettings); + public static string GetConnectionString(SqliteOptions sqliteOptions, ShellOptions shellOptions, ShellSettings shellSettings) => + GetConnectionString(sqliteOptions, GetDatabaseFolder(shellOptions, shellSettings.Name), shellSettings); /// /// Orchard Core SQLite connection string helper that requires ShellSettings to be passed @@ -52,7 +52,13 @@ public static string GetConnectionString(SqliteOptions sqliteOptions, string dat public static string GetDatabaseFolder(ShellOptions shellOptions, string shellName) => Path.Combine(shellOptions.ShellsApplicationDataPath, shellOptions.ShellsContainerName, shellName); - private static SqliteConnectionStringBuilder GetSqliteConnectionStringBuilder(SqliteOptions sqliteOptions, string databaseFolder, string databaseName, SqliteOpenMode sqliteOpenMode){ + private static SqliteConnectionStringBuilder GetSqliteConnectionStringBuilder( + SqliteOptions sqliteOptions, + string databaseFolder, + string databaseName, + SqliteOpenMode sqliteOpenMode + ) + { return new SqliteConnectionStringBuilder { DataSource = string.IsNullOrEmpty(databaseFolder) ? databaseName : Path.Combine(databaseFolder, databaseName), diff --git a/src/OrchardCore/OrchardCore.Data/Documents/FileDocumentStore.cs b/src/OrchardCore/OrchardCore.Data/Documents/FileDocumentStore.cs index 7495cfd0bb5..bd18fa8e04e 100644 --- a/src/OrchardCore/OrchardCore.Data/Documents/FileDocumentStore.cs +++ b/src/OrchardCore/OrchardCore.Data/Documents/FileDocumentStore.cs @@ -23,16 +23,14 @@ public class FileDocumentStore : IFileDocumentStore public FileDocumentStore(IOptions shellOptions, ShellSettings shellSettings) { - _tenantPath = Path.Combine( - shellOptions.Value.ShellsApplicationDataPath, - shellOptions.Value.ShellsContainerName, - shellSettings.Name) + "/"; + _tenantPath = Path.Combine(shellOptions.Value.ShellsApplicationDataPath, shellOptions.Value.ShellsContainerName, shellSettings.Name) + "/"; Directory.CreateDirectory(_tenantPath); } /// - public async Task GetOrCreateMutableAsync(Func> factoryAsync = null) where T : class, new() + public async Task GetOrCreateMutableAsync(Func> factoryAsync = null) + where T : class, new() { var loaded = ShellScope.Get(typeof(T)); if (loaded != null) @@ -40,9 +38,7 @@ public FileDocumentStore(IOptions shellOptions, ShellSettings shel return loaded; } - var document = await GetDocumentAsync() - ?? await (factoryAsync?.Invoke() ?? Task.FromResult((T)null)) - ?? new T(); + var document = await GetDocumentAsync() ?? await (factoryAsync?.Invoke() ?? Task.FromResult((T)null)) ?? new T(); ShellScope.Set(typeof(T), document); @@ -50,7 +46,8 @@ public FileDocumentStore(IOptions shellOptions, ShellSettings shel } /// - public async Task<(bool, T)> GetOrCreateImmutableAsync(Func> factoryAsync = null) where T : class, new() + public async Task<(bool, T)> GetOrCreateImmutableAsync(Func> factoryAsync = null) + where T : class, new() { var loaded = ShellScope.Get(typeof(T)); if (loaded != null) @@ -76,8 +73,11 @@ public Task UpdateAsync(T document, Func updateCache, bool checkConc } public Task CancelAsync() => DocumentStore.CancelAsync(); + public void AfterCommitSuccess(DocumentStoreCommitSuccessDelegate afterCommitSuccess) => DocumentStore.AfterCommitSuccess(afterCommitSuccess); + public void AfterCommitFailure(DocumentStoreCommitFailureDelegate afterCommitFailure) => DocumentStore.AfterCommitFailure(afterCommitFailure); + public Task CommitAsync() => throw new NotImplementedException(); private async Task GetDocumentAsync() diff --git a/src/OrchardCore/OrchardCore.Data/Migration/AutomaticDataMigrations.cs b/src/OrchardCore/OrchardCore.Data/Migration/AutomaticDataMigrations.cs index cb49d078f80..e8586d0ec38 100644 --- a/src/OrchardCore/OrchardCore.Data/Migration/AutomaticDataMigrations.cs +++ b/src/OrchardCore/OrchardCore.Data/Migration/AutomaticDataMigrations.cs @@ -22,10 +22,7 @@ public class AutomaticDataMigrations : ModularTenantEvents /// The . /// The . /// The . - public AutomaticDataMigrations( - IServiceProvider serviceProvider, - ShellSettings shellSettings, - ILogger logger) + public AutomaticDataMigrations(IServiceProvider serviceProvider, ShellSettings shellSettings, ILogger logger) { _serviceProvider = serviceProvider; _shellSettings = shellSettings; diff --git a/src/OrchardCore/OrchardCore.Deployment.Abstractions/DeploymentPlanResult.cs b/src/OrchardCore/OrchardCore.Deployment.Abstractions/DeploymentPlanResult.cs index 4758a4f22c6..0f13c78c3ce 100644 --- a/src/OrchardCore/OrchardCore.Deployment.Abstractions/DeploymentPlanResult.cs +++ b/src/OrchardCore/OrchardCore.Deployment.Abstractions/DeploymentPlanResult.cs @@ -32,6 +32,7 @@ public DeploymentPlanResult(IFileBuilder fileBuilder, RecipeDescriptor recipeDes public JsonObject Recipe { get; } public IList Steps { get; init; } = []; public IFileBuilder FileBuilder { get; } + public async Task FinalizeAsync() { Recipe["steps"] = JArray.FromObject(Steps); diff --git a/src/OrchardCore/OrchardCore.Deployment.Abstractions/IDeploymentStepFactory.cs b/src/OrchardCore/OrchardCore.Deployment.Abstractions/IDeploymentStepFactory.cs index 0b8e20236f7..5f5f018c34e 100644 --- a/src/OrchardCore/OrchardCore.Deployment.Abstractions/IDeploymentStepFactory.cs +++ b/src/OrchardCore/OrchardCore.Deployment.Abstractions/IDeploymentStepFactory.cs @@ -6,7 +6,8 @@ public interface IDeploymentStepFactory DeploymentStep Create(); } - public class DeploymentStepFactory : IDeploymentStepFactory where TStep : DeploymentStep, new() + public class DeploymentStepFactory : IDeploymentStepFactory + where TStep : DeploymentStep, new() { private static readonly string _typeName = typeof(TStep).Name; diff --git a/src/OrchardCore/OrchardCore.Deployment.Abstractions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Deployment.Abstractions/ServiceCollectionExtensions.cs index d443bd423fe..b274adf79af 100644 --- a/src/OrchardCore/OrchardCore.Deployment.Abstractions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Deployment.Abstractions/ServiceCollectionExtensions.cs @@ -18,8 +18,7 @@ public static IServiceCollection AddDeployment(this IServiceColl where TSource : IDeploymentSource where TStep : DeploymentStep, new() { - services.AddDeploymentSource() - .AddDeploymentStep(); + services.AddDeploymentSource().AddDeploymentStep(); return services; } @@ -29,8 +28,7 @@ public static IServiceCollection AddDeployment(t where TStep : DeploymentStep, new() where TDisplayDriver : DisplayDriver { - services.AddDeployment() - .AddDeploymentStepDisplayDriver(); + services.AddDeployment().AddDeploymentStepDisplayDriver(); return services; } @@ -39,8 +37,7 @@ public static IServiceCollection AddDeploymentWithoutSource { - services.AddDeploymentStep() - .AddDeploymentStepDisplayDriver(); + services.AddDeploymentStep().AddDeploymentStepDisplayDriver(); return services; } diff --git a/src/OrchardCore/OrchardCore.Deployment.Core/Services/DeploymentManager.cs b/src/OrchardCore/OrchardCore.Deployment.Core/Services/DeploymentManager.cs index 531ef857494..c8245b70fe8 100644 --- a/src/OrchardCore/OrchardCore.Deployment.Core/Services/DeploymentManager.cs +++ b/src/OrchardCore/OrchardCore.Deployment.Core/Services/DeploymentManager.cs @@ -14,7 +14,8 @@ public class DeploymentManager : IDeploymentManager public DeploymentManager( IEnumerable deploymentSources, IEnumerable deploymentTargetProviders, - IEnumerable deploymentTargetHandlers) + IEnumerable deploymentTargetHandlers + ) { _deploymentSources = deploymentSources; _deploymentTargetProviders = deploymentTargetProviders; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/Extensions/ResultExecutingContextExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/Extensions/ResultExecutingContextExtensions.cs index 4b67a4cfe9c..8ee2f3d9ef9 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/Extensions/ResultExecutingContextExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/Extensions/ResultExecutingContextExtensions.cs @@ -4,6 +4,5 @@ namespace Microsoft.AspNetCore.Mvc.Filters; public static class ResultExecutingContextExtensions { - public static bool IsViewOrPageResult(this ResultExecutingContext context) - => context.Result is ViewResult or PageResult; + public static bool IsViewOrPageResult(this ResultExecutingContext context) => context.Result is ViewResult or PageResult; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/ModelBinding/IUpdateModel.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/ModelBinding/IUpdateModel.cs index e8bd5fd217c..9b112fe3106 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/ModelBinding/IUpdateModel.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/ModelBinding/IUpdateModel.cs @@ -7,9 +7,12 @@ namespace OrchardCore.DisplayManagement.ModelBinding { public interface IUpdateModel { - Task TryUpdateModelAsync(TModel model) where TModel : class; - Task TryUpdateModelAsync(TModel model, string prefix) where TModel : class; - Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) where TModel : class; + Task TryUpdateModelAsync(TModel model) + where TModel : class; + Task TryUpdateModelAsync(TModel model, string prefix) + where TModel : class; + Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) + where TModel : class; bool TryValidateModel(object model); bool TryValidateModel(object model, string prefix); ModelStateDictionary ModelState { get; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/ModelBinding/ModelStateDictionaryExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/ModelBinding/ModelStateDictionaryExtensions.cs index 07f6a54f108..f0b656ef936 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/ModelBinding/ModelStateDictionaryExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Abstractions/ModelBinding/ModelStateDictionaryExtensions.cs @@ -53,5 +53,3 @@ public static void BindValidationResult(this ModelStateDictionary modelState, st } } } - - diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheTag.cs index a96ce571b3c..91d3aaf9810 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheTag.cs @@ -18,7 +18,13 @@ public class CacheTag { private static readonly char[] _splitChars = [',', ' ']; - public static async ValueTask WriteToAsync(List arguments, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync( + List arguments, + IReadOnlyList statements, + TextWriter writer, + TextEncoder encoder, + TemplateContext context + ) { var services = ((LiquidTemplateContext)context).Services; @@ -30,9 +36,11 @@ public static async ValueTask WriteToAsync(List argu if (dynamicCache == null || cacheScopeManager == null) { - logger.LogInformation(@"Liquid cache block entered without an available IDynamicCacheService or ICacheScopeManager. + logger.LogInformation( + @"Liquid cache block entered without an available IDynamicCacheService or ICacheScopeManager. The contents of the cache block will not be cached. - To enable caching, make sure that a feature that contains an implementation of IDynamicCacheService and ICacheScopeManager is enabled (for example, 'Dynamic Cache')."); + To enable caching, make sure that a feature that contains an implementation of IDynamicCacheService and ICacheScopeManager is enabled (for example, 'Dynamic Cache')." + ); if (statements != null && statements.Count > 0) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/ResourceUrlFilter.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/ResourceUrlFilter.cs index 0b14801eb87..43e6aabcad5 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/ResourceUrlFilter.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/ResourceUrlFilter.cs @@ -33,12 +33,16 @@ public ValueTask ProcessAsync(FluidValue input, FilterArguments argu } // Don't prefix cdn if the path includes a protocol, i.e. is an external url, or is in debug mode. - if (!_options.DebugMode && !string.IsNullOrEmpty(_options.CdnBaseUrl) && + if ( + !_options.DebugMode + && !string.IsNullOrEmpty(_options.CdnBaseUrl) + && // Don't evaluate with Uri.TryCreate as it produces incorrect results on Linux. - !resourcePath.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && - !resourcePath.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && - !resourcePath.StartsWith("//", StringComparison.OrdinalIgnoreCase) && - !resourcePath.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) + !resourcePath.StartsWith("https://", StringComparison.OrdinalIgnoreCase) + && !resourcePath.StartsWith("http://", StringComparison.OrdinalIgnoreCase) + && !resourcePath.StartsWith("//", StringComparison.OrdinalIgnoreCase) + && !resourcePath.StartsWith("file://", StringComparison.OrdinalIgnoreCase) + ) { resourcePath = _options.CdnBaseUrl + resourcePath; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/SanitizeHtmlFilter.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/SanitizeHtmlFilter.cs index 3fc708a0ddd..8a5394059d6 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/SanitizeHtmlFilter.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/SanitizeHtmlFilter.cs @@ -14,6 +14,7 @@ public SanitizeHtmlFilter(IHtmlSanitizerService htmlSanitizerService) { _htmlSanitizerService = htmlSanitizerService; } + public ValueTask ProcessAsync(FluidValue input, FilterArguments arguments, LiquidTemplateContext ctx) { var html = input.ToStringValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidCultureAccessor.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidCultureAccessor.cs index 3c2b8e8da6f..c226bb2cf6e 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidCultureAccessor.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidCultureAccessor.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Liquid /// /// This is a placeholder class that allows modules to extend the `Culture` property in the current Liquid scope. /// - public class LiquidCultureAccessor - { - } + public class LiquidCultureAccessor { } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidEnvironmentAccessor.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidEnvironmentAccessor.cs index f991319ff18..9706cea1be7 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidEnvironmentAccessor.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidEnvironmentAccessor.cs @@ -3,6 +3,4 @@ namespace OrchardCore.DisplayManagement.Liquid; /// /// This is a placeholder class that allows modules to extend the `Environment` property in the current Liquid scope. /// -public class LiquidEnvironmentAccessor -{ -} +public class LiquidEnvironmentAccessor { } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidHttpContextAccessor.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidHttpContextAccessor.cs index 74b65fc9247..e33194f4218 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidHttpContextAccessor.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidHttpContextAccessor.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Liquid /// /// This is a placeholder class that allows modules to extend the `HttpContext` property in the current Liquid scope. /// - public class LiquidHttpContextAccessor - { - } + public class LiquidHttpContextAccessor { } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidRequestAccessor.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidRequestAccessor.cs index 4bafefb9373..f317b9a04d0 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidRequestAccessor.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidRequestAccessor.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Liquid /// /// This is a placeholder class that allows modules to extend the `HttpRequest` property in the current Liquid scope. /// - public class LiquidRequestAccessor - { - } + public class LiquidRequestAccessor { } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewParser.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewParser.cs index 138e3c1c2c0..54ad1883357 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewParser.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewParser.cs @@ -49,8 +49,15 @@ public LiquidViewParser(IOptions liquidViewOptions) RegisterParserTag("shape", ArgumentsList, ShapeTag.WriteToAsync); RegisterParserBlock("zone", ArgumentsList, ZoneTag.WriteToAsync); - RegisteredTags["a"] = ArgumentsList.AndSkip(TagEnd).And(Parsers.ZeroOrOne(AnyTagsList.AndSkip(CreateTag("enda")))).Then(x => new ParserBlockStatement>(x.Item1, x.Item2, DefaultAnchorTag.WriteToAsync)); - RegisterParserBlock("form", ArgumentsList, (list, statements, writer, encoder, context) => FluidTagHelper.WriteToAsync("form", list, statements, writer, encoder, context)); + RegisteredTags["a"] = ArgumentsList + .AndSkip(TagEnd) + .And(Parsers.ZeroOrOne(AnyTagsList.AndSkip(CreateTag("enda")))) + .Then(x => new ParserBlockStatement>(x.Item1, x.Item2, DefaultAnchorTag.WriteToAsync)); + RegisterParserBlock( + "form", + ArgumentsList, + (list, statements, writer, encoder, context) => FluidTagHelper.WriteToAsync("form", list, statements, writer, encoder, context) + ); // Dynamic caching RegisterParserBlock("cache", ArgumentsList, CacheTag.WriteToAsync); @@ -71,7 +78,12 @@ internal sealed class ParserBlockStatement : TagStatement { private readonly Func, TextWriter, TextEncoder, TemplateContext, ValueTask> _render; - public ParserBlockStatement(T value, List statements, Func, TextWriter, TextEncoder, TemplateContext, ValueTask> render) : base(statements) + public ParserBlockStatement( + T value, + List statements, + Func, TextWriter, TextEncoder, TemplateContext, ValueTask> render + ) + : base(statements) { ArgumentNullException.ThrowIfNull(render); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewTemplate.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewTemplate.cs index 63be8f7837e..da09e432cb6 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewTemplate.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewTemplate.cs @@ -76,75 +76,78 @@ internal static async Task RenderAsync(RazorPage page) public static Task ParseAsync(LiquidViewParser parser, string path, IFileProvider fileProvider, IMemoryCache cache, bool isDevelopment) { - return cache.GetOrCreateAsync(path, async entry => - { - entry.SetSlidingExpiration(TimeSpan.FromHours(1)); - var fileInfo = fileProvider.GetFileInfo(path); - - if (isDevelopment) + return cache.GetOrCreateAsync( + path, + async entry => { - entry.ExpirationTokens.Add(fileProvider.Watch(path)); - } + entry.SetSlidingExpiration(TimeSpan.FromHours(1)); + var fileInfo = fileProvider.GetFileInfo(path); - await using var stream = fileInfo.CreateReadStream(); - using var sr = new StreamReader(stream); + if (isDevelopment) + { + entry.ExpirationTokens.Add(fileProvider.Watch(path)); + } - if (parser.TryParse(await sr.ReadToEndAsync(), out var template, out var errors)) - { - return new LiquidViewTemplate(template); - } + await using var stream = fileInfo.CreateReadStream(); + using var sr = new StreamReader(stream); - throw new Exception($"Failed to parse liquid file {path}: {string.Join(System.Environment.NewLine, errors)}"); - }); + if (parser.TryParse(await sr.ReadToEndAsync(), out var template, out var errors)) + { + return new LiquidViewTemplate(template); + } + + throw new Exception($"Failed to parse liquid file {path}: {string.Join(System.Environment.NewLine, errors)}"); + } + ); } } internal class ShapeAccessor : DelegateAccessor { - public ShapeAccessor() : base(_getter) - { - } + public ShapeAccessor() + : base(_getter) { } - private static Func _getter => (o, n) => - { - if (o is Shape shape) + private static Func _getter => + (o, n) => { - object obj = n switch + if (o is Shape shape) { - nameof(Shape.Id) => shape.Id, - nameof(Shape.TagName) => shape.TagName, - nameof(Shape.HasItems) => shape.HasItems, - nameof(Shape.Classes) => shape.Classes, - nameof(Shape.Attributes) => shape.Attributes, - nameof(Shape.Metadata) => shape.Metadata, - nameof(Shape.Items) => shape.Items, - nameof(Shape.Properties) => shape.Properties, - _ => null - }; - - if (obj != null) - { - return obj; + object obj = n switch + { + nameof(Shape.Id) => shape.Id, + nameof(Shape.TagName) => shape.TagName, + nameof(Shape.HasItems) => shape.HasItems, + nameof(Shape.Classes) => shape.Classes, + nameof(Shape.Attributes) => shape.Attributes, + nameof(Shape.Metadata) => shape.Metadata, + nameof(Shape.Items) => shape.Items, + nameof(Shape.Properties) => shape.Properties, + _ => null + }; + + if (obj != null) + { + return obj; + } + + if (shape.Properties.TryGetValue(n, out obj)) + { + return obj; + } + + // 'MyType-MyField-FieldType_Display__DisplayMode'. + var namedShaped = shape.Named(n); + if (namedShaped != null) + { + return namedShaped; + } + + // 'MyNamedPart', 'MyType__MyField' 'MyType-MyField'. + return shape.NormalizedNamed(n.Replace("__", "-")); } - if (shape.Properties.TryGetValue(n, out obj)) - { - return obj; - } - - // 'MyType-MyField-FieldType_Display__DisplayMode'. - var namedShaped = shape.Named(n); - if (namedShaped != null) - { - return namedShaped; - } - - // 'MyNamedPart', 'MyType__MyField' 'MyType-MyField'. - return shape.NormalizedNamed(n.Replace("__", "-")); - } - - return null; - }; + return null; + }; } public static class LiquidViewTemplateExtensions @@ -221,22 +224,18 @@ internal static ViewContext GetViewContext(ActionContext actionContext) var options = services.GetService>(); var viewEngine = options.Value.ViewEngines[0]; - var viewResult = viewEngine.GetView(executingFilePath: null, - LiquidViewsFeatureProvider.DefaultRazorViewPath, isMainPage: true); + var viewResult = viewEngine.GetView(executingFilePath: null, LiquidViewsFeatureProvider.DefaultRazorViewPath, isMainPage: true); var tempDataProvider = services.GetService(); var viewContext = new ViewContext( actionContext, viewResult.View, - new ViewDataDictionary( - metadataProvider: new EmptyModelMetadataProvider(), - modelState: new ModelStateDictionary()), - new TempDataDictionary( - actionContext.HttpContext, - tempDataProvider), + new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary()), + new TempDataDictionary(actionContext.HttpContext, tempDataProvider), TextWriter.Null, - new HtmlHelperOptions()); + new HtmlHelperOptions() + ); if (viewContext.View is RazorView razorView) { @@ -291,7 +290,8 @@ internal static async Task EnterScopeAsync(this LiquidTemplateContext context, V if (context.ShapeRecursions++ > LiquidTemplateContext.MaxShapeRecursions) { throw new InvalidOperationException( - $"The '{shape.Metadata.Type}' shape has been called recursively more than {LiquidTemplateContext.MaxShapeRecursions} times."); + $"The '{shape.Metadata.Type}' shape has been called recursively more than {LiquidTemplateContext.MaxShapeRecursions} times." + ); } } else diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewsFeatureProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewsFeatureProvider.cs index 6d2d3e435f0..f8d6bc5334d 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewsFeatureProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewsFeatureProvider.cs @@ -35,8 +35,10 @@ public LiquidViewsFeatureProvider(IOptions templateOptions) _sharedPaths = []; var filePaths = templateOptions.Value.FileProvider.GetViewFilePaths( - Application.ModulesPath, [LiquidViewTemplate.ViewExtension], - LiquidViewTemplate.ViewsFolder); + Application.ModulesPath, + [LiquidViewTemplate.ViewExtension], + LiquidViewTemplate.ViewsFolder + ); _sharedPaths.AddRange(filePaths.Select(p => '/' + p)); } @@ -45,22 +47,16 @@ public LiquidViewsFeatureProvider(IOptions templateOptions) public void PopulateFeature(IEnumerable parts, ViewsFeature feature) { - feature.ViewDescriptors.Add(new CompiledViewDescriptor - { - RelativePath = DefaultRazorViewPath, - Item = new TenantRazorCompiledItem(typeof(LiquidPage), DefaultLiquidViewPath) - }); + feature.ViewDescriptors.Add( + new CompiledViewDescriptor { RelativePath = DefaultRazorViewPath, Item = new TenantRazorCompiledItem(typeof(LiquidPage), DefaultLiquidViewPath) } + ); foreach (var path in _sharedPaths) { if (!Path.GetFileName(path).StartsWith('_')) { var viewPath = Path.ChangeExtension(path, RazorViewEngine.ViewExtension); - feature.ViewDescriptors.Add(new CompiledViewDescriptor - { - RelativePath = viewPath, - Item = new TenantRazorCompiledItem(typeof(LiquidPage), viewPath) - }); + feature.ViewDescriptors.Add(new CompiledViewDescriptor { RelativePath = viewPath, Item = new TenantRazorCompiledItem(typeof(LiquidPage), viewPath) }); } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/ModuleProjectLiquidFileProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/ModuleProjectLiquidFileProvider.cs index 52793d0d976..e19327608a1 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/ModuleProjectLiquidFileProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/ModuleProjectLiquidFileProvider.cs @@ -36,15 +36,13 @@ public ModuleProjectLiquidFileProvider(IApplicationContext applicationContext) { // If the module and the application assemblies are not at the same location, // this means that the module is referenced as a package, not as a project in dev. - if (module.Assembly == null || Path.GetDirectoryName(module.Assembly.Location) - != Path.GetDirectoryName(application.Assembly.Location)) + if (module.Assembly == null || Path.GetDirectoryName(module.Assembly.Location) != Path.GetDirectoryName(application.Assembly.Location)) { continue; } // Get module assets which are liquid template files. - assets.AddRange(module.Assets.Where(a => a.ModuleAssetPath - .EndsWith(".liquid", StringComparison.Ordinal))); + assets.AddRange(module.Assets.Where(a => a.ModuleAssetPath.EndsWith(".liquid", StringComparison.Ordinal))); } // Init the mapping between module and project asset paths. diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/OrchardCoreBuilderExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/OrchardCoreBuilderExtensions.cs index d03b6f95bbb..aa4abbec01b 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/OrchardCoreBuilderExtensions.cs @@ -37,142 +37,148 @@ public static OrchardCoreBuilder AddLiquidViews(this OrchardCoreBuilder builder) services.AddTransient, TemplateOptionsFileProviderSetup>(); - services.TryAddEnumerable( - ServiceDescriptor.Transient, - LiquidViewOptionsSetup>()); + services.TryAddEnumerable(ServiceDescriptor.Transient, LiquidViewOptionsSetup>()); - services.TryAddEnumerable( - ServiceDescriptor.Transient, - LiquidShapeTemplateOptionsSetup>()); + services.TryAddEnumerable(ServiceDescriptor.Transient, LiquidShapeTemplateOptionsSetup>()); services.AddSingleton, LiquidViewsFeatureProvider>(); services.AddScoped(); services.AddSingleton(); - services.Configure(o => - { - o.ValueConverters.Add(x => + services + .Configure(o => { - if (x is Shape s) + o.ValueConverters.Add(x => { - return new ObjectValue(s); - } - else if (x is IHtmlContent c) - { - return new HtmlContentValue(c); - } + if (x is Shape s) + { + return new ObjectValue(s); + } + else if (x is IHtmlContent c) + { + return new HtmlContentValue(c); + } - return null; - }); + return null; + }); - o.MemberAccessStrategy.Register("*", new ShapeAccessor()); - o.MemberAccessStrategy.Register("*", new ShapeAccessor()); - o.MemberAccessStrategy.Register(); + o.MemberAccessStrategy.Register("*", new ShapeAccessor()); + o.MemberAccessStrategy.Register("*", new ShapeAccessor()); + o.MemberAccessStrategy.Register(); - o.Scope.SetValue("Culture", new ObjectValue(new LiquidCultureAccessor())); - o.MemberAccessStrategy.Register((obj, name, ctx) => - { - return name switch - { - nameof(CultureInfo.Name) => new StringValue(CultureInfo.CurrentUICulture.Name), - "Dir" => new StringValue(CultureInfo.CurrentUICulture.GetLanguageDirection()), - _ => NilValue.Instance - }; - }); - - o.Scope.SetValue("Environment", new ObjectValue(new LiquidEnvironmentAccessor())); - o.MemberAccessStrategy.Register((obj, name, ctx) => - { - var hostEnvironment = ((LiquidTemplateContext)ctx).Services.GetRequiredService(); - - if (hostEnvironment != null) - { - return name switch + o.Scope.SetValue("Culture", new ObjectValue(new LiquidCultureAccessor())); + o.MemberAccessStrategy.Register( + (obj, name, ctx) => { - "IsDevelopment" => BooleanValue.Create(hostEnvironment.IsDevelopment()), - "IsStaging" => BooleanValue.Create(hostEnvironment.IsStaging()), - "IsProduction" => BooleanValue.Create(hostEnvironment.IsProduction()), - "Name" => StringValue.Create(hostEnvironment.EnvironmentName), - _ => NilValue.Instance - }; - } - - return NilValue.Instance; - }); - - o.Scope.SetValue("Request", new ObjectValue(new LiquidRequestAccessor())); - o.MemberAccessStrategy.Register((obj, name, ctx) => - { - var request = ((LiquidTemplateContext)ctx).Services.GetRequiredService().HttpContext?.Request; - if (request != null) - { - return name switch + return name switch + { + nameof(CultureInfo.Name) => new StringValue(CultureInfo.CurrentUICulture.Name), + "Dir" => new StringValue(CultureInfo.CurrentUICulture.GetLanguageDirection()), + _ => NilValue.Instance + }; + } + ); + + o.Scope.SetValue("Environment", new ObjectValue(new LiquidEnvironmentAccessor())); + o.MemberAccessStrategy.Register( + (obj, name, ctx) => { - nameof(HttpRequest.QueryString) => new StringValue(request.QueryString.Value), - nameof(HttpRequest.ContentType) => new StringValue(request.ContentType), - nameof(HttpRequest.ContentLength) => NumberValue.Create(request.ContentLength ?? 0), - nameof(HttpRequest.Cookies) => new ObjectValue(new CookieCollectionWrapper(request.Cookies)), - nameof(HttpRequest.Headers) => new ObjectValue(new HeaderDictionaryWrapper(request.Headers)), - nameof(HttpRequest.Query) => new ObjectValue(new QueryCollection(request.Query.ToDictionary(kv => kv.Key, kv => kv.Value))), - nameof(HttpRequest.Form) => request.HasFormContentType ? (FluidValue)new ObjectValue(request.Form) : NilValue.Instance, - nameof(HttpRequest.Protocol) => new StringValue(request.Protocol), - nameof(HttpRequest.Path) => new StringValue(request.Path.Value), - nameof(HttpRequest.PathBase) => new StringValue(request.PathBase.Value), - nameof(HttpRequest.Host) => new StringValue(request.Host.Value), - nameof(HttpRequest.IsHttps) => BooleanValue.Create(request.IsHttps), - nameof(HttpRequest.Scheme) => new StringValue(request.Scheme), - nameof(HttpRequest.Method) => new StringValue(request.Method), - nameof(HttpRequest.RouteValues) => new ObjectValue(new RouteValueDictionaryWrapper(request.RouteValues)), - - // Provides correct escaping to reconstruct a request or redirect URI. - "UriHost" => new StringValue(request.Host.ToUriComponent(), encode: false), - "UriPath" => new StringValue(request.Path.ToUriComponent(), encode: false), - "UriPathBase" => new StringValue(request.PathBase.ToUriComponent(), encode: false), - "UriQueryString" => new StringValue(request.QueryString.ToUriComponent(), encode: false), - - _ => NilValue.Instance - }; - } - - return NilValue.Instance; - }); - - o.Scope.SetValue("HttpContext", new ObjectValue(new LiquidHttpContextAccessor())); - o.MemberAccessStrategy.Register((obj, name, ctx) => - { - var httpContext = ((LiquidTemplateContext)ctx).Services.GetRequiredService().HttpContext; - if (httpContext != null) - { - return name switch + var hostEnvironment = ((LiquidTemplateContext)ctx).Services.GetRequiredService(); + + if (hostEnvironment != null) + { + return name switch + { + "IsDevelopment" => BooleanValue.Create(hostEnvironment.IsDevelopment()), + "IsStaging" => BooleanValue.Create(hostEnvironment.IsStaging()), + "IsProduction" => BooleanValue.Create(hostEnvironment.IsProduction()), + "Name" => StringValue.Create(hostEnvironment.EnvironmentName), + _ => NilValue.Instance + }; + } + + return NilValue.Instance; + } + ); + + o.Scope.SetValue("Request", new ObjectValue(new LiquidRequestAccessor())); + o.MemberAccessStrategy.Register( + (obj, name, ctx) => { - nameof(HttpContext.Items) => new ObjectValue(new HttpContextItemsWrapper(httpContext.Items)), - _ => NilValue.Instance - }; - } - - return NilValue.Instance; - }); - - o.MemberAccessStrategy.Register((forms, name) => - { - if (name == "Keys") - { - return new ArrayValue(forms.Keys.Select(x => new StringValue(x))); - } - - return new ArrayValue(forms[name].Select(x => new StringValue(x)).ToArray()); - }); - - o.MemberAccessStrategy.Register((httpContext, name) => httpContext.Items[name]); - o.MemberAccessStrategy.Register((queries, name) => queries[name].ToArray()); - o.MemberAccessStrategy.Register((cookies, name) => cookies.RequestCookieCollection[name]); - o.MemberAccessStrategy.Register((headers, name) => headers.HeaderDictionary[name].ToArray()); - o.MemberAccessStrategy.Register((headers, name) => headers.RouteValueDictionary[name]); - - }) - .AddLiquidFilter("append_version") - .AddLiquidFilter("resource_url") - .AddLiquidFilter("sanitize_html"); + var request = ((LiquidTemplateContext)ctx).Services.GetRequiredService().HttpContext?.Request; + if (request != null) + { + return name switch + { + nameof(HttpRequest.QueryString) => new StringValue(request.QueryString.Value), + nameof(HttpRequest.ContentType) => new StringValue(request.ContentType), + nameof(HttpRequest.ContentLength) => NumberValue.Create(request.ContentLength ?? 0), + nameof(HttpRequest.Cookies) => new ObjectValue(new CookieCollectionWrapper(request.Cookies)), + nameof(HttpRequest.Headers) => new ObjectValue(new HeaderDictionaryWrapper(request.Headers)), + nameof(HttpRequest.Query) => new ObjectValue(new QueryCollection(request.Query.ToDictionary(kv => kv.Key, kv => kv.Value))), + nameof(HttpRequest.Form) => request.HasFormContentType ? (FluidValue)new ObjectValue(request.Form) : NilValue.Instance, + nameof(HttpRequest.Protocol) => new StringValue(request.Protocol), + nameof(HttpRequest.Path) => new StringValue(request.Path.Value), + nameof(HttpRequest.PathBase) => new StringValue(request.PathBase.Value), + nameof(HttpRequest.Host) => new StringValue(request.Host.Value), + nameof(HttpRequest.IsHttps) => BooleanValue.Create(request.IsHttps), + nameof(HttpRequest.Scheme) => new StringValue(request.Scheme), + nameof(HttpRequest.Method) => new StringValue(request.Method), + nameof(HttpRequest.RouteValues) => new ObjectValue(new RouteValueDictionaryWrapper(request.RouteValues)), + + // Provides correct escaping to reconstruct a request or redirect URI. + "UriHost" => new StringValue(request.Host.ToUriComponent(), encode: false), + "UriPath" => new StringValue(request.Path.ToUriComponent(), encode: false), + "UriPathBase" => new StringValue(request.PathBase.ToUriComponent(), encode: false), + "UriQueryString" => new StringValue(request.QueryString.ToUriComponent(), encode: false), + + _ => NilValue.Instance + }; + } + + return NilValue.Instance; + } + ); + + o.Scope.SetValue("HttpContext", new ObjectValue(new LiquidHttpContextAccessor())); + o.MemberAccessStrategy.Register( + (obj, name, ctx) => + { + var httpContext = ((LiquidTemplateContext)ctx).Services.GetRequiredService().HttpContext; + if (httpContext != null) + { + return name switch + { + nameof(HttpContext.Items) => new ObjectValue(new HttpContextItemsWrapper(httpContext.Items)), + _ => NilValue.Instance + }; + } + + return NilValue.Instance; + } + ); + + o.MemberAccessStrategy.Register( + (forms, name) => + { + if (name == "Keys") + { + return new ArrayValue(forms.Keys.Select(x => new StringValue(x))); + } + + return new ArrayValue(forms[name].Select(x => new StringValue(x)).ToArray()); + } + ); + + o.MemberAccessStrategy.Register((httpContext, name) => httpContext.Items[name]); + o.MemberAccessStrategy.Register((queries, name) => queries[name].ToArray()); + o.MemberAccessStrategy.Register((cookies, name) => cookies.RequestCookieCollection[name]); + o.MemberAccessStrategy.Register((headers, name) => headers.HeaderDictionary[name].ToArray()); + o.MemberAccessStrategy.Register((headers, name) => headers.RouteValueDictionary[name]); + }) + .AddLiquidFilter("append_version") + .AddLiquidFilter("resource_url") + .AddLiquidFilter("sanitize_html"); }); return builder; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperActivator.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperActivator.cs index 3b8a4f9b287..ee70b8b7a28 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperActivator.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperActivator.cs @@ -27,16 +27,12 @@ public class LiquidTagHelperActivator private readonly Func _activatorByService; private readonly Action _viewContextSetter; - public LiquidTagHelperActivator() - { - } + public LiquidTagHelperActivator() { } public LiquidTagHelperActivator(Type type) { - var accessibleProperties = type.GetProperties().Where(p => - (p.GetCustomAttribute() == null || - p.GetCustomAttribute() != null) && - p.GetSetMethod() != null); + var accessibleProperties = type.GetProperties() + .Where(p => (p.GetCustomAttribute() == null || p.GetCustomAttribute() != null) && p.GetSetMethod() != null); foreach (var property in accessibleProperties) { @@ -77,49 +73,52 @@ public LiquidTagHelperActivator(Type type) foreach (var propertyName in allNames) { - _setters.Add(propertyName, (h, mp, vd, k, v) => - { - object value = null; - - if (property.PropertyType.IsEnum) - { - value = Enum.Parse(property.PropertyType, v.ToStringValue()); - } - else if (property.PropertyType == typeof(string)) - { - value = v.ToStringValue(); - } - else if (property.PropertyType == typeof(bool)) - { - value = Convert.ToBoolean(v.ToStringValue()); - } - else if (property.PropertyType == typeof(bool?)) + _setters.Add( + propertyName, + (h, mp, vd, k, v) => { - value = v.IsNil() ? null : (bool?)Convert.ToBoolean(v.ToStringValue()); + object value = null; + + if (property.PropertyType.IsEnum) + { + value = Enum.Parse(property.PropertyType, v.ToStringValue()); + } + else if (property.PropertyType == typeof(string)) + { + value = v.ToStringValue(); + } + else if (property.PropertyType == typeof(bool)) + { + value = Convert.ToBoolean(v.ToStringValue()); + } + else if (property.PropertyType == typeof(bool?)) + { + value = v.IsNil() ? null : (bool?)Convert.ToBoolean(v.ToStringValue()); + } + else if (property.PropertyType == typeof(IDictionary)) + { + var dictionary = (IDictionary)getter(h); + dictionary[k] = v.ToStringValue(); + value = dictionary; + } + else if (property.PropertyType == typeof(IDictionary)) + { + var dictionary = (IDictionary)getter(h); + dictionary[k] = v.ToObjectValue(); + value = dictionary; + } + else if (property.PropertyType == typeof(ModelExpression)) + { + value = mp.CreateModelExpression(vd, v.ToStringValue()); + } + else + { + value = v.ToObjectValue(); + } + + setter(h, value); } - else if (property.PropertyType == typeof(IDictionary)) - { - var dictionary = (IDictionary)getter(h); - dictionary[k] = v.ToStringValue(); - value = dictionary; - } - else if (property.PropertyType == typeof(IDictionary)) - { - var dictionary = (IDictionary)getter(h); - dictionary[k] = v.ToObjectValue(); - value = dictionary; - } - else if (property.PropertyType == typeof(ModelExpression)) - { - value = mp.CreateModelExpression(vd, v.ToStringValue()); - } - else - { - value = v.ToObjectValue(); - } - - setter(h, value); - }); + ); } } @@ -137,13 +136,18 @@ public LiquidTagHelperActivator(Type type) var genericFactory = typeof(ReusableTagHelperFactory<>).MakeGenericType(type); var factoryMethod = genericFactory.GetMethod("CreateTagHelper"); - _activatorByFactory = Delegate.CreateDelegate(typeof(Func), - factoryMethod) as Func; + _activatorByFactory = + Delegate.CreateDelegate(typeof(Func), factoryMethod) as Func; } } - public ITagHelper Create(ITagHelperFactory factory, ViewContext context, FilterArguments arguments, - out TagHelperAttributeList contextAttributes, out TagHelperAttributeList outputAttributes) + public ITagHelper Create( + ITagHelperFactory factory, + ViewContext context, + FilterArguments arguments, + out TagHelperAttributeList contextAttributes, + out TagHelperAttributeList outputAttributes + ) { contextAttributes = []; outputAttributes = []; @@ -214,7 +218,8 @@ public ITagHelper Create(ITagHelperFactory factory, ViewContext context, FilterA return tagHelper; } - private class ReusableTagHelperFactory where T : class, ITagHelper + private class ReusableTagHelperFactory + where T : class, ITagHelper { public static ITagHelper CreateTagHelper(ITagHelperFactory tagHelperFactory, ViewContext viewContext) { @@ -232,11 +237,10 @@ private static Action MakeFastPropertySetter(Type type, Property return (Action)setterDelegate; } - private static readonly MethodInfo _callPropertySetterOpenGenericMethod = - typeof(LiquidTagHelperActivator).GetTypeInfo().GetDeclaredMethod(nameof(CallPropertySetter)); + private static readonly MethodInfo _callPropertySetterOpenGenericMethod = typeof(LiquidTagHelperActivator).GetTypeInfo().GetDeclaredMethod(nameof(CallPropertySetter)); - private static void CallPropertySetter(Action setter, object target, object value) - => setter((TDeclaringType)target, (TValue)value); + private static void CallPropertySetter(Action setter, object target, object value) => + setter((TDeclaringType)target, (TValue)value); private static Func MakeFastPropertyGetter(Type type, PropertyInfo prop) { @@ -248,10 +252,8 @@ private static Func MakeFastPropertyGetter(Type type, PropertyIn return (Func)getterDelegate; } - private static readonly MethodInfo _callPropertyGetterOpenGenericMethod = - typeof(LiquidTagHelperActivator).GetTypeInfo().GetDeclaredMethod(nameof(CallPropertyGetter)); + private static readonly MethodInfo _callPropertyGetterOpenGenericMethod = typeof(LiquidTagHelperActivator).GetTypeInfo().GetDeclaredMethod(nameof(CallPropertyGetter)); - private static object CallPropertyGetter(Func getter, object target) - => getter((TDeclaringType)target); + private static object CallPropertyGetter(Func getter, object target) => getter((TDeclaringType)target); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperFactory.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperFactory.cs index 117e0aa84f2..9022f10873d 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperFactory.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperFactory.cs @@ -49,21 +49,19 @@ private void EnsureMatchings() foreach (var tagHelper in feature.TagHelpers) { - var matching = _allMatchings.GetOrAdd(tagHelper.AsType(), type => - { - var descriptorBuilder = TagHelperDescriptorBuilder.Create( - type.FullName, type.Assembly.GetName().Name); - - descriptorBuilder.SetTypeName(type.FullName); - AddTagMatchingRules(type, descriptorBuilder); - var descriptor = descriptorBuilder.Build(); - - return new LiquidTagHelperMatching( - descriptor.Name, - descriptor.AssemblyName, - descriptor.TagMatchingRules - ); - }); + var matching = _allMatchings.GetOrAdd( + tagHelper.AsType(), + type => + { + var descriptorBuilder = TagHelperDescriptorBuilder.Create(type.FullName, type.Assembly.GetName().Name); + + descriptorBuilder.SetTypeName(type.FullName); + AddTagMatchingRules(type, descriptorBuilder); + var descriptor = descriptorBuilder.Build(); + + return new LiquidTagHelperMatching(descriptor.Name, descriptor.AssemblyName, descriptor.TagMatchingRules); + } + ); matchings.Add(matching); } @@ -87,8 +85,13 @@ public LiquidTagHelperActivator GetActivator(string helper, IEnumerable return LiquidTagHelperActivator.None; } - public ITagHelper CreateTagHelper(LiquidTagHelperActivator activator, ViewContext context, FilterArguments arguments, - out TagHelperAttributeList contextAttributes, out TagHelperAttributeList outputAttributes) + public ITagHelper CreateTagHelper( + LiquidTagHelperActivator activator, + ViewContext context, + FilterArguments arguments, + out TagHelperAttributeList contextAttributes, + out TagHelperAttributeList outputAttributes + ) { return activator.Create(_factory, context, arguments, out contextAttributes, out outputAttributes); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperMatching.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperMatching.cs index 37aabe391ee..8e39ae8cbc5 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperMatching.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperMatching.cs @@ -8,12 +8,10 @@ namespace OrchardCore.DisplayManagement.Liquid.TagHelpers public class LiquidTagHelperMatching { private const string AspPrefix = "asp-"; - public readonly static LiquidTagHelperMatching None = new(); + public static readonly LiquidTagHelperMatching None = new(); public readonly TagMatchingRuleDescriptor[] _rules = []; - public LiquidTagHelperMatching() - { - } + public LiquidTagHelperMatching() { } public LiquidTagHelperMatching(string name, string assemblyName, IEnumerable tagMatchingRules) { @@ -40,32 +38,34 @@ private static bool Predicate(TagMatchingRuleDescriptor rule, string helper, IEn } // Are all required attributes present? - var allRequired = rule.Attributes.All(attr => arguments.Any(name => - { - // Exact match - if (string.Equals(name, attr.Name, StringComparison.OrdinalIgnoreCase)) + var allRequired = rule.Attributes.All(attr => + arguments.Any(name => { - return true; - } - - // Check by replacing all '_' with '-', e.g. asp_src will map to asp-src - name = name.Replace('_', '-'); + // Exact match + if (string.Equals(name, attr.Name, StringComparison.OrdinalIgnoreCase)) + { + return true; + } - if (string.Equals(name, attr.Name, StringComparison.OrdinalIgnoreCase)) - { - return true; - } + // Check by replacing all '_' with '-', e.g. asp_src will map to asp-src + name = name.Replace('_', '-'); - if (attr.Name.StartsWith(AspPrefix, StringComparison.Ordinal)) - { - if (name.AsSpan().Equals(attr.Name.AsSpan(AspPrefix.Length), StringComparison.OrdinalIgnoreCase)) + if (string.Equals(name, attr.Name, StringComparison.OrdinalIgnoreCase)) { return true; } - } - return false; - })); + if (attr.Name.StartsWith(AspPrefix, StringComparison.Ordinal)) + { + if (name.AsSpan().Equals(attr.Name.AsSpan(AspPrefix.Length), StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + + return false; + }) + ); if (allRequired) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs index e0584e1ca29..d5dd82fde51 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs @@ -28,9 +28,7 @@ private class DefaultRequiredAttributeParser private static readonly char[] _invalidPlainAttributeNameCharacters = [' ', '\t', ',', RequiredAttributeWildcardSuffix]; - private static readonly char[] _invalidCssAttributeNameCharacters = (new[] { ' ', '\t', ',', ']' }) - .Concat(_cssValueComparisons.Keys) - .ToArray(); + private static readonly char[] _invalidCssAttributeNameCharacters = (new[] { ' ', '\t', ',', ']' }).Concat(_cssValueComparisons.Keys).ToArray(); private static readonly char[] _invalidCssQuotelessValueCharacters = [' ', '\t', ']']; @@ -100,8 +98,7 @@ public void AddRequiredAttributes(TagMatchingRuleDescriptorBuilder ruleBuilder) { break; } - } - while (!AtEnd); + } while (!AtEnd); } private void ParsePlainSelector(RequiredAttributeDescriptorBuilder attributeBuilder) diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AnchorTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AnchorTag.cs index 7194fe1bc7d..51da4156491 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AnchorTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AnchorTag.cs @@ -22,7 +22,13 @@ public bool Match(List argumentsList) return true; } - public async ValueTask WriteToAsync(List argumentsList, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, LiquidTemplateContext context) + public async ValueTask WriteToAsync( + List argumentsList, + IReadOnlyList statements, + TextWriter writer, + TextEncoder encoder, + LiquidTemplateContext context + ) { var services = context.Services; var viewContext = context.ViewContext; @@ -46,15 +52,33 @@ public async ValueTask WriteToAsync(List argumentsLi { switch (argument.Name) { - case "action": action = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "controller": controller = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "area": area = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "page": page = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "page_handler": pageHandler = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "fragment": fragment = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "host": host = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "protocol": protocol = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "route": route = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "action": + action = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "controller": + controller = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "area": + area = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "page": + page = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "page_handler": + pageHandler = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "fragment": + fragment = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "host": + host = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "protocol": + protocol = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "route": + route = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; case "all_route_data": @@ -67,7 +91,9 @@ public async ValueTask WriteToAsync(List argumentsLi break; - case "href": href = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "href": + href = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; default: @@ -89,16 +115,18 @@ public async ValueTask WriteToAsync(List argumentsLi // If "href" is already set, it means the user is attempting to use a normal anchor. if (!string.IsNullOrEmpty(href)) { - if (action != null || - controller != null || - area != null || - page != null || - pageHandler != null || - route != null || - protocol != null || - host != null || - fragment != null || - (routeValues != null && routeValues.Count > 0)) + if ( + action != null + || controller != null + || area != null + || page != null + || pageHandler != null + || route != null + || protocol != null + || host != null + || fragment != null + || (routeValues != null && routeValues.Count > 0) + ) { // User specified an href and one of the bound attributes; can't determine the href attribute. throw new InvalidOperationException("Cannot override href with other properties"); @@ -141,7 +169,8 @@ public async ValueTask WriteToAsync(List argumentsLi hostname: host, fragment: fragment, routeValues: localRouteValues, - htmlAttributes: null); + htmlAttributes: null + ); } else if (routeLink) { @@ -153,20 +182,22 @@ public async ValueTask WriteToAsync(List argumentsLi hostName: host, fragment: fragment, routeValues: localRouteValues, - htmlAttributes: null); + htmlAttributes: null + ); } else { tagBuilder = generator.GenerateActionLink( - viewContext, - linkText: string.Empty, - actionName: action, - controllerName: controller, - protocol: protocol, - hostname: host, - fragment: fragment, - routeValues: localRouteValues, - htmlAttributes: null); + viewContext, + linkText: string.Empty, + actionName: action, + controllerName: controller, + protocol: protocol, + hostname: host, + fragment: fragment, + routeValues: localRouteValues, + htmlAttributes: null + ); } foreach (var attribute in customAttributes) diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/DefaultAnchorTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/DefaultAnchorTag.cs index 72c02e68a8a..8c4cf049d44 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/DefaultAnchorTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/DefaultAnchorTag.cs @@ -12,7 +12,13 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class DefaultAnchorTag { - public static ValueTask WriteToAsync(List argumentsList, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static ValueTask WriteToAsync( + List argumentsList, + IReadOnlyList statements, + TextWriter writer, + TextEncoder encoder, + TemplateContext context + ) { var services = ((LiquidTemplateContext)context).Services; var anchorTags = services.GetRequiredService>(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/FluidTagHelper.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/FluidTagHelper.cs index eb0acd1fd1b..d021b3cbd0a 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/FluidTagHelper.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/FluidTagHelper.cs @@ -22,12 +22,25 @@ public static ValueTask WriteArgumentsTagHelperAsync(List WriteArgumentsBlockHelperAsync(List arguments, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static ValueTask WriteArgumentsBlockHelperAsync( + List arguments, + IReadOnlyList statements, + TextWriter writer, + TextEncoder encoder, + TemplateContext context + ) { return WriteToAsync(null, arguments, statements, writer, encoder, context); } - public static async ValueTask WriteToAsync(string identifier, List arguments, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync( + string identifier, + List arguments, + IReadOnlyList statements, + TextWriter writer, + TextEncoder encoder, + TemplateContext context + ) { var services = ((LiquidTemplateContext)context).Services; @@ -61,8 +74,7 @@ public static async ValueTask WriteToAsync(string identifier, List WriteToAsync(string identifier, List Task.FromResult(new DefaultTagHelperContent().AppendHtml(content)) - ); + tagHelperOutput = new TagHelperOutput(identifier, outputAttributes, (_, e) => Task.FromResult(new DefaultTagHelperContent().AppendHtml(content))); tagHelperOutput.Content.AppendHtml(content); } else { - tagHelperOutput = new TagHelperOutput( - identifier, - outputAttributes, (_, e) => Task.FromResult(new DefaultTagHelperContent()) - ); + tagHelperOutput = new TagHelperOutput(identifier, outputAttributes, (_, e) => Task.FromResult(new DefaultTagHelperContent())); } await tagHelper.ProcessAsync(tagHelperContext, tagHelperOutput); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextRemoveItemTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextRemoveItemTag.cs index e60d7282a96..a3552e9ef30 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextRemoveItemTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextRemoveItemTag.cs @@ -25,7 +25,6 @@ public static async ValueTask WriteToAsync(Expression argument, Text { httpContext.Items.Remove(itemKey); } - } return Completion.Normal; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/IAnchorTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/IAnchorTag.cs index ce2f658a005..521111c5ea2 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/IAnchorTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/IAnchorTag.cs @@ -11,7 +11,13 @@ public interface IAnchorTag { bool Match(List argumentsList); - ValueTask WriteToAsync(List argumentsList, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, LiquidTemplateContext context); + ValueTask WriteToAsync( + List argumentsList, + IReadOnlyList statements, + TextWriter writer, + TextEncoder encoder, + LiquidTemplateContext context + ); int Order { get; } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePagerTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePagerTag.cs index 85590ecf825..96ea36911b6 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePagerTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePagerTag.cs @@ -14,16 +14,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ShapePagerTag { - private static readonly HashSet _properties = - [ - "Id", - "PreviousText", - "NextText", - "PreviousClass", - "NextClass", - "TagName", - "ItemTagName" - ]; + private static readonly HashSet _properties = ["Id", "PreviousText", "NextText", "PreviousClass", "NextClass", "TagName", "ItemTagName"]; public static async ValueTask WriteToAsync(ValueTuple> arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePositionTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePositionTag.cs index 1a5c3db03f9..caa68100171 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePositionTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePositionTag.cs @@ -21,6 +21,5 @@ public static async ValueTask WriteToAsync(ValueTuple WriteToAsync(List argu { switch (argument.Name) { - case "cache_id": cacheId = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "cache_id": + cacheId = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; #pragma warning disable CA1806 // Do not ignore method results - case "cache_fixed_duration": TimeSpan.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), out var fd); cacheFixedDuration = fd; break; - case "cache_sliding_duration": TimeSpan.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), out var sd); cacheSlidingDuration = sd; break; + case "cache_fixed_duration": + TimeSpan.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), out var fd); + cacheFixedDuration = fd; + break; + case "cache_sliding_duration": + TimeSpan.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), out var sd); + cacheSlidingDuration = sd; + break; #pragma warning restore CA1806 // Do not ignore method results // case "cache_dependency": cacheDependency = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "cache_context": cacheContext = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "cache_tag": cacheTag = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - - case "id": id = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "alternate": alternate = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; - case "wrapper": wrapper = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "cache_context": + cacheContext = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "cache_tag": + cacheTag = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + + case "id": + id = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "alternate": + alternate = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; + case "wrapper": + wrapper = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; case null: case "type": - case "": type = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; + case "": + type = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); + break; - default: (customAttributes ??= [])[argument.Name.ToPascalCaseUnderscore()] = (await argument.Expression.EvaluateAsync(context)).ToObjectValue(); break; + default: + (customAttributes ??= [])[argument.Name.ToPascalCaseUnderscore()] = (await argument.Expression.EvaluateAsync(context)).ToObjectValue(); + break; } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ZoneTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ZoneTag.cs index c45ab9c32d8..69cd32c16ba 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ZoneTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ZoneTag.cs @@ -19,7 +19,8 @@ public static async ValueTask WriteToAsync( IReadOnlyList statements, TextWriter writer, TextEncoder encoder, - TemplateContext context) + TemplateContext context + ) { var services = ((LiquidTemplateContext)context).Services; var layoutAccessor = services.GetRequiredService(); @@ -74,10 +75,10 @@ public static async ValueTask WriteToAsync( else { logger.LogWarning( - "Unable to add shape to the zone using the {{% zone %}} Liquid tag because the zone's type " + - "is \"{ActualType}\" instead of the expected {ExpectedType}", + "Unable to add shape to the zone using the {{% zone %}} Liquid tag because the zone's type " + "is \"{ActualType}\" instead of the expected {ExpectedType}", zone.GetType().FullName, - nameof(Shape)); + nameof(Shape) + ); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs index e7e8bcc5663..880540b276f 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs @@ -33,18 +33,21 @@ public static INamedEnumerable From(IDictionary dictiona public static INamedEnumerable From(object propertyObject) { - var propertiesAccessor = _propertiesAccessors.GetOrAdd(propertyObject.GetType(), type => - { - var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); - var names = properties.Select(x => x.Name).ToArray(); - - return obj => + var propertiesAccessor = _propertiesAccessors.GetOrAdd( + propertyObject.GetType(), + type => { - // properties and names are referenced in the closure - var values = properties.Select(x => x.GetValue(obj, null)).ToArray(); - return new NamedEnumerable(values, names); - }; - }); + var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); + var names = properties.Select(x => x.Name).ToArray(); + + return obj => + { + // properties and names are referenced in the closure + var values = properties.Select(x => x.GetValue(obj, null)).ToArray(); + return new NamedEnumerable(values, names); + }; + } + ); return propertiesAccessor(propertyObject); } @@ -206,10 +209,7 @@ T IDictionary.this[string key] ICollection IDictionary.Keys { - get - { - return _names; - } + get { return _names; } } ICollection IDictionary.Values diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/BaseDisplayManager.cs b/src/OrchardCore/OrchardCore.DisplayManagement/BaseDisplayManager.cs index b9ed6ac1ffd..bc7c9db845d 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/BaseDisplayManager.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/BaseDisplayManager.cs @@ -13,10 +13,7 @@ public abstract class BaseDisplayManager private readonly IShapeFactory _shapeFactory; private readonly IEnumerable _placementProviders; - public BaseDisplayManager( - IShapeFactory shapeFactory, - IEnumerable placementProviders - ) + public BaseDisplayManager(IShapeFactory shapeFactory, IEnumerable placementProviders) { _shapeFactory = shapeFactory; _placementProviders = placementProviders; @@ -39,7 +36,13 @@ protected async Task BindPlacementAsync(IBuildShapeContext context) context.FindPlacement = (shapeType, differentiator, displayType, displayContext) => FindPlacementImpl(resolvers, shapeType, differentiator, displayType, context); } - private static PlacementInfo FindPlacementImpl(IList placementResolvers, string shapeType, string differentiator, string displayType, IBuildShapeContext context) + private static PlacementInfo FindPlacementImpl( + IList placementResolvers, + string shapeType, + string differentiator, + string displayType, + IBuildShapeContext context + ) { var delimiterIndex = shapeType.IndexOf("__", StringComparison.Ordinal); @@ -48,22 +51,17 @@ private static PlacementInfo FindPlacementImpl(IList pla shapeType = shapeType[..delimiterIndex]; } - var placementContext = new ShapePlacementContext( - shapeType, - displayType, - differentiator, - context.Shape - ); + var placementContext = new ShapePlacementContext(shapeType, displayType, differentiator, context.Shape); - return placementResolvers.Aggregate(null, (prev, resolver) => - PlacementInfoExtensions.Combine(prev, resolver.ResolvePlacement(placementContext)) + return placementResolvers.Aggregate( + null, + (prev, resolver) => PlacementInfoExtensions.Combine(prev, resolver.ResolvePlacement(placementContext)) ); } protected ValueTask CreateContentShapeAsync(string actualShapeType) { - return _shapeFactory.CreateAsync(actualShapeType, () => - new ValueTask(new ZoneHolding(() => _shapeFactory.CreateAsync("ContentZone")))); + return _shapeFactory.CreateAsync(actualShapeType, () => new ValueTask(new ZoneHolding(() => _shapeFactory.CreateAsync("ContentZone")))); } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/DefaultShapeTableManager.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/DefaultShapeTableManager.cs index 05f07e0d972..48ea080c503 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/DefaultShapeTableManager.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/DefaultShapeTableManager.cs @@ -37,7 +37,8 @@ public DefaultShapeTableManager( IExtensionManager extensionManager, ITypeFeatureProvider typeFeatureProvider, IMemoryCache memoryCache, - ILogger logger) + ILogger logger + ) { _hostingEnvironment = hostingEnvironment; _bindingStrategies = bindingStrategies; @@ -48,8 +49,7 @@ public DefaultShapeTableManager( _logger = logger; } - public ShapeTable GetShapeTable(string themeId) - => GetShapeTableAsync(themeId).GetAwaiter().GetResult(); + public ShapeTable GetShapeTable(string themeId) => GetShapeTableAsync(themeId).GetAwaiter().GetResult(); public async Task GetShapeTableAsync(string themeId) { @@ -89,9 +89,7 @@ public async Task GetShapeTableAsync(string themeId) } } - var enabledAndOrderedFeatureIds = (await _shellFeaturesManager.GetEnabledFeaturesAsync()) - .Select(f => f.Id) - .ToList(); + var enabledAndOrderedFeatureIds = (await _shellFeaturesManager.GetEnabledFeaturesAsync()).Select(f => f.Id).ToList(); // let the application acting as a super theme for shapes rendering. if (enabledAndOrderedFeatureIds.Remove(_hostingEnvironment.ApplicationName)) @@ -104,16 +102,10 @@ public async Task GetShapeTableAsync(string themeId) .Where(sd => IsModuleOrRequestedTheme(sd.Value.Feature, themeId)) .OrderBy(sd => enabledAndOrderedFeatureIds.IndexOf(sd.Value.Feature.Id)) .GroupBy(sd => sd.Value.ShapeType, StringComparer.OrdinalIgnoreCase) - .Select(group => new ShapeDescriptorIndex - ( - shapeType: group.Key, - alterationKeys: group.Select(kv => kv.Key), - descriptors: _shapeDescriptors - )) + .Select(group => new ShapeDescriptorIndex(shapeType: group.Key, alterationKeys: group.Select(kv => kv.Key), descriptors: _shapeDescriptors)) .ToList(); - shapeTable = new ShapeTable - ( + shapeTable = new ShapeTable( descriptors: descriptors.ToDictionary(sd => sd.ShapeType, x => (ShapeDescriptor)x, StringComparer.OrdinalIgnoreCase), bindings: descriptors.SelectMany(sd => sd.Bindings).ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase) ); @@ -129,7 +121,8 @@ public async Task GetShapeTableAsync(string themeId) private static void BuildDescriptors( IShapeTableProvider bindingStrategy, IEnumerable builtAlterations, - Dictionary shapeDescriptors) + Dictionary shapeDescriptors + ) { var alterationSets = builtAlterations.GroupBy(a => a.Feature.Id + a.ShapeType); @@ -137,17 +130,11 @@ private static void BuildDescriptors( { var firstAlteration = alterations.First(); - var key = bindingStrategy.GetType().Name - + firstAlteration.Feature.Id - + firstAlteration.ShapeType.ToLower(); + var key = bindingStrategy.GetType().Name + firstAlteration.Feature.Id + firstAlteration.ShapeType.ToLower(); if (!_shapeDescriptors.ContainsKey(key)) { - var descriptor = new FeatureShapeDescriptor - ( - firstAlteration.Feature, - firstAlteration.ShapeType - ); + var descriptor = new FeatureShapeDescriptor(firstAlteration.Feature, firstAlteration.ShapeType); foreach (var alteration in alterations) { @@ -176,9 +163,7 @@ private bool IsModuleOrRequestedTheme(IFeatureInfo feature, string themeId) private bool IsBaseTheme(string themeFeatureId, string themeId) { - return _extensionManager - .GetFeatureDependencies(themeId) - .Any(f => f.Id == themeFeatureId); + return _extensionManager.GetFeatureDependencies(themeId).Any(f => f.Id == themeFeatureId); } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/FeatureShapeDescriptor.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/FeatureShapeDescriptor.cs index 9e044ec7859..d7404f55a88 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/FeatureShapeDescriptor.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/FeatureShapeDescriptor.cs @@ -33,26 +33,17 @@ public class ShapeDescriptorIndex : ShapeDescriptor private readonly List> _processingAsync; private readonly List> _displayedAsync; - public ShapeDescriptorIndex( - string shapeType, - IEnumerable alterationKeys, - ConcurrentDictionary descriptors) + public ShapeDescriptorIndex(string shapeType, IEnumerable alterationKeys, ConcurrentDictionary descriptors) { ShapeType = shapeType; _descriptors = descriptors; // pre-calculate as much as we can - _alternationDescriptors = alterationKeys - .Select(key => _descriptors[key]) - .ToList(); + _alternationDescriptors = alterationKeys.Select(key => _descriptors[key]).ToList(); - _wrappers = _alternationDescriptors - .SelectMany(sd => sd.Wrappers) - .ToList(); + _wrappers = _alternationDescriptors.SelectMany(sd => sd.Wrappers).ToList(); - _bindingSources = _alternationDescriptors - .SelectMany(sd => sd.BindingSources) - .ToList(); + _bindingSources = _alternationDescriptors.SelectMany(sd => sd.BindingSources).ToList(); _bindings = _alternationDescriptors .SelectMany(sd => sd.Bindings) @@ -60,36 +51,24 @@ public ShapeDescriptorIndex( .Select(kv => kv.Last()) .ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase); - _creatingAsync = _alternationDescriptors - .SelectMany(sd => sd.CreatingAsync) - .ToList(); + _creatingAsync = _alternationDescriptors.SelectMany(sd => sd.CreatingAsync).ToList(); - _createdAsync = _alternationDescriptors - .SelectMany(sd => sd.CreatedAsync) - .ToList(); + _createdAsync = _alternationDescriptors.SelectMany(sd => sd.CreatedAsync).ToList(); - _displayingAsync = _alternationDescriptors - .SelectMany(sd => sd.DisplayingAsync) - .ToList(); + _displayingAsync = _alternationDescriptors.SelectMany(sd => sd.DisplayingAsync).ToList(); - _processingAsync = _alternationDescriptors - .SelectMany(sd => sd.ProcessingAsync) - .ToList(); + _processingAsync = _alternationDescriptors.SelectMany(sd => sd.ProcessingAsync).ToList(); - _displayedAsync = _alternationDescriptors - .SelectMany(sd => sd.DisplayedAsync) - .ToList(); + _displayedAsync = _alternationDescriptors.SelectMany(sd => sd.DisplayedAsync).ToList(); } /// /// The BindingSource is informational text about the source of the Binding delegate. Not used except for /// troubleshooting. /// - public override string BindingSource => - Bindings.TryGetValue(ShapeType, out var binding) ? binding.BindingSource : null; + public override string BindingSource => Bindings.TryGetValue(ShapeType, out var binding) ? binding.BindingSource : null; - public override Func> Binding => - Bindings.TryGetValue(ShapeType, out var binding) ? binding.BindingAsync : null; + public override Func> Binding => Bindings.TryGetValue(ShapeType, out var binding) ? binding.BindingAsync : null; public override IDictionary Bindings => _bindings; @@ -153,10 +132,7 @@ protected PlacementInfo DefaultPlacementAction(ShapePlacementContext context) return null; } - return new PlacementInfo - { - Location = DefaultPlacement - }; + return new PlacementInfo { Location = DefaultPlacement }; } public string ShapeType { get; set; } @@ -165,11 +141,9 @@ protected PlacementInfo DefaultPlacementAction(ShapePlacementContext context) /// The BindingSource is informational text about the source of the Binding delegate. Not used except for /// troubleshooting. /// - public virtual string BindingSource => - Bindings.TryGetValue(ShapeType, out var binding) ? binding.BindingSource : null; + public virtual string BindingSource => Bindings.TryGetValue(ShapeType, out var binding) ? binding.BindingSource : null; - public virtual Func> Binding => - Bindings[ShapeType].BindingAsync; + public virtual Func> Binding => Bindings[ShapeType].BindingAsync; public virtual IDictionary Bindings { get; set; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/IShapeAttributeProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/IShapeAttributeProvider.cs index 361850deb88..ace94c5fcb2 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/IShapeAttributeProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/IShapeAttributeProvider.cs @@ -3,6 +3,4 @@ namespace OrchardCore.DisplayManagement.Descriptors; /// /// Represents a marker interface for classes that have Shape methods tagged with . /// -public interface IShapeAttributeProvider -{ -} +public interface IShapeAttributeProvider { } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/IShapeTableHarvester.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/IShapeTableHarvester.cs index 5db093b3535..c9c2b19b868 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/IShapeTableHarvester.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/IShapeTableHarvester.cs @@ -1,5 +1,3 @@ namespace OrchardCore.DisplayManagement.Descriptors; -public interface IShapeTableHarvester : IShapeTableProvider -{ -} +public interface IShapeTableHarvester : IShapeTableProvider { } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAttributeStrategy/ShapeAttributeBindingStrategy.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAttributeStrategy/ShapeAttributeBindingStrategy.cs index 697a27983a5..cd6225083ac 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAttributeStrategy/ShapeAttributeBindingStrategy.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAttributeStrategy/ShapeAttributeBindingStrategy.cs @@ -21,9 +21,7 @@ public class ShapeAttributeBindingStrategy : ShapeTableProvider, IShapeTableHarv private readonly ITypeFeatureProvider _typeFeatureProvider; private readonly IEnumerable _shapeProviders; - public ShapeAttributeBindingStrategy( - ITypeFeatureProvider typeFeatureProvider, - IEnumerable shapeProviders) + public ShapeAttributeBindingStrategy(ITypeFeatureProvider typeFeatureProvider, IEnumerable shapeProviders) { _typeFeatureProvider = typeFeatureProvider; _shapeProviders = shapeProviders; @@ -51,11 +49,10 @@ public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { var occurrence = iter; var shapeType = occurrence.ShapeAttribute.ShapeType ?? occurrence.MethodInfo.Name; - builder.Describe(shapeType) + builder + .Describe(shapeType) .From(_typeFeatureProvider.GetFeatureForDependency(occurrence.ServiceType)) - .BoundAs( - occurrence.MethodInfo.DeclaringType.FullName + "::" + occurrence.MethodInfo.Name, - CreateDelegate(occurrence)); + .BoundAs(occurrence.MethodInfo.DeclaringType.FullName + "::" + occurrence.MethodInfo.Name, CreateDelegate(occurrence)); } return ValueTask.CompletedTask; @@ -133,7 +130,6 @@ private static Func CreateMethodWrapper(Type type, Met var targetExp = Expression.Parameter(typeof(object), "target"); var castTargetExp = Expression.Convert(targetExp, type); - LambdaExpression lambdaExp; if (method.ReturnType != typeof(void)) @@ -232,14 +228,14 @@ private static Func BindParameter(ParameterInfo paramete }; } - // pre-calculate the default value + // pre-calculate the default value var defaultValue = parameter.ParameterType.IsValueType ? Activator.CreateInstance(parameter.ParameterType) : null; var isDateTimeType = - parameter.ParameterType == typeof(DateTime) || - parameter.ParameterType == typeof(DateTime?) || - parameter.ParameterType == typeof(DateTimeOffset) || - parameter.ParameterType == typeof(DateTimeOffset?); + parameter.ParameterType == typeof(DateTime) + || parameter.ParameterType == typeof(DateTime?) + || parameter.ParameterType == typeof(DateTimeOffset) + || parameter.ParameterType == typeof(DateTimeOffset?); return d => { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PathPlacementNodeFilterProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PathPlacementNodeFilterProvider.cs index bacaeb4ae5d..3dc99a1c8bc 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PathPlacementNodeFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PathPlacementNodeFilterProvider.cs @@ -15,7 +15,10 @@ public PathPlacementNodeFilterProvider(IHttpContextAccessor httpContextAccessor) _httpContextAccessor = httpContextAccessor; } - public string Key { get { return "path"; } } + public string Key + { + get { return "path"; } + } public bool IsMatch(ShapePlacementContext context, object expression) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PlacementFile.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PlacementFile.cs index 545ebc35181..d7cd2a427d4 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PlacementFile.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PlacementFile.cs @@ -3,9 +3,7 @@ namespace OrchardCore.DisplayManagement.Descriptors.ShapePlacementStrategy { - public class PlacementFile : Dictionary - { - } + public class PlacementFile : Dictionary { } public class PlacementNode { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/ShapePlacementParsingStrategy.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/ShapePlacementParsingStrategy.cs index 78b18835e1a..2d051f0b5c2 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/ShapePlacementParsingStrategy.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/ShapePlacementParsingStrategy.cs @@ -23,7 +23,8 @@ public class ShapePlacementParsingStrategy : ShapeTableProvider, IShapeTableHarv public ShapePlacementParsingStrategy( IHostEnvironment hostingEnvironment, IShellFeaturesManager shellFeaturesManager, - IEnumerable placementParseMatchProviders) + IEnumerable placementParseMatchProviders + ) { _hostingEnvironment = hostingEnvironment; _shellFeaturesManager = shellFeaturesManager; @@ -32,8 +33,7 @@ public ShapePlacementParsingStrategy( public override async ValueTask DiscoverAsync(ShapeTableBuilder builder) { - var enabledFeatures = (await _shellFeaturesManager.GetEnabledFeaturesAsync()) - .Where(Feature => !builder.ExcludedFeatureIds.Contains(Feature.Id)); + var enabledFeatures = (await _shellFeaturesManager.GetEnabledFeaturesAsync()).Where(Feature => !builder.ExcludedFeatureIds.Contains(Feature.Id)); foreach (var featureDescriptor in enabledFeatures) { @@ -45,8 +45,7 @@ private Task ProcessFeatureDescriptorAsync(ShapeTableBuilder builder, IFeatureIn { // TODO : (ngm) Replace with configuration Provider and read from that. // Dont use JSON Deserializer directly. - var virtualFileInfo = _hostingEnvironment - .GetExtensionFileInfo(featureDescriptor.Extension, "placement.json"); + var virtualFileInfo = _hostingEnvironment.GetExtensionFileInfo(featureDescriptor.Extension, "placement.json"); if (virtualFileInfo.Exists) { @@ -79,10 +78,7 @@ private void ProcessPlacementFile(ShapeTableBuilder builder, IFeatureInfo featur predicate = matches.Aggregate(predicate, BuildPredicate); } - var placement = new PlacementInfo - { - Location = filter.Location, - }; + var placement = new PlacementInfo { Location = filter.Location, }; if (filter.Alternates?.Length > 0) { @@ -96,9 +92,7 @@ private void ProcessPlacementFile(ShapeTableBuilder builder, IFeatureInfo featur placement.ShapeType = filter.ShapeType; - builder.Describe(shapeType) - .From(featureDescriptor) - .Placement(ctx => predicate(ctx), placement); + builder.Describe(shapeType).From(featureDescriptor).Placement(ctx => predicate(ctx), placement); } } } @@ -118,14 +112,16 @@ public static bool CheckFilter(ShapePlacementContext ctx, PlacementNode filter) return true; } - private Func BuildPredicate(Func predicate, - KeyValuePair term) + private Func BuildPredicate(Func predicate, KeyValuePair term) { return BuildPredicate(predicate, term, _placementParseMatchProviders); } - public static Func BuildPredicate(Func predicate, - KeyValuePair term, IEnumerable placementMatchProviders) + public static Func BuildPredicate( + Func predicate, + KeyValuePair term, + IEnumerable placementMatchProviders + ) { if (placementMatchProviders != null) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeProviderExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeProviderExtensions.cs index 88c82b846e5..a0f84907e65 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeProviderExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeProviderExtensions.cs @@ -5,11 +5,11 @@ namespace OrchardCore.DisplayManagement.Descriptors; public static class ShapeProviderExtensions { - public static IServiceCollection AddShapeAttributes(this IServiceCollection services) where T : class, IShapeAttributeProvider + public static IServiceCollection AddShapeAttributes(this IServiceCollection services) + where T : class, IShapeAttributeProvider { services.TryAddScoped(); - services.TryAddEnumerable( - ServiceDescriptor.Scoped(sp => sp.GetRequiredService())); + services.TryAddEnumerable(ServiceDescriptor.Scoped(sp => sp.GetRequiredService())); return services; } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTablePlacementProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTablePlacementProvider.cs index e11a2ee0ed0..556fc3658f3 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTablePlacementProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTablePlacementProvider.cs @@ -9,10 +9,7 @@ public class ShapeTablePlacementProvider : IShapePlacementProvider private readonly IShapeTableManager _shapeTableManager; private readonly IThemeManager _themeManager; - public ShapeTablePlacementProvider( - IShapeTableManager shapeTableManager, - IThemeManager themeManager - ) + public ShapeTablePlacementProvider(IShapeTableManager shapeTableManager, IThemeManager themeManager) { _shapeTableManager = shapeTableManager; _themeManager = themeManager; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTableProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTableProvider.cs index 057df85a480..02afba7d651 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTableProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTableProvider.cs @@ -6,9 +6,7 @@ namespace OrchardCore.DisplayManagement.Descriptors; public abstract class ShapeTableProvider : IShapeTableProvider { [Obsolete($"Instead, utilize the {nameof(IShapeTableProvider.DiscoverAsync)} method. This current method is slated for removal in upcoming releases.")] - public void Discover(ShapeTableBuilder builder) - { - } + public void Discover(ShapeTableBuilder builder) { } public abstract ValueTask DiscoverAsync(ShapeTableBuilder builder); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/BasicShapeTemplateHarvester.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/BasicShapeTemplateHarvester.cs index 2d254f62ff4..85bd41c696d 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/BasicShapeTemplateHarvester.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/BasicShapeTemplateHarvester.cs @@ -16,19 +16,12 @@ public IEnumerable HarvestShape(HarvestShapeInfo info) var lastDot = info.FileName.LastIndexOf('.'); if (lastDot <= 0 || lastDot < lastDash) { - yield return new HarvestShapeHit - { - ShapeType = Adjust(info.SubPath, info.FileName, null), - }; + yield return new HarvestShapeHit { ShapeType = Adjust(info.SubPath, info.FileName, null), }; } else { var displayType = info.FileName[(lastDot + 1)..]; - yield return new HarvestShapeHit - { - ShapeType = Adjust(info.SubPath, info.FileName[..lastDot], displayType), - DisplayType = displayType, - }; + yield return new HarvestShapeHit { ShapeType = Adjust(info.SubPath, info.FileName[..lastDot], displayType), DisplayType = displayType, }; } } @@ -55,9 +48,7 @@ private static string Adjust(string subPath, string fileName, string displayType return (shapeType + "_" + displayType).ToLowerInvariant(); } - return string.Concat( - shapeType.AsSpan(0, firstBreakingSeparator), "_", displayType, shapeType.AsSpan(firstBreakingSeparator)) - .ToLowerInvariant(); + return string.Concat(shapeType.AsSpan(0, firstBreakingSeparator), "_", displayType, shapeType.AsSpan(firstBreakingSeparator)).ToLowerInvariant(); } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/ShapeTemplateBindingStrategy.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/ShapeTemplateBindingStrategy.cs index 1abd79f31a3..986c0f6696e 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/ShapeTemplateBindingStrategy.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/ShapeTemplateBindingStrategy.cs @@ -28,7 +28,8 @@ public ShapeTemplateBindingStrategy( IShellFeaturesManager shellFeaturesManager, IEnumerable shapeTemplateViewEngines, IShapeTemplateFileProviderAccessor fileProviderAccessor, - ILogger logger) + ILogger logger + ) { _harvesters = harvesters; _shellFeaturesManager = shellFeaturesManager; @@ -43,21 +44,13 @@ public override async ValueTask DiscoverAsync(ShapeTableBuilder builder) { _logger.LogInformation("Start discovering shapes"); - var harvesterInfos = _harvesters - .Select(harvester => new - { - harvester, - subPaths = harvester.SubPaths() - }) - .ToList(); + var harvesterInfos = _harvesters.Select(harvester => new { harvester, subPaths = harvester.SubPaths() }).ToList(); var enabledFeatures = await _shellFeaturesManager.GetEnabledFeaturesAsync(); var enabledFeatureIds = enabledFeatures.Select(f => f.Id).ToList(); // Excludes the extensions whose templates are already associated to an excluded feature that is still enabled. - var activeExtensions = Once(enabledFeatures) - .Where(e => !e.Features.Any(f => builder.ExcludedFeatureIds.Contains(f.Id) && enabledFeatureIds.Contains(f.Id))) - .ToArray(); + var activeExtensions = Once(enabledFeatures).Where(e => !e.Features.Any(f => builder.ExcludedFeatureIds.Contains(f.Id) && enabledFeatureIds.Contains(f.Id))).ToArray(); if (_viewEnginesByExtension.Count == 0) { @@ -73,49 +66,69 @@ public override async ValueTask DiscoverAsync(ShapeTableBuilder builder) } } - var hits = activeExtensions.Select(extensionDescriptor => - { - _logger.LogInformation("Start discovering candidate views filenames"); - - var pathContexts = harvesterInfos.SelectMany(harvesterInfo => harvesterInfo.subPaths.Select(subPath => + var hits = activeExtensions + .Select(extensionDescriptor => { - var filePaths = _fileProviderAccessor.FileProvider.GetViewFilePaths( - PathExtensions.Combine(extensionDescriptor.SubPath, subPath), - _viewEnginesByExtension.Keys.ToArray(), - inViewsFolder: true, inDepth: false).ToArray(); - - return new { harvesterInfo.harvester, subPath, filePaths }; - })) - .ToList(); - - _logger.LogInformation("Done discovering candidate views filenames"); - - var fileContexts = pathContexts.SelectMany(pathContext => _shapeTemplateViewEngines.SelectMany(ve => - { - return pathContext.filePaths.Select( - filePath => new + _logger.LogInformation("Start discovering candidate views filenames"); + + var pathContexts = harvesterInfos + .SelectMany(harvesterInfo => + harvesterInfo.subPaths.Select(subPath => + { + var filePaths = _fileProviderAccessor + .FileProvider.GetViewFilePaths( + PathExtensions.Combine(extensionDescriptor.SubPath, subPath), + _viewEnginesByExtension.Keys.ToArray(), + inViewsFolder: true, + inDepth: false + ) + .ToArray(); + + return new + { + harvesterInfo.harvester, + subPath, + filePaths + }; + }) + ) + .ToList(); + + _logger.LogInformation("Done discovering candidate views filenames"); + + var fileContexts = pathContexts.SelectMany(pathContext => + _shapeTemplateViewEngines.SelectMany(ve => { - fileName = Path.GetFileNameWithoutExtension(filePath), - relativePath = filePath, - pathContext + return pathContext.filePaths.Select(filePath => new + { + fileName = Path.GetFileNameWithoutExtension(filePath), + relativePath = filePath, + pathContext + }); + }) + ); + + var shapeContexts = fileContexts.SelectMany(fileContext => + { + var harvestShapeInfo = new HarvestShapeInfo + { + SubPath = fileContext.pathContext.subPath, + FileName = fileContext.fileName, + RelativePath = fileContext.relativePath, + Extension = Path.GetExtension(fileContext.relativePath) + }; + var harvestShapeHits = fileContext.pathContext.harvester.HarvestShape(harvestShapeInfo); + return harvestShapeHits.Select(harvestShapeHit => new + { + harvestShapeInfo, + harvestShapeHit, + fileContext }); - })); + }); - var shapeContexts = fileContexts.SelectMany(fileContext => - { - var harvestShapeInfo = new HarvestShapeInfo - { - SubPath = fileContext.pathContext.subPath, - FileName = fileContext.fileName, - RelativePath = fileContext.relativePath, - Extension = Path.GetExtension(fileContext.relativePath) - }; - var harvestShapeHits = fileContext.pathContext.harvester.HarvestShape(harvestShapeInfo); - return harvestShapeHits.Select(harvestShapeHit => new { harvestShapeInfo, harvestShapeHit, fileContext }); - }); - - return shapeContexts.Select(shapeContext => new { extensionDescriptor, shapeContext }).ToList(); - }).SelectMany(hits2 => hits2); + return shapeContexts.Select(shapeContext => new { extensionDescriptor, shapeContext }).ToList(); + }) + .SelectMany(hits2 => hits2); foreach (var iter in hits) { @@ -126,25 +139,28 @@ public override async ValueTask DiscoverAsync(ShapeTableBuilder builder) if (_logger.IsEnabled(LogLevel.Debug)) { - _logger.LogDebug("Binding '{TemplatePath}' as shape '{ShapeType}' for feature '{FeatureName}'", + _logger.LogDebug( + "Binding '{TemplatePath}' as shape '{ShapeType}' for feature '{FeatureName}'", hit.shapeContext.harvestShapeInfo.RelativePath, iter.shapeContext.harvestShapeHit.ShapeType, - feature.Id); + feature.Id + ); } var viewEngineType = _viewEnginesByExtension[iter.shapeContext.harvestShapeInfo.Extension].GetType(); - builder.Describe(iter.shapeContext.harvestShapeHit.ShapeType) + builder + .Describe(iter.shapeContext.harvestShapeHit.ShapeType) .From(feature) .BoundAs( - hit.shapeContext.harvestShapeInfo.RelativePath, displayContext => + hit.shapeContext.harvestShapeInfo.RelativePath, + displayContext => { - var viewEngine = displayContext.ServiceProvider - .GetServices() - .FirstOrDefault(e => e.GetType() == viewEngineType); + var viewEngine = displayContext.ServiceProvider.GetServices().FirstOrDefault(e => e.GetType() == viewEngineType); return viewEngine.RenderAsync(hit.shapeContext.harvestShapeInfo.RelativePath, displayContext); - }); + } + ); } _logger.LogInformation("Done discovering shapes"); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/DisplayManager.cs b/src/OrchardCore/OrchardCore.DisplayManagement/DisplayManager.cs index b55a6de8d50..25416b39709 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/DisplayManager.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/DisplayManager.cs @@ -22,7 +22,8 @@ public DisplayManager( IEnumerable placementProviders, ILogger> logger, ILayoutAccessor layoutAccessor - ) : base(shapeFactory, placementProviders) + ) + : base(shapeFactory, placementProviders) { _shapeFactory = shapeFactory; _layoutAccessor = layoutAccessor; @@ -58,14 +59,19 @@ await _layoutAccessor.GetLayoutAsync(), await BindPlacementAsync(context); - await _drivers.InvokeAsync(async (driver, model, context) => - { - var result = await driver.BuildDisplayAsync(model, context); - if (result != null) + await _drivers.InvokeAsync( + async (driver, model, context) => { - await result.ApplyAsync(context); - } - }, model, context, _logger); + var result = await driver.BuildDisplayAsync(model, context); + if (result != null) + { + await result.ApplyAsync(context); + } + }, + model, + context, + _logger + ); return shape; } @@ -92,14 +98,19 @@ await _layoutAccessor.GetLayoutAsync(), await BindPlacementAsync(context); - await _drivers.InvokeAsync(async (driver, model, context) => - { - var result = await driver.BuildEditorAsync(model, context); - if (result != null) + await _drivers.InvokeAsync( + async (driver, model, context) => { - await result.ApplyAsync(context); - } - }, model, context, _logger); + var result = await driver.BuildEditorAsync(model, context); + if (result != null) + { + await result.ApplyAsync(context); + } + }, + model, + context, + _logger + ); return shape; } @@ -126,14 +137,19 @@ await _layoutAccessor.GetLayoutAsync(), await BindPlacementAsync(context); - await _drivers.InvokeAsync(async (driver, model, context) => - { - var result = await driver.UpdateEditorAsync(model, context); - if (result != null) + await _drivers.InvokeAsync( + async (driver, model, context) => { - await result.ApplyAsync(context); - } - }, model, context, _logger); + var result = await driver.UpdateEditorAsync(model, context); + if (result != null) + { + await result.ApplyAsync(context); + } + }, + model, + context, + _logger + ); return shape; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Entities/SectionDisplayDriver.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Entities/SectionDisplayDriver.cs index 95993f5f312..1804756c079 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Entities/SectionDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Entities/SectionDisplayDriver.cs @@ -121,10 +121,7 @@ public virtual Task UpdateAsync(TSection section, IUpdateModel u return Task.FromResult(null); } - private TSection GetSection(TModel model) - => model.Properties.TryGetPropertyValue(PropertyName, out var property) - ? property.ToObject() - : new TSection(); + private TSection GetSection(TModel model) => model.Properties.TryGetPropertyValue(PropertyName, out var property) ? property.ToObject() : new TSection(); protected override void BuildPrefix(TModel model, string htmlFieldPrefix) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Events/ThemeFeatureBuilderEvents.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Events/ThemeFeatureBuilderEvents.cs index 4eb771e74c3..a4b8c0dc383 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Events/ThemeFeatureBuilderEvents.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Events/ThemeFeatureBuilderEvents.cs @@ -13,17 +13,13 @@ public override void Building(FeatureBuildingContext context) { var moduleInfo = context.ExtensionInfo.Manifest.ModuleInfo; - if (moduleInfo is ThemeAttribute || (moduleInfo is ModuleMarkerAttribute && - moduleInfo.Type.Equals("Theme", StringComparison.OrdinalIgnoreCase))) + if (moduleInfo is ThemeAttribute || (moduleInfo is ModuleMarkerAttribute && moduleInfo.Type.Equals("Theme", StringComparison.OrdinalIgnoreCase))) { var extensionInfo = new ThemeExtensionInfo(context.ExtensionInfo); if (extensionInfo.HasBaseTheme()) { - context.FeatureDependencyIds = context - .FeatureDependencyIds - .Concat(new[] { extensionInfo.BaseTheme }) - .ToArray(); + context.FeatureDependencyIds = context.FeatureDependencyIds.Concat(new[] { extensionInfo.BaseTheme }).ToArray(); } context.ExtensionInfo = extensionInfo; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/DisplayManagerExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/DisplayManagerExtensions.cs index 5b4199e0708..cb4d5534e0a 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/DisplayManagerExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/DisplayManagerExtensions.cs @@ -5,9 +5,9 @@ namespace OrchardCore.DisplayManagement; public static class DisplayManagerExtensions { - public static Task BuildDisplayAsync(this IDisplayManager displayManager, IUpdateModel updater, string displayType = "", string groupId = "") where TModel : new() - => displayManager.BuildDisplayAsync(new TModel(), updater, displayType, groupId); + public static Task BuildDisplayAsync(this IDisplayManager displayManager, IUpdateModel updater, string displayType = "", string groupId = "") + where TModel : new() => displayManager.BuildDisplayAsync(new TModel(), updater, displayType, groupId); - public static Task BuildEditorAsync(this IDisplayManager displayManager, IUpdateModel updater, bool isNew, string groupId = "", string htmlPrefix = "") where TModel : new() - => displayManager.BuildEditorAsync(new TModel(), updater, isNew, groupId, htmlPrefix); + public static Task BuildEditorAsync(this IDisplayManager displayManager, IUpdateModel updater, bool isNew, string groupId = "", string htmlPrefix = "") + where TModel : new() => displayManager.BuildEditorAsync(new TModel(), updater, isNew, groupId, htmlPrefix); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/ExtensionInfoExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/ExtensionInfoExtensions.cs index 225ac65aa50..c53533d3527 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/ExtensionInfoExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/ExtensionInfoExtensions.cs @@ -5,11 +5,8 @@ namespace OrchardCore.DisplayManagement.Extensions { public static class ExtensionInfoExtensions { - public static bool IsTheme(this IExtensionInfo extensionInfo) => - extensionInfo is IThemeExtensionInfo; + public static bool IsTheme(this IExtensionInfo extensionInfo) => extensionInfo is IThemeExtensionInfo; - public static bool IsTheme(this IFeatureInfo featureInfo) => - featureInfo.Extension is IThemeExtensionInfo && - featureInfo.Id == featureInfo.Extension.Id; + public static bool IsTheme(this IFeatureInfo featureInfo) => featureInfo.Extension is IThemeExtensionInfo && featureInfo.Id == featureInfo.Extension.Id; } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/IThemeExtensionInfo.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/IThemeExtensionInfo.cs index a9807adb20c..9501b81c8c9 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/IThemeExtensionInfo.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/IThemeExtensionInfo.cs @@ -2,7 +2,4 @@ namespace OrchardCore.DisplayManagement.Extensions; -public interface IThemeExtensionInfo : IExtensionInfo -{ - -} +public interface IThemeExtensionInfo : IExtensionInfo { } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/ServiceCollectionExtensions.cs index 785dfd47b10..be3c793bfe5 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/ServiceCollectionExtensions.cs @@ -18,9 +18,7 @@ public static IServiceCollection AddTagHelpers(this IServiceCollection services, /// public static IServiceCollection AddTagHelpers(this IServiceCollection services) { - return services - .AddTransient(sp => new TagHelpersProvider()) - .AddTransient(typeof(T)); + return services.AddTransient(sp => new TagHelpersProvider()).AddTransient(typeof(T)); } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriver.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriver.cs index 947291efd71..6ca2907137d 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriver.cs @@ -4,9 +4,9 @@ namespace OrchardCore.DisplayManagement.Handlers { - public abstract class DisplayDriver : - DisplayDriverBase, - IDisplayDriver + public abstract class DisplayDriver + : DisplayDriverBase, + IDisplayDriver where TModel : class where TDisplayContext : BuildDisplayContext where TEditorContext : BuildEditorContext @@ -125,16 +125,12 @@ protected virtual void BuildPrefix(TModel model, string htmlFieldPrefix) } } - public abstract class DisplayDriver : - DisplayDriver, - IDisplayDriver - where TModel : class - { - } + public abstract class DisplayDriver : DisplayDriver, IDisplayDriver + where TModel : class { } - public abstract class DisplayDriver : - DisplayDriver, - IDisplayDriver + public abstract class DisplayDriver + : DisplayDriver, + IDisplayDriver where TConcrete : class, TModel where TModel : class where TDisplayContext : BuildDisplayContext @@ -193,11 +189,7 @@ Task IDisplayDriver : - DisplayDriver, - IDisplayDriver + public abstract class DisplayDriver : DisplayDriver, IDisplayDriver where TConcrete : class, TModel - where TModel : class - { - } + where TModel : class { } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriverBase.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriverBase.cs index 053ba72d1cf..6053bd79694 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriverBase.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriverBase.cs @@ -12,7 +12,8 @@ public class DisplayDriverBase /// /// Creates a new strongly typed shape and initializes it if it needs to be rendered. /// - public ShapeResult Initialize(Action initialize) where TModel : class + public ShapeResult Initialize(Action initialize) + where TModel : class { return Initialize(shape => { @@ -24,29 +25,26 @@ public ShapeResult Initialize(Action initialize) where TModel : /// /// Creates a new strongly typed shape and initializes it if it needs to be rendered. /// - public ShapeResult Initialize(Func initializeAsync) where TModel : class + public ShapeResult Initialize(Func initializeAsync) + where TModel : class { - return Initialize( - typeof(TModel).Name, - shape => initializeAsync(shape) - ); + return Initialize(typeof(TModel).Name, shape => initializeAsync(shape)); } /// /// Creates a new strongly typed shape and initializes it if it needs to be rendered. /// - public ShapeResult Initialize(string shapeType, Func initializeAsync) where TModel : class + public ShapeResult Initialize(string shapeType, Func initializeAsync) + where TModel : class { - return Factory( - shapeType, - ctx => ctx.ShapeFactory.CreateAsync(shapeType, initializeAsync) - ); + return Factory(shapeType, ctx => ctx.ShapeFactory.CreateAsync(shapeType, initializeAsync)); } /// /// Creates a dynamic proxy for the specified model. Properties are copied to the new object. /// - public ShapeResult Copy(string shapeType, TModel model) where TModel : class + public ShapeResult Copy(string shapeType, TModel model) + where TModel : class { return Factory(shapeType, ctx => ctx.ShapeFactory.CreateAsync(shapeType, model)); } @@ -54,13 +52,17 @@ public ShapeResult Copy(string shapeType, TModel model) where TModel : c /// /// Creates a new strongly typed shape and initializes it if it needs to be rendered. /// - public ShapeResult Initialize(string shapeType, Action initialize) where TModel : class + public ShapeResult Initialize(string shapeType, Action initialize) + where TModel : class { - return Initialize(shapeType, shape => - { - initialize(shape); - return new ValueTask(); - }); + return Initialize( + shapeType, + shape => + { + initialize(shape); + return new ValueTask(); + } + ); } /// @@ -68,13 +70,15 @@ public ShapeResult Initialize(string shapeType, Action initializ /// public ShapeResult Dynamic(string shapeType, Func initializeAsync) { - return Factory(shapeType, + return Factory( + shapeType, async ctx => { dynamic shape = await ctx.ShapeFactory.CreateAsync(shapeType); await initializeAsync(shape); return shape; - }); + } + ); } /// @@ -82,13 +86,15 @@ public ShapeResult Dynamic(string shapeType, Func initializeAsync /// public ShapeResult Dynamic(string shapeType, Action initialize) { - return Factory(shapeType, + return Factory( + shapeType, async ctx => { dynamic shape = await ctx.ShapeFactory.CreateAsync(shapeType); initialize(shape); return shape; - }); + } + ); } /// @@ -102,7 +108,8 @@ public ShapeResult Dynamic(string shapeType) /// /// Creates a for the specific model. /// - public ShapeResult View(string shapeType, TModel model) where TModel : class + public ShapeResult View(string shapeType, TModel model) + where TModel : class { return Factory(shapeType, ctx => new ValueTask(new ShapeViewModel(model))); } @@ -140,8 +147,7 @@ public ShapeResult Factory(string shapeType, Func sh /// public virtual ShapeResult Factory(string shapeType, Func> shapeBuilder, Func initializeAsync) { - return new ShapeResult(shapeType, shapeBuilder, initializeAsync) - .Prefix(Prefix); + return new ShapeResult(shapeType, shapeBuilder, initializeAsync).Prefix(Prefix); } public static CombinedResult Combine(params IDisplayResult[] results) => new(results); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/IDisplayDriver.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/IDisplayDriver.cs index 60975004280..81fa9dcee04 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/IDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/IDisplayDriver.cs @@ -13,7 +13,5 @@ public interface IDisplayDriver UpdateEditorAsync(TModel model, TUpdateContext context); } - public interface IDisplayDriver : IDisplayDriver - { - } + public interface IDisplayDriver : IDisplayDriver { } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/UpdateEditorContext.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/UpdateEditorContext.cs index dbfb0b5ffae..6d54bc5278a 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/UpdateEditorContext.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/UpdateEditorContext.cs @@ -5,12 +5,7 @@ namespace OrchardCore.DisplayManagement.Handlers { public class UpdateEditorContext : BuildEditorContext { - - public UpdateEditorContext(IShape model, string groupId, bool isNew, string htmlFieldPrefix, IShapeFactory shapeFactory, - IZoneHolding layout, IUpdateModel updater) - : base(model, groupId, isNew, htmlFieldPrefix, shapeFactory, layout, updater) - { - } - + public UpdateEditorContext(IShape model, string groupId, bool isNew, string htmlFieldPrefix, IShapeFactory shapeFactory, IZoneHolding layout, IUpdateModel updater) + : base(model, groupId, isNew, htmlFieldPrefix, shapeFactory, layout, updater) { } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Html/CssOrchardHelperExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Html/CssOrchardHelperExtensions.cs index 85d0e5b4c77..62b9f44a449 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Html/CssOrchardHelperExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Html/CssOrchardHelperExtensions.cs @@ -10,23 +10,23 @@ namespace OrchardCore; public static class CssOrchardHelperExtensions { - public static IHtmlContent GetLimitedWidthWrapperClasses(this IOrchardHelper helper, params string[] additionalClasses) - => GetHtmlContentBuilder(helper.GetThemeOptions().LimitedWidthWrapperClasses, additionalClasses); + public static IHtmlContent GetLimitedWidthWrapperClasses(this IOrchardHelper helper, params string[] additionalClasses) => + GetHtmlContentBuilder(helper.GetThemeOptions().LimitedWidthWrapperClasses, additionalClasses); - public static IHtmlContent GetLimitedWidthClasses(this IOrchardHelper helper, params string[] additionalClasses) - => GetHtmlContentBuilder(helper.GetThemeOptions().LimitedWidthClasses, additionalClasses); + public static IHtmlContent GetLimitedWidthClasses(this IOrchardHelper helper, params string[] additionalClasses) => + GetHtmlContentBuilder(helper.GetThemeOptions().LimitedWidthClasses, additionalClasses); - public static IHtmlContent GetStartClasses(this IOrchardHelper helper, params string[] additionalClasses) - => GetHtmlContentBuilder(helper.GetThemeOptions().StartClasses, additionalClasses); + public static IHtmlContent GetStartClasses(this IOrchardHelper helper, params string[] additionalClasses) => + GetHtmlContentBuilder(helper.GetThemeOptions().StartClasses, additionalClasses); - public static IHtmlContent GetEndClasses(this IOrchardHelper helper, params string[] additionalClasses) - => GetHtmlContentBuilder(helper.GetThemeOptions().EndClasses, additionalClasses); + public static IHtmlContent GetEndClasses(this IOrchardHelper helper, params string[] additionalClasses) => + GetHtmlContentBuilder(helper.GetThemeOptions().EndClasses, additionalClasses); - public static IHtmlContent GetLabelClasses(this IOrchardHelper helper, params string[] additionalClasses) - => GetHtmlContentBuilder(helper.GetThemeOptions().LabelClasses, additionalClasses); + public static IHtmlContent GetLabelClasses(this IOrchardHelper helper, params string[] additionalClasses) => + GetHtmlContentBuilder(helper.GetThemeOptions().LabelClasses, additionalClasses); - public static IHtmlContent GetWrapperClasses(this IOrchardHelper helper, params string[] additionalClasses) - => GetHtmlContentBuilder(helper.GetThemeOptions().WrapperClasses, additionalClasses); + public static IHtmlContent GetWrapperClasses(this IOrchardHelper helper, params string[] additionalClasses) => + GetHtmlContentBuilder(helper.GetThemeOptions().WrapperClasses, additionalClasses); public static IHtmlContent GetEndClasses(this IOrchardHelper helper, bool withOffset, params string[] additionalClasses) { @@ -34,10 +34,7 @@ public static IHtmlContent GetEndClasses(this IOrchardHelper helper, bool withOf if (withOffset && !string.IsNullOrEmpty(options.OffsetClasses)) { - var cssClasses = new List(additionalClasses) - { - options.OffsetClasses - }; + var cssClasses = new List(additionalClasses) { options.OffsetClasses }; return GetHtmlContentBuilder(options.EndClasses, cssClasses); } @@ -45,33 +42,32 @@ public static IHtmlContent GetEndClasses(this IOrchardHelper helper, bool withOf return GetHtmlContentBuilder(options.EndClasses, additionalClasses); } - public static IHtmlContent GetOffsetClasses(this IOrchardHelper helper, params string[] additionalClasses) - => GetHtmlContentBuilder(helper.GetThemeOptions().OffsetClasses, additionalClasses); + public static IHtmlContent GetOffsetClasses(this IOrchardHelper helper, params string[] additionalClasses) => + GetHtmlContentBuilder(helper.GetThemeOptions().OffsetClasses, additionalClasses); [Obsolete($"Please use {nameof(GetLimitedWidthWrapperClasses)} instead, as this method is deprecated and will be removed in upcoming versions.")] - public static string GetLimitedWidthWrapperCssClasses(this IOrchardHelper helper, params string[] additionalClasses) - => string.Join(' ', Combine(helper.GetThemeOptions().LimitedWidthWrapperClasses, additionalClasses)); + public static string GetLimitedWidthWrapperCssClasses(this IOrchardHelper helper, params string[] additionalClasses) => + string.Join(' ', Combine(helper.GetThemeOptions().LimitedWidthWrapperClasses, additionalClasses)); [Obsolete($"Please use {nameof(GetLimitedWidthClasses)} instead, as this method is deprecated and will be removed in upcoming versions.")] - public static string GetLimitedWidthCssClasses(this IOrchardHelper helper, params string[] additionalClasses) - => string.Join(' ', Combine(helper.GetThemeOptions().LimitedWidthClasses, additionalClasses)); + public static string GetLimitedWidthCssClasses(this IOrchardHelper helper, params string[] additionalClasses) => + string.Join(' ', Combine(helper.GetThemeOptions().LimitedWidthClasses, additionalClasses)); [Obsolete($"Please use {nameof(GetLabelClasses)} instead, as this method is deprecated and will be removed in upcoming versions.")] - public static string GetLabelCssClasses(this IOrchardHelper helper, params string[] additionalClasses) - => string.Join(' ', Combine(helper.GetThemeOptions().LabelClasses, additionalClasses)); + public static string GetLabelCssClasses(this IOrchardHelper helper, params string[] additionalClasses) => + string.Join(' ', Combine(helper.GetThemeOptions().LabelClasses, additionalClasses)); [Obsolete($"Please use {nameof(GetStartClasses)} instead, as this method is deprecated and will be removed in upcoming versions.")] - public static string GetStartCssClasses(this IOrchardHelper helper, params string[] additionalClasses) - => string.Join(' ', Combine(helper.GetThemeOptions().StartClasses, additionalClasses)); + public static string GetStartCssClasses(this IOrchardHelper helper, params string[] additionalClasses) => + string.Join(' ', Combine(helper.GetThemeOptions().StartClasses, additionalClasses)); [Obsolete($"Please use {nameof(GetEndClasses)} instead, as this method is deprecated and will be removed in upcoming versions.")] - public static string GetEndCssClasses(this IOrchardHelper helper, params string[] additionalClasses) - => string.Join(' ', Combine(helper.GetThemeOptions().EndClasses, additionalClasses)); + public static string GetEndCssClasses(this IOrchardHelper helper, params string[] additionalClasses) => + string.Join(' ', Combine(helper.GetThemeOptions().EndClasses, additionalClasses)); [Obsolete($"Please use {nameof(GetWrapperClasses)} instead, as this method is deprecated and will be removed in upcoming versions.")] - public static string GetWrapperCssClasses(this IOrchardHelper helper, params string[] additionalClasses) - => string.Join(' ', Combine(helper.GetThemeOptions().WrapperClasses, additionalClasses)); - + public static string GetWrapperCssClasses(this IOrchardHelper helper, params string[] additionalClasses) => + string.Join(' ', Combine(helper.GetThemeOptions().WrapperClasses, additionalClasses)); [Obsolete($"Please use {nameof(GetEndClasses)} instead, as this method is deprecated and will be removed in upcoming versions.")] public static string GetEndCssClasses(this IOrchardHelper helper, bool withOffset, params string[] additionalClasses) @@ -80,10 +76,7 @@ public static string GetEndCssClasses(this IOrchardHelper helper, bool withOffse if (withOffset && !string.IsNullOrEmpty(options.OffsetClasses)) { - var cssClasses = new List(additionalClasses) - { - options.OffsetClasses - }; + var cssClasses = new List(additionalClasses) { options.OffsetClasses }; return string.Join(' ', Combine(options.EndClasses, cssClasses.ToArray())); } @@ -92,11 +85,10 @@ public static string GetEndCssClasses(this IOrchardHelper helper, bool withOffse } [Obsolete($"Please use {nameof(GetOffsetClasses)} instead, as this method is deprecated and will be removed in upcoming versions.")] - public static string GetOffsetCssClasses(this IOrchardHelper helper, params string[] additionalClasses) - => string.Join(' ', Combine(helper.GetThemeOptions().OffsetClasses, additionalClasses)); + public static string GetOffsetCssClasses(this IOrchardHelper helper, params string[] additionalClasses) => + string.Join(' ', Combine(helper.GetThemeOptions().OffsetClasses, additionalClasses)); - public static TheAdminThemeOptions GetThemeOptions(this IOrchardHelper helper) - => helper.HttpContext.RequestServices.GetService>().Value; + public static TheAdminThemeOptions GetThemeOptions(this IOrchardHelper helper) => helper.HttpContext.RequestServices.GetService>().Value; private static IEnumerable Combine(string optionClasses, string[] additionalClasses) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/IDisplayManager.cs b/src/OrchardCore/OrchardCore.DisplayManagement/IDisplayManager.cs index 0358436891d..9eae9c17943 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/IDisplayManager.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/IDisplayManager.cs @@ -11,11 +11,9 @@ public interface IDisplayManager Task UpdateEditorAsync(TModel model, IUpdateModel updater, bool isNew, string groupId, string htmlPrefix); [Obsolete("This method will be removed in a future version", false)] - Task BuildEditorAsync(TModel model, IUpdateModel updater, bool isNew, string groupId = "") - => BuildEditorAsync(model, updater, isNew, groupId, ""); + Task BuildEditorAsync(TModel model, IUpdateModel updater, bool isNew, string groupId = "") => BuildEditorAsync(model, updater, isNew, groupId, ""); [Obsolete("This method will be removed in a future version", false)] - Task UpdateEditorAsync(TModel model, IUpdateModel updater, bool isNew, string groupId = "") - => UpdateEditorAsync(model, updater, isNew, groupId, ""); + Task UpdateEditorAsync(TModel model, IUpdateModel updater, bool isNew, string groupId = "") => UpdateEditorAsync(model, updater, isNew, groupId, ""); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/IShape.cs b/src/OrchardCore/OrchardCore.DisplayManagement/IShape.cs index 33a8e9a7c06..43c8004b179 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/IShape.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/IShape.cs @@ -120,6 +120,5 @@ public static TagBuilder GetTagBuilder(this IShape shape, string defaultTagName } public static JsonObject ShapeToJson(this IShape shape) => new ShapeSerializer(shape).Serialize(); - } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/IShapeFactory.cs b/src/OrchardCore/OrchardCore.DisplayManagement/IShapeFactory.cs index 682cdcf9b72..f3e5ee2971b 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/IShapeFactory.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/IShapeFactory.cs @@ -14,11 +14,7 @@ namespace OrchardCore.DisplayManagement /// public interface IShapeFactory { - ValueTask CreateAsync( - string shapeType, - Func> shapeFactory, - Action creating, - Action created); + ValueTask CreateAsync(string shapeType, Func> shapeFactory, Action creating, Action created); dynamic New { get; } } @@ -107,12 +103,15 @@ static ValueTask ShapeFactory(Func init) /// public static ValueTask CreateAsync(this IShapeFactory factory, string shapeType, Action initialize) { - return factory.CreateAsync(shapeType, () => - { - var shape = CreateShape(typeof(TModel)); - initialize((TModel)shape); - return new ValueTask(shape); - }); + return factory.CreateAsync( + shapeType, + () => + { + var shape = CreateShape(typeof(TModel)); + initialize((TModel)shape); + return new ValueTask(shape); + } + ); } public static ValueTask CreateAsync(this IShapeFactory factory, string shapeType, INamedEnumerable parameters) @@ -122,32 +121,37 @@ public static ValueTask CreateAsync(this IShapeFactory factory, strin return factory.CreateAsync(shapeType); } - return factory.CreateAsync(shapeType, _newShape, null, createdContext => - { - var shape = (Shape)createdContext.Shape; - - // If only one non-Type, use it as the source object to copy + return factory.CreateAsync( + shapeType, + _newShape, + null, + createdContext => + { + var shape = (Shape)createdContext.Shape; - var initializer = parameters.Positional.SingleOrDefault(); + // If only one non-Type, use it as the source object to copy - if (initializer != null) - { - // Use the Arguments class to optimize reflection code - var arguments = Arguments.From(initializer); + var initializer = parameters.Positional.SingleOrDefault(); - foreach (var prop in arguments.Named) + if (initializer != null) { - shape.Properties[prop.Key] = prop.Value; + // Use the Arguments class to optimize reflection code + var arguments = Arguments.From(initializer); + + foreach (var prop in arguments.Named) + { + shape.Properties[prop.Key] = prop.Value; + } } - } - else - { - foreach (var kv in parameters.Named) + else { - shape.Properties[kv.Key] = kv.Value; + foreach (var kv in parameters.Named) + { + shape.Properties[kv.Key] = kv.Value; + } } } - }); + ); } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultHtmlDisplay.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultHtmlDisplay.cs index fab1d676f32..c46980d791f 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultHtmlDisplay.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultHtmlDisplay.cs @@ -27,7 +27,8 @@ public DefaultHtmlDisplay( IShapeTableManager shapeTableManager, IServiceProvider serviceProvider, ILogger logger, - IThemeManager themeManager) + IThemeManager themeManager + ) { _shapeTableManager = shapeTableManager; _shapeDisplayEvents = shapeDisplayEvents; @@ -63,10 +64,7 @@ public async Task ExecuteAsync(DisplayContext context) // Copy the current context such that the rendering can customize it if necessary, // for instance to change the HtmlFieldPrefix. - var localContext = new DisplayContext(context) - { - HtmlFieldPrefix = shapeMetadata.Prefix ?? "", - }; + var localContext = new DisplayContext(context) { HtmlFieldPrefix = shapeMetadata.Prefix ?? "", }; var displayContext = new ShapeDisplayContext { @@ -145,33 +143,41 @@ public async Task ExecuteAsync(DisplayContext context) shape.Metadata.Wrappers.Clear(); } - await _shapeDisplayEvents.InvokeAsync(async (e, displayContext) => - { - var prior = displayContext.ChildContent = displayContext.Shape.Metadata.ChildContent; - - await e.DisplayedAsync(displayContext); - - // Update the child content if the context variable has been reassigned. - if (prior != displayContext.ChildContent) - { - displayContext.Shape.Metadata.ChildContent = displayContext.ChildContent; - } - }, displayContext, _logger); - - if (shapeDescriptor != null) - { - await shapeDescriptor.DisplayedAsync.InvokeAsync(async (action, displayContext) => + await _shapeDisplayEvents.InvokeAsync( + async (e, displayContext) => { var prior = displayContext.ChildContent = displayContext.Shape.Metadata.ChildContent; - await action(displayContext); + await e.DisplayedAsync(displayContext); // Update the child content if the context variable has been reassigned. if (prior != displayContext.ChildContent) { displayContext.Shape.Metadata.ChildContent = displayContext.ChildContent; } - }, displayContext, _logger); + }, + displayContext, + _logger + ); + + if (shapeDescriptor != null) + { + await shapeDescriptor.DisplayedAsync.InvokeAsync( + async (action, displayContext) => + { + var prior = displayContext.ChildContent = displayContext.Shape.Metadata.ChildContent; + + await action(displayContext); + + // Update the child content if the context variable has been reassigned. + if (prior != displayContext.ChildContent) + { + displayContext.Shape.Metadata.ChildContent = displayContext.ChildContent; + } + }, + displayContext, + _logger + ); } // Invoking ShapeMetadata displayed events. @@ -254,8 +260,7 @@ private async Task GetShapeBindingAsync(string shapeType, Alternat { return shapeBinding; } - } - while (TryGetParentShapeTypeName(ref shapeTypeScan)); + } while (TryGetParentShapeTypeName(ref shapeTypeScan)); return null; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultShapeFactory.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultShapeFactory.cs index 1b8ee2a17ee..4593d8ba8bc 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultShapeFactory.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultShapeFactory.cs @@ -15,11 +15,7 @@ public class DefaultShapeFactory : DynamicObject, IShapeFactory private readonly IServiceProvider _serviceProvider; private ShapeTable _scopedShapeTable; - public DefaultShapeFactory( - IEnumerable events, - IShapeTableManager shapeTableManager, - IThemeManager themeManager, - IServiceProvider serviceProvider) + public DefaultShapeFactory(IEnumerable events, IShapeTableManager shapeTableManager, IThemeManager themeManager, IServiceProvider serviceProvider) { _events = events; _shapeTableManager = shapeTableManager; @@ -41,9 +37,7 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o binderName = binder.Name[..^"Async".Length]; } - result = ShapeFactoryExtensions - .CreateAsync(this, binderName, Arguments.From(args, binder.CallInfo.ArgumentNames)) - .AsTask(); + result = ShapeFactoryExtensions.CreateAsync(this, binderName, Arguments.From(args, binder.CallInfo.ArgumentNames)).AsTask(); return true; } @@ -59,7 +53,12 @@ private async Task GetShapeTableAsync() return _scopedShapeTable; } - public async ValueTask CreateAsync(string shapeType, Func> shapeFactory, Action creating, Action created) + public async ValueTask CreateAsync( + string shapeType, + Func> shapeFactory, + Action creating, + Action created + ) { ShapeDescriptor shapeDescriptor; (await GetShapeTableAsync()).Descriptors.TryGetValue(shapeType, out shapeDescriptor); @@ -100,8 +99,7 @@ public async ValueTask CreateAsync(string shapeType, Func /// Guaranteed to be called, even in the event of an exception when rendering the shape. /// diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/IShapeFactoryEvents.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/IShapeFactoryEvents.cs index f0cdbff3e71..5ce7261fa4f 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/IShapeFactoryEvents.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/IShapeFactoryEvents.cs @@ -36,11 +36,8 @@ public class ShapeCreatedContext public abstract class ShapeFactoryEvents : IShapeFactoryEvents { - public virtual void Creating(ShapeCreatingContext context) - { - } - public virtual void Created(ShapeCreatedContext context) - { - } + public virtual void Creating(ShapeCreatingContext context) { } + + public virtual void Created(ShapeCreatedContext context) { } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Layout/LayoutAccessor.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Layout/LayoutAccessor.cs index bb1d236d051..bd55f25841e 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Layout/LayoutAccessor.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Layout/LayoutAccessor.cs @@ -17,9 +17,7 @@ public LayoutAccessor(IShapeFactory shapeFactory) public async Task GetLayoutAsync() { // Create a shape whose properties are dynamically created as Zone shapes. - _layout ??= await _shapeFactory.CreateAsync( - "Layout", - () => new ValueTask(new ZoneHolding(() => _shapeFactory.CreateAsync("Zone")))) as IZoneHolding; + _layout ??= await _shapeFactory.CreateAsync("Layout", () => new ValueTask(new ZoneHolding(() => _shapeFactory.CreateAsync("Zone")))) as IZoneHolding; if (_layout == null) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/LocationExpander/ThemeViewLocationExpanderProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement/LocationExpander/ThemeViewLocationExpanderProvider.cs index 8ea6177fc16..5105bcef6d0 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/LocationExpander/ThemeViewLocationExpanderProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/LocationExpander/ThemeViewLocationExpanderProvider.cs @@ -35,24 +35,17 @@ public void PopulateValues(ViewLocationExpanderContext context) } /// - public virtual IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, - IEnumerable viewLocations) + public virtual IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable viewLocations) { if (!context.Values.TryGetValue("Theme", out var currentThemeId)) { return viewLocations; } - var currentThemeAndBaseThemesOrdered = _extensionManager - .GetFeatures([currentThemeId]) - .Where(f => f.IsTheme()) - .Reverse() - .ToList(); + var currentThemeAndBaseThemesOrdered = _extensionManager.GetFeatures([currentThemeId]).Where(f => f.IsTheme()).Reverse().ToList(); // let the application acting as a super theme also for mvc views discovering. - var applicationTheme = _extensionManager - .GetFeatures() - .FirstOrDefault(x => x.Id == _hostingEnvironment.ApplicationName); + var applicationTheme = _extensionManager.GetFeatures().FirstOrDefault(x => x.Id == _hostingEnvironment.ApplicationName); if (applicationTheme != null) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Manifest/ThemeAttribute.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Manifest/ThemeAttribute.cs index 1761be24990..8a5c6973896 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Manifest/ThemeAttribute.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Manifest/ThemeAttribute.cs @@ -19,9 +19,8 @@ public class ThemeAttribute : ModuleAttribute /// /// Default parameterless ctor. /// - public ThemeAttribute() : base() - { - } + public ThemeAttribute() + : base() { } /// /// Ctor allowing , as well as defaults for @@ -58,24 +57,23 @@ public ThemeAttribute( object defaultTenant, object alwaysEnabled, object enabledByDependencyOnly - ) : this( - id, - default, - baseTheme, - default, - default, - description, - author, - semVer, - websiteUrl, - featureDependencies, - tags, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly ) - { - } + : this( + id, + default, + baseTheme, + default, + default, + description, + author, + semVer, + websiteUrl, + featureDependencies, + tags, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ) { } /// /// Ctor allowing , as well as defaults for @@ -115,24 +113,9 @@ public ThemeAttribute( object defaultTenant, object alwaysEnabled, object enabledByDependencyOnly - ) : this( - id, - name, - baseTheme, - default, - default, - description, - author, - semVer, - websiteUrl, - featureDependencies, - tags, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly ) - { - } + : this(id, name, baseTheme, default, default, description, author, semVer, websiteUrl, featureDependencies, tags, defaultTenant, alwaysEnabled, enabledByDependencyOnly) + { } // TODO: MWP: do we need a 'type' version? probably not... /// @@ -177,21 +160,8 @@ public ThemeAttribute( object defaultTenant, object alwaysEnabled, object enabledByDependencyOnly - ) : base( - id, - name, - category, - priority, - description, - author, - semVer, - websiteUrl, - featureDependencies, - tags, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly ) + : base(id, name, category, priority, description, author, semVer, websiteUrl, featureDependencies, tags, defaultTenant, alwaysEnabled, enabledByDependencyOnly) { BaseTheme = baseTheme; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ControllerModelUpdater.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ControllerModelUpdater.cs index f2ebe2dd9f9..4e19b423d8d 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ControllerModelUpdater.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ControllerModelUpdater.cs @@ -17,17 +17,20 @@ public ControllerModelUpdater(Controller controller) public ModelStateDictionary ModelState => _controller.ModelState; - public Task TryUpdateModelAsync(TModel model) where TModel : class + public Task TryUpdateModelAsync(TModel model) + where TModel : class { return _controller.TryUpdateModelAsync(model); } - public Task TryUpdateModelAsync(TModel model, string prefix) where TModel : class + public Task TryUpdateModelAsync(TModel model, string prefix) + where TModel : class { return _controller.TryUpdateModelAsync(model, prefix); } - public Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) where TModel : class + public Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) + where TModel : class { return _controller.TryUpdateModelAsync(model, prefix, includeExpressions); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/LocalModelBinderAccessor.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/LocalModelBinderAccessor.cs index 7751814ce0f..738c24ae632 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/LocalModelBinderAccessor.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/LocalModelBinderAccessor.cs @@ -19,7 +19,6 @@ public IUpdateModel ModelUpdater var updateModel = _httpContextAccessor.HttpContext.Items[_key] as IUpdateModel; return updateModel ?? new NullModelUpdater(); } - set { _httpContextAccessor.HttpContext.Items[_key] = value; } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ModelBinderAccessorFilter.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ModelBinderAccessorFilter.cs index 0b1da17e934..824c343ce51 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ModelBinderAccessorFilter.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ModelBinderAccessorFilter.cs @@ -7,9 +7,7 @@ namespace OrchardCore.DisplayManagement.ModelBinding { public class ModelBinderAccessorFilter : IActionFilter, IPageFilter { - public void OnActionExecuted(ActionExecutedContext context) - { - } + public void OnActionExecuted(ActionExecutedContext context) { } public void OnActionExecuting(ActionExecutingContext context) { @@ -21,9 +19,7 @@ public void OnActionExecuting(ActionExecutingContext context) } } - public void OnPageHandlerSelected(PageHandlerSelectedContext context) - { - } + public void OnPageHandlerSelected(PageHandlerSelectedContext context) { } public void OnPageHandlerExecuting(PageHandlerExecutingContext context) { @@ -36,8 +32,6 @@ public void OnPageHandlerExecuting(PageHandlerExecutingContext context) } } - public void OnPageHandlerExecuted(PageHandlerExecutedContext context) - { - } + public void OnPageHandlerExecuted(PageHandlerExecutedContext context) { } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ModelStateWrapperUpdater.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ModelStateWrapperUpdater.cs index 182b026a110..8b038d69c93 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ModelStateWrapperUpdater.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/ModelStateWrapperUpdater.cs @@ -18,17 +18,20 @@ public ModelStateWrapperUpdater(IUpdateModel updateModel) public ModelStateDictionary ModelState => _updater.ModelState; - public Task TryUpdateModelAsync(TModel model) where TModel : class + public Task TryUpdateModelAsync(TModel model) + where TModel : class { return PreserveModelState(() => _updater.TryUpdateModelAsync(model)); } - public Task TryUpdateModelAsync(TModel model, string prefix) where TModel : class + public Task TryUpdateModelAsync(TModel model, string prefix) + where TModel : class { return PreserveModelState(() => _updater.TryUpdateModelAsync(model, prefix)); } - public Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) where TModel : class + public Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) + where TModel : class { return PreserveModelState(() => _updater.TryUpdateModelAsync(model, prefix, includeExpressions)); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/NullModelUpdater.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/NullModelUpdater.cs index 908e777f267..0d78484815e 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/NullModelUpdater.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/NullModelUpdater.cs @@ -7,15 +7,21 @@ namespace OrchardCore.DisplayManagement.ModelBinding { public class NullModelUpdater : IUpdateModel { - public NullModelUpdater() - { - } + public NullModelUpdater() { } public ModelStateDictionary ModelState { get; } = new ModelStateDictionary(); - public Task TryUpdateModelAsync(TModel model) where TModel : class => Task.FromResult(true); - public Task TryUpdateModelAsync(TModel model, string prefix) where TModel : class => Task.FromResult(true); - public Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) where TModel : class => Task.FromResult(true); + + public Task TryUpdateModelAsync(TModel model) + where TModel : class => Task.FromResult(true); + + public Task TryUpdateModelAsync(TModel model, string prefix) + where TModel : class => Task.FromResult(true); + + public Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) + where TModel : class => Task.FromResult(true); + public bool TryValidateModel(object model) => true; + public bool TryValidateModel(object model, string prefix) => true; } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/PageModelUpdater.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/PageModelUpdater.cs index dfb6ec59f59..c7931d35802 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/PageModelUpdater.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/PageModelUpdater.cs @@ -9,13 +9,13 @@ public class PageModelUpdater : PageModel, IUpdateModel { public PageModelUpdater(PageModel page) => PageContext = page.PageContext; - public new Task TryUpdateModelAsync(TModel model) where TModel : class - => base.TryUpdateModelAsync(model); + public new Task TryUpdateModelAsync(TModel model) + where TModel : class => base.TryUpdateModelAsync(model); - public new Task TryUpdateModelAsync(TModel model, string prefix) where TModel : class - => base.TryUpdateModelAsync(model, prefix); + public new Task TryUpdateModelAsync(TModel model, string prefix) + where TModel : class => base.TryUpdateModelAsync(model, prefix); - public new Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) where TModel : class - => base.TryUpdateModelAsync(model, prefix, includeExpressions); + public new Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) + where TModel : class => base.TryUpdateModelAsync(model, prefix, includeExpressions); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/PrefixedModelUpdater.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/PrefixedModelUpdater.cs index 64cf746cae6..dbb6a5f7a62 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/PrefixedModelUpdater.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/PrefixedModelUpdater.cs @@ -9,9 +9,8 @@ public class PrefixedModelUpdater : IUpdateModel { private readonly IUpdateModel _updateModel; - public PrefixedModelUpdater(IUpdateModel updateModel) : this(updateModel, x => x) - { - } + public PrefixedModelUpdater(IUpdateModel updateModel) + : this(updateModel, x => x) { } public PrefixedModelUpdater(IUpdateModel updateModel, Func prefix) { @@ -23,18 +22,17 @@ public PrefixedModelUpdater(IUpdateModel updateModel, Func prefi public Func Prefix { get; set; } - public Task TryUpdateModelAsync(TModel model) where TModel : class - => _updateModel.TryUpdateModelAsync(model); + public Task TryUpdateModelAsync(TModel model) + where TModel : class => _updateModel.TryUpdateModelAsync(model); - public Task TryUpdateModelAsync(TModel model, string prefix) where TModel : class - => _updateModel.TryUpdateModelAsync(Prefix(prefix)); + public Task TryUpdateModelAsync(TModel model, string prefix) + where TModel : class => _updateModel.TryUpdateModelAsync(Prefix(prefix)); - public Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) where TModel : class - => _updateModel.TryUpdateModelAsync(model, Prefix(prefix), includeExpressions); + public Task TryUpdateModelAsync(TModel model, string prefix, params Expression>[] includeExpressions) + where TModel : class => _updateModel.TryUpdateModelAsync(model, Prefix(prefix), includeExpressions); public bool TryValidateModel(object model) => _updateModel.TryValidateModel(model); - public bool TryValidateModel(object model, string prefix) - => _updateModel.TryValidateModel(model, Prefix(prefix)); + public bool TryValidateModel(object model, string prefix) => _updateModel.TryValidateModel(model, Prefix(prefix)); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifierExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifierExtensions.cs index e4ec132643e..7fcb83afc6a 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifierExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifierExtensions.cs @@ -24,8 +24,7 @@ public static void Information(this INotifier notifier, LocalizedHtmlString mess /// /// The . /// A localized message to display. - public static ValueTask InformationAsync(this INotifier notifier, LocalizedHtmlString message) - => notifier.AddAsync(NotifyType.Information, message); + public static ValueTask InformationAsync(this INotifier notifier, LocalizedHtmlString message) => notifier.AddAsync(NotifyType.Information, message); /// /// Adds a new UI notification of type Warning. @@ -45,8 +44,7 @@ public static void Warning(this INotifier notifier, LocalizedHtmlString message) /// /// The . /// A localized message to display. - public static ValueTask WarningAsync(this INotifier notifier, LocalizedHtmlString message) - => notifier.AddAsync(NotifyType.Warning, message); + public static ValueTask WarningAsync(this INotifier notifier, LocalizedHtmlString message) => notifier.AddAsync(NotifyType.Warning, message); /// /// Adds a new UI notification of type Error. @@ -66,8 +64,7 @@ public static void Error(this INotifier notifier, LocalizedHtmlString message) /// /// The . /// A localized message to display. - public static ValueTask ErrorAsync(this INotifier notifier, LocalizedHtmlString message) - => notifier.AddAsync(NotifyType.Error, message); + public static ValueTask ErrorAsync(this INotifier notifier, LocalizedHtmlString message) => notifier.AddAsync(NotifyType.Error, message); /// /// Adds a new UI notification of type Success. @@ -87,7 +84,6 @@ public static void Success(this INotifier notifier, LocalizedHtmlString message) /// /// The . /// A localized message to display. - public static ValueTask SuccessAsync(this INotifier notifier, LocalizedHtmlString message) - => notifier.AddAsync(NotifyType.Success, message); + public static ValueTask SuccessAsync(this INotifier notifier, LocalizedHtmlString message) => notifier.AddAsync(NotifyType.Success, message); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyEntryConverter.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyEntryConverter.cs index 82a8c1fff6a..fb99a050e61 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyEntryConverter.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyEntryConverter.cs @@ -27,10 +27,7 @@ public override NotifyEntry Read(ref Utf8JsonReader reader, Type typeToConvert, { var jo = JObject.Load(ref reader); - var notifyEntry = new NotifyEntry - { - Message = new HtmlString(jo.Value("Message")), - }; + var notifyEntry = new NotifyEntry { Message = new HtmlString(jo.Value("Message")), }; if (Enum.TryParse(jo.Value("Type"), out var type)) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyFilter.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyFilter.cs index 84c8ab54ba8..c3a50d16e69 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyFilter.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyFilter.cs @@ -35,7 +35,8 @@ public NotifyFilter( ILayoutAccessor layoutAccessor, IDataProtectionProvider dataProtectionProvider, HtmlEncoder htmlEncoder, - ILogger logger) + ILogger logger + ) { _notifier = notifier; _shapeFactory = shapeFactory; @@ -109,9 +110,7 @@ public void OnActionExecuted(ActionExecutedContext filterContext) OnHandlerExecuted(filterContext); } - public void OnPageHandlerSelected(PageHandlerSelectedContext context) - { - } + public void OnPageHandlerSelected(PageHandlerSelectedContext context) { } public void OnPageHandlerExecuting(PageHandlerExecutingContext filterContext) { @@ -202,10 +201,7 @@ private void DeserializeNotifyEntries(string value, out NotifyEntry[] messageEnt private static CookieOptions GetCookieOptions(HttpContext httpContext) { - var cookieOptions = new CookieOptions - { - HttpOnly = true - }; + var cookieOptions = new CookieOptions { HttpOnly = true }; if (httpContext.Request.PathBase.HasValue) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ObjectPool.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ObjectPool.cs index 0b3660c8a4a..03828658802 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ObjectPool.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ObjectPool.cs @@ -24,7 +24,8 @@ namespace OrchardCore.DisplayManagement /// Rationale: /// If there is no intent for reusing the object, do not use pool - just use "new". /// - internal class ObjectPool where T : class + internal class ObjectPool + where T : class { [DebuggerDisplay("{Value,nq}")] private struct Element @@ -84,15 +85,16 @@ private string GetTrace() // If you are seeing this message it means that object has been allocated from the pool // and has not been returned back. This is not critical, but turns pool into rather // inefficient kind of "new". - Debug.WriteLine($"TRACEOBJECTPOOLLEAKS_BEGIN\nPool detected potential leaking of {typeof(T)}. \n Location of the leak: \n {GetTrace()} TRACEOBJECTPOOLLEAKS_END"); + Debug.WriteLine( + $"TRACEOBJECTPOOLLEAKS_BEGIN\nPool detected potential leaking of {typeof(T)}. \n Location of the leak: \n {GetTrace()} TRACEOBJECTPOOLLEAKS_END" + ); } } } #endif internal ObjectPool(Factory factory) - : this(factory, System.Environment.ProcessorCount * 2) - { } + : this(factory, System.Environment.ProcessorCount * 2) { } internal ObjectPool(Factory factory, int size) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/OrchardCoreBuilderExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement/OrchardCoreBuilderExtensions.cs index ca2bff861f0..4d0bf8627ca 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/OrchardCoreBuilderExtensions.cs @@ -34,15 +34,18 @@ public static class OrchardCoreBuilderExtensions /// public static OrchardCoreBuilder AddTheming(this OrchardCoreBuilder builder) { - builder.AddThemingHost() + builder + .AddThemingHost() .ConfigureServices(services => { - services.Configure((options) => - { - options.Filters.Add(typeof(ModelBinderAccessorFilter)); - options.Filters.Add(typeof(NotifyFilter)); - options.Filters.Add(typeof(RazorViewActionFilter)); - }); + services.Configure( + (options) => + { + options.Filters.Add(typeof(ModelBinderAccessorFilter)); + options.Filters.Add(typeof(NotifyFilter)); + options.Filters.Add(typeof(RazorViewActionFilter)); + } + ); // Used as a service when we create a fake 'ActionContext'. services.AddScoped(); @@ -65,8 +68,7 @@ public static OrchardCoreBuilder AddTheming(this OrchardCoreBuilder builder) services.AddScoped(); - services.TryAddEnumerable( - ServiceDescriptor.Transient, ShapeTemplateOptionsSetup>()); + services.TryAddEnumerable(ServiceDescriptor.Transient, ShapeTemplateOptionsSetup>()); services.TryAddSingleton(); services.AddShapeAttributes(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorPage.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorPage.cs index f99f8798a09..24b91c2a99c 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorPage.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorPage.cs @@ -132,7 +132,6 @@ public string ViewLayout return string.Empty; } - set { if (ThemeLayout is IShape layout) @@ -327,7 +326,5 @@ public static object OrDefault(object text, object other) public ISite Site => _site ??= Context.Features.Get()?.Site; } - public abstract class RazorPage : RazorPage - { - } + public abstract class RazorPage : RazorPage { } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorShapeTemplateViewEngine.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorShapeTemplateViewEngine.cs index 04980a050ac..8b31f1724b8 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorShapeTemplateViewEngine.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorShapeTemplateViewEngine.cs @@ -35,7 +35,8 @@ public RazorShapeTemplateViewEngine( IEnumerable viewExtensionProviders, IHttpContextAccessor httpContextAccessor, ViewContextAccessor viewContextAccessor, - ITempDataProvider tempDataProvider) + ITempDataProvider tempDataProvider + ) { _options = options; _httpContextAccessor = httpContextAccessor; @@ -46,10 +47,7 @@ public RazorShapeTemplateViewEngine( public IEnumerable TemplateFileExtensions { - get - { - return _templateFileExtensions; - } + get { return _templateFileExtensions; } } public Task RenderAsync(string relativePath, DisplayContext displayContext) @@ -79,10 +77,14 @@ private async Task RenderRazorViewAsync(string viewName, DisplayCo if (viewEngines.Count == 0) { - throw new InvalidOperationException(string.Format("'{0}.{1}' must not be empty. At least one '{2}' is required to locate a view for rendering.", - typeof(MvcViewOptions).FullName, - nameof(MvcViewOptions.ViewEngines), - typeof(IViewEngine).FullName)); + throw new InvalidOperationException( + string.Format( + "'{0}.{1}' must not be empty. At least one '{2}' is required to locate a view for rendering.", + typeof(MvcViewOptions).FullName, + nameof(MvcViewOptions.ViewEngines), + typeof(IViewEngine).FullName + ) + ); } var viewEngine = viewEngines[0]; @@ -101,17 +103,11 @@ public async Task RenderViewToStringAsync(string viewName, object model, var viewContext = new ViewContext( actionContext, view, - new ViewDataDictionary( - metadataProvider: new EmptyModelMetadataProvider(), - modelState: new ModelStateDictionary()) - { - Model = model - }, - new TempDataDictionary( - actionContext.HttpContext, - _tempDataProvider), + new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary()) { Model = model }, + new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), output, - new HtmlHelperOptions()); + new HtmlHelperOptions() + ); await view.RenderAsync(viewContext); @@ -135,7 +131,8 @@ private static IView FindView(ActionContext actionContext, string viewName, IVie var searchedLocations = getViewResult.SearchedLocations.Concat(findViewResult.SearchedLocations); var errorMessage = string.Join( System.Environment.NewLine, - new[] { $"Unable to find view '{viewName}'. The following locations were searched:" }.Concat(searchedLocations)); + new[] { $"Unable to find view '{viewName}'. The following locations were searched:" }.Concat(searchedLocations) + ); throw new InvalidOperationException(errorMessage); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorViewActionFilter.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorViewActionFilter.cs index bd75a21e4d8..92d10c5f0b7 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorViewActionFilter.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorViewActionFilter.cs @@ -24,9 +24,7 @@ static async Task Awaited(Task task, ActionExecutionDelegate next) } var task = OnActionExecutionAsync(context); - return !task.IsCompletedSuccessfully - ? Awaited(task, next) - : next(); + return !task.IsCompletedSuccessfully ? Awaited(task, next) : next(); } public async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/RazorPages/Page.cs b/src/OrchardCore/OrchardCore.DisplayManagement/RazorPages/Page.cs index 8f975d0b80e..f99f7a60ecf 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/RazorPages/Page.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/RazorPages/Page.cs @@ -133,7 +133,6 @@ public string ViewLayout return string.Empty; } - set { if (ThemeLayout is IShape layout) diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ShapeAttribute.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ShapeAttribute.cs index 6a98bf8e312..9d91dfd804f 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ShapeAttribute.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ShapeAttribute.cs @@ -5,9 +5,7 @@ namespace OrchardCore.DisplayManagement [AttributeUsage(AttributeTargets.Method)] public class ShapeAttribute : Attribute { - public ShapeAttribute() - { - } + public ShapeAttribute() { } public ShapeAttribute(string shapeType) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Composite.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Composite.cs index 8118700e6df..c7b55aa9809 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Composite.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Composite.cs @@ -160,12 +160,13 @@ public override int GetHashCode() public class Nil : DynamicObject { private static readonly Nil _singleton = new(); - public static Nil Instance { get { return _singleton; } } - - private Nil() + public static Nil Instance { + get { return _singleton; } } + private Nil() { } + public override bool TryGetMember(GetMemberBinder binder, out object result) { result = Instance; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/CoreShapes.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/CoreShapes.cs index 070b1594679..3d9bd7456c2 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/CoreShapes.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/CoreShapes.cs @@ -22,13 +22,17 @@ public void PlaceChildContent(dynamic Source, TextWriter Output) [Shape] #pragma warning disable CA1822 // Mark members as static - public async Task List(Shape shape, DisplayContext displayContext, IEnumerable Items, + public async Task List( + Shape shape, + DisplayContext displayContext, + IEnumerable Items, #pragma warning restore CA1822 // Mark members as static string ItemTagName, IEnumerable ItemClasses, IDictionary ItemAttributes, string FirstClass, - string LastClass) + string LastClass + ) { if (Items == null) { @@ -123,7 +127,8 @@ public class CoreShapesTableProvider : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("List") + builder + .Describe("List") .OnCreated(created => { dynamic list = created.Shape; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/DateTimeShapes.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/DateTimeShapes.cs index a54ef37848c..f9273da9d21 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/DateTimeShapes.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/DateTimeShapes.cs @@ -19,12 +19,7 @@ public class DateTimeShapes : IShapeAttributeProvider protected readonly IStringLocalizer S; protected readonly IHtmlLocalizer H; - public DateTimeShapes( - IClock clock, - IStringLocalizer localizer, - IHtmlLocalizer htmlLocalizer, - ILocalClock localClock - ) + public DateTimeShapes(IClock clock, IStringLocalizer localizer, IHtmlLocalizer htmlLocalizer, ILocalClock localClock) { _localClock = localClock; _clock = clock; @@ -110,9 +105,7 @@ public IHtmlContent TimeSpan(DateTime? Utc, DateTime? Origin) return H.Plural(-time.Seconds, "in 1 second", "in {0} seconds"); } - return time.TotalMilliseconds > 0 - ? H["a moment ago"] - : H["in a moment"]; + return time.TotalMilliseconds > 0 ? H["a moment ago"] : H["in a moment"]; } [Shape] diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/GroupShapes.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/GroupShapes.cs index 0a320bce025..4fb1095259a 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/GroupShapes.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/GroupShapes.cs @@ -178,11 +178,7 @@ public async Task Tab(IDisplayHelper displayAsync, GroupingViewMod [Shape] public async Task TabContainer(IDisplayHelper displayAsync, GroupingsViewModel shape, IShapeFactory shapeFactory) { - var localNavigation = await shapeFactory.CreateAsync("LocalNavigation", Arguments.From(new - { - shape.Identifier, - Tabs = shape.Groupings - })); + var localNavigation = await shapeFactory.CreateAsync("LocalNavigation", Arguments.From(new { shape.Identifier, Tabs = shape.Groupings })); var htmlContentBuilder = new HtmlContentBuilder(); htmlContentBuilder.AppendHtml(await displayAsync.ShapeExecuteAsync(localNavigation)); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Shape.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Shape.cs index ae7f47ea11d..9ccf112d70e 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Shape.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Shape.cs @@ -192,9 +192,7 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o // In case AddAsync() is called on a dynamic object, to prevent Composite from seing it as a property assignment. if (binder.Name == "AddAsync") { - result = - AddAsync(args.Length > 0 ? args[0] : null, args.Length > 1 ? args[1].ToString() : "") - .AsTask(); + result = AddAsync(args.Length > 0 ? args[0] : null, args.Length > 1 ? args[1].ToString() : "").AsTask(); return true; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeDebugView.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeDebugView.cs index 338fb04223e..191482262ac 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeDebugView.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeDebugView.cs @@ -13,22 +13,32 @@ public ShapeDebugView(Shape shape) _shape = shape; } - public ShapeMetadata Metadata { get { return _shape.Metadata; } } + public ShapeMetadata Metadata + { + get { return _shape.Metadata; } + } - public string Id { get { return _shape.Id; } } - public IList Classes { get { return _shape.Classes; } } - public IDictionary Attributes { get { return _shape.Attributes; } } - public IEnumerable Items { get { return _shape.Items; } } + public string Id + { + get { return _shape.Id; } + } + public IList Classes + { + get { return _shape.Classes; } + } + public IDictionary Attributes + { + get { return _shape.Attributes; } + } + public IEnumerable Items + { + get { return _shape.Items; } + } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePairs[] Properties { - get - { - return _shape.Properties - .Select(entry => new KeyValuePairs(entry.Key, entry.Value)) - .ToArray(); - } + get { return _shape.Properties.Select(entry => new KeyValuePairs(entry.Key, entry.Value)).ToArray(); } } [DebuggerDisplay(" { _shapeType == null ? _value : \"Shape: \" + _shapeType}", Name = "{_key,nq}")] diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeSerializer.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeSerializer.cs index c91cbb006ca..0d7313e7779 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeSerializer.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeSerializer.cs @@ -14,10 +14,7 @@ namespace OrchardCore.DisplayManagement.Shapes /// public class ShapeSerializer { - private static readonly JsonSerializerOptions _shapeJsonSerializer = new() - { - ReferenceHandler = ReferenceHandler.IgnoreCycles, - }; + private static readonly JsonSerializerOptions _shapeJsonSerializer = new() { ReferenceHandler = ReferenceHandler.IgnoreCycles, }; private readonly HashSet _shapes = []; private readonly IShape _shape; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/DateTimeTagHelper.cs b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/DateTimeTagHelper.cs index 9a585bebe92..c86d413e410 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/DateTimeTagHelper.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/DateTimeTagHelper.cs @@ -25,7 +25,7 @@ public DateTimeTagHelper(IShapeFactory shapeFactory, IDisplayHelper displayHelpe [HtmlAttributeName(FormatAttribute)] public string Format { set; get; } - public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var shapeType = "DateTime"; dynamic shape = await _shapeFactory.CreateAsync(shapeType); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ShapeTagHelper.cs b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ShapeTagHelper.cs index 4b7c8839863..9ae8b01cb39 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ShapeTagHelper.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ShapeTagHelper.cs @@ -7,8 +7,6 @@ namespace OrchardCore.DisplayManagement.TagHelpers public class ShapeTagHelper : BaseShapeTagHelper { public ShapeTagHelper(IShapeFactory shapeFactory, IDisplayHelper displayHelper) - : base(shapeFactory, displayHelper) - { - } + : base(shapeFactory, displayHelper) { } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/TimeSpanTagHelper.cs b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/TimeSpanTagHelper.cs index aeecb9c99c9..c51ba6a5e93 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/TimeSpanTagHelper.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/TimeSpanTagHelper.cs @@ -25,7 +25,7 @@ public TimeSpanTagHelper(IShapeFactory shapeFactory, IDisplayHelper displayHelpe [HtmlAttributeName(OriginAttribute)] public DateTime? Origin { set; get; } - public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var shapeType = "TimeSpan"; dynamic shape = await _shapeFactory.CreateAsync(shapeType); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ValidationMessageTagHelper.cs b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ValidationMessageTagHelper.cs index 0c3d12fe50a..d51147aa8a8 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ValidationMessageTagHelper.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ValidationMessageTagHelper.cs @@ -25,10 +25,7 @@ public ValidationMessageTagHelper(IHtmlHelper htmlHelper) /// public override int Order { - get - { - return -1000; - } + get { return -1000; } } [HtmlAttributeNotBound] diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ZoneTagHelper.cs b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ZoneTagHelper.cs index c9d1cba3ae4..f480f9ae70a 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ZoneTagHelper.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ZoneTagHelper.cs @@ -47,10 +47,10 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu else { _logger.LogWarning( - "Unable to add shape to the zone using the tag helper because the zone's type is " + - "\"{ActualType}\" instead of the expected {ExpectedType}", + "Unable to add shape to the zone using the tag helper because the zone's type is " + "\"{ActualType}\" instead of the expected {ExpectedType}", zone.GetType().FullName, - nameof(Shape)); + nameof(Shape) + ); } // Don't render the zone tag or the inner content diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemeManager.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemeManager.cs index 9a37c268b18..5f43a66d092 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemeManager.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemeManager.cs @@ -12,9 +12,7 @@ public class ThemeManager : IThemeManager private IExtensionInfo _theme; - public ThemeManager( - IEnumerable themeSelectors, - IExtensionManager extensionManager) + public ThemeManager(IEnumerable themeSelectors, IExtensionManager extensionManager) { _themeSelectors = themeSelectors; _extensionManager = extensionManager; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemingViewsFeatureProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemingViewsFeatureProvider.cs index 5738daffee4..083ec8a0cda 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemingViewsFeatureProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemingViewsFeatureProvider.cs @@ -15,25 +15,27 @@ public class ThemingViewsFeatureProvider : IApplicationFeatureProvider parts, ViewsFeature feature) { - feature.ViewDescriptors.Add(new CompiledViewDescriptor() - { - ExpirationTokens = Array.Empty(), - RelativePath = "/_ViewStart" + RazorViewEngine.ViewExtension, - Item = new TenantRazorCompiledItem(typeof(ThemeViewStart), "/_ViewStart") - }); + feature.ViewDescriptors.Add( + new CompiledViewDescriptor() + { + ExpirationTokens = Array.Empty(), + RelativePath = "/_ViewStart" + RazorViewEngine.ViewExtension, + Item = new TenantRazorCompiledItem(typeof(ThemeViewStart), "/_ViewStart") + } + ); - feature.ViewDescriptors.Add(new CompiledViewDescriptor() - { - ExpirationTokens = Array.Empty(), - RelativePath = '/' + ThemeLayoutFileName, - Item = new TenantRazorCompiledItem(typeof(ThemeLayout), '/' + ThemeLayoutFileName) - }); + feature.ViewDescriptors.Add( + new CompiledViewDescriptor() + { + ExpirationTokens = Array.Empty(), + RelativePath = '/' + ThemeLayoutFileName, + Item = new TenantRazorCompiledItem(typeof(ThemeLayout), '/' + ThemeLayoutFileName) + } + ); } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Title/PageTitleBuilder.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Title/PageTitleBuilder.cs index 165bf0801ec..b3fc932887b 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Title/PageTitleBuilder.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Title/PageTitleBuilder.cs @@ -6,7 +6,7 @@ namespace OrchardCore.DisplayManagement.Title { public class PageTitleBuilder : IPageTitleBuilder { - private readonly static HtmlString _defaultTitleSeparator = new(" - "); + private static readonly HtmlString _defaultTitleSeparator = new(" - "); private readonly List _titleParts; private HtmlContentBuilder _title; @@ -26,11 +26,7 @@ public void AddSegment(IHtmlContent titlePart, string position) { _title = null; - _titleParts.Add(new PositionalTitlePart - { - Value = titlePart, - Position = position - }); + _titleParts.Add(new PositionalTitlePart { Value = titlePart, Position = position }); } public void AddSegments(IEnumerable titleParts, string position) diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeResult.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeResult.cs index abd04a4d42e..42605b59d24 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeResult.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeResult.cs @@ -27,9 +27,7 @@ public class ShapeResult : IDisplayResult private Func> _renderPredicateAsync; public ShapeResult(string shapeType, Func> shapeBuilder) - : this(shapeType, shapeBuilder, null) - { - } + : this(shapeType, shapeBuilder, null) { } public ShapeResult(string shapeType, Func> shapeBuilder, Func processing) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModel.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModel.cs index c6b8ce84d72..2fc052c6487 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModel.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModel.cs @@ -10,9 +10,7 @@ namespace OrchardCore.DisplayManagement.Views { public class ShapeViewModel : IShape, IPositioned { - public ShapeViewModel() - { - } + public ShapeViewModel() { } public ShapeViewModel(string shapeType) { @@ -28,10 +26,7 @@ public ShapeViewModel(string shapeType) public string Position { get => Metadata.Position; - set - { - Metadata.Position = value; - } + set { Metadata.Position = value; } } public string Id { get; set; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModelOfT.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModelOfT.cs index 0ba3fbb215f..ccf49f76840 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModelOfT.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModelOfT.cs @@ -3,9 +3,7 @@ namespace OrchardCore.DisplayManagement.Views public class ShapeViewModel : ShapeViewModel { public ShapeViewModel(T value) - : this(typeof(T).Name, value) - { - } + : this(typeof(T).Name, value) { } public ShapeViewModel(string shapeType, T value) : base(shapeType) diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Zones/FlatPositionComparer.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Zones/FlatPositionComparer.cs index fa911de9c41..fe9df3b7ad6 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Zones/FlatPositionComparer.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Zones/FlatPositionComparer.cs @@ -12,9 +12,7 @@ static FlatPositionComparer() Instance = new FlatPositionComparer(); } - private FlatPositionComparer() - { - } + private FlatPositionComparer() { } public int Compare(IPositioned a, IPositioned b) { @@ -32,12 +30,18 @@ public int Compare(string x, string y) } // null == "before"; "" == "0" - x = x == null - ? "before." // in order to have before < null when 'before' is explicitly defined - : x.Trim().Length == 0 ? "0" : x.Trim(':').TrimEnd('.'); // ':' is _sometimes_ used as a partition identifier - y = y == null - ? "before." - : y.Trim().Length == 0 ? "0" : y.Trim(':').TrimEnd('.'); + x = + x == null + ? "before." // in order to have before < null when 'before' is explicitly defined + : x.Trim().Length == 0 + ? "0" + : x.Trim(':').TrimEnd('.'); // ':' is _sometimes_ used as a partition identifier + y = + y == null + ? "before." + : y.Trim().Length == 0 + ? "0" + : y.Trim(':').TrimEnd('.'); var xParts = x.Split(['.', ':']); var yParts = y.Split(['.', ':']); @@ -49,7 +53,8 @@ public int Compare(string x, string y) return 1; } - int xPos, yPos; + int xPos, + yPos; var xPart = string.IsNullOrEmpty(xParts[i]) ? "before" : NormalizeKnownPartitions(xParts[i]); var yPart = string.IsNullOrEmpty(yParts[i]) ? "before" : NormalizeKnownPartitions(yParts[i]); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapeAlternates.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapeAlternates.cs index 04442228b03..3c994c1ecd8 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapeAlternates.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapeAlternates.cs @@ -7,7 +7,8 @@ public class ZoneShapeAlternates : ShapeTableProvider { public override ValueTask DiscoverAsync(ShapeTableBuilder builder) { - builder.Describe("Zone") + builder + .Describe("Zone") .OnDisplaying(context => { if (context.Shape.TryGetProperty("ZoneName", out string zoneName)) diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapes.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapes.cs index 2c268a978fc..dff5392eb92 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapes.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapes.cs @@ -41,10 +41,9 @@ public async Task ContentZone(IDisplayHelper DisplayAsync, dynamic var shapes = ((IEnumerable)Shape); // Evaluate shapes for grouping metadata, when it is not an IShape it cannot be grouped. - var isGrouped = shapes.Any(x => x is IShape s && - (!string.IsNullOrEmpty(s.Metadata.Tab) || - !string.IsNullOrEmpty(s.Metadata.Card) || - !string.IsNullOrEmpty(s.Metadata.Column))); + var isGrouped = shapes.Any(x => + x is IShape s && (!string.IsNullOrEmpty(s.Metadata.Tab) || !string.IsNullOrEmpty(s.Metadata.Card) || !string.IsNullOrEmpty(s.Metadata.Column)) + ); // When there is no grouping metadata on any shapes just render the Zone. if (!isGrouped) @@ -85,44 +84,57 @@ public async Task ContentZone(IDisplayHelper DisplayAsync, dynamic // Process Tabs first, then Cards, then Columns. if (groupings.Count > 1) { - var orderedGroupings = groupings.OrderBy(grouping => - { - var firstGroupWithModifier = grouping.FirstOrDefault(group => - { - if (group is IShape s && !string.IsNullOrEmpty(s.Metadata.Tab) && s.Metadata.Tab.Contains(';')) + var orderedGroupings = groupings + .OrderBy( + grouping => { - return true; + var firstGroupWithModifier = grouping.FirstOrDefault(group => + { + if (group is IShape s && !string.IsNullOrEmpty(s.Metadata.Tab) && s.Metadata.Tab.Contains(';')) + { + return true; + } + + return false; + }); + + if (firstGroupWithModifier is IShape shape) + { + var key = shape.Metadata.Tab; + var modifierIndex = key.IndexOf(';'); + + return new PositionalGrouping(key[modifierIndex..]); + } + + return new PositionalGrouping(null); + }, + FlatPositionComparer.Instance + ) + .ToArray(); + + var container = (GroupingsViewModel) + await ShapeFactory.CreateAsync( + "TabContainer", + m => + { + m.Identifier = identifier; + m.Groupings = orderedGroupings; } - - return false; - }); - - if (firstGroupWithModifier is IShape shape) - { - var key = shape.Metadata.Tab; - var modifierIndex = key.IndexOf(';'); - - return new PositionalGrouping(key[modifierIndex..]); - } - - return new PositionalGrouping(null); - }, FlatPositionComparer.Instance).ToArray(); - - var container = (GroupingsViewModel)await ShapeFactory.CreateAsync("TabContainer", m => - { - m.Identifier = identifier; - m.Groupings = orderedGroupings; - }); + ); container.Classes.Add("accordion"); foreach (var orderedGrouping in orderedGroupings) { - var groupingShape = (GroupingViewModel)await ShapeFactory.CreateAsync("Tab", m => - { - m.Identifier = identifier; - m.Grouping = orderedGrouping; - }); + var groupingShape = (GroupingViewModel) + await ShapeFactory.CreateAsync( + "Tab", + m => + { + m.Identifier = identifier; + m.Grouping = orderedGrouping; + } + ); foreach (var item in orderedGrouping) { @@ -137,11 +149,15 @@ public async Task ContentZone(IDisplayHelper DisplayAsync, dynamic else if (groupings.Count == 1) { // Evaluate for cards. - var cardGrouping = (GroupingViewModel)await ShapeFactory.CreateAsync("CardGrouping", m => - { - m.Identifier = identifier; - m.Grouping = groupings.ElementAt(0); - }); + var cardGrouping = (GroupingViewModel) + await ShapeFactory.CreateAsync( + "CardGrouping", + m => + { + m.Identifier = identifier; + m.Grouping = groupings.ElementAt(0); + } + ); htmlContentBuilder.AppendHtml(await DisplayAsync.ShapeExecuteAsync(cardGrouping)); } @@ -177,47 +193,57 @@ public async Task CardGrouping(IDisplayHelper DisplayAsync, Groupi } return ContentKey; - }); if (groupings.Count > 1) { - var orderedGroupings = groupings.OrderBy(grouping => - { - var firstGroupWithModifier = grouping.FirstOrDefault(group => + var orderedGroupings = groupings.OrderBy( + grouping => { - if (group is IShape s && !string.IsNullOrEmpty(s.Metadata.Card) && s.Metadata.Card.Contains(';')) + var firstGroupWithModifier = grouping.FirstOrDefault(group => { - return true; - } - - return false; - }); + if (group is IShape s && !string.IsNullOrEmpty(s.Metadata.Card) && s.Metadata.Card.Contains(';')) + { + return true; + } - if (firstGroupWithModifier is IShape shape) - { - var key = shape.Metadata.Card; - var modifierIndex = key.IndexOf(';'); - return new PositionalGrouping(key[modifierIndex..]); - } + return false; + }); - return new PositionalGrouping(); - }, FlatPositionComparer.Instance); + if (firstGroupWithModifier is IShape shape) + { + var key = shape.Metadata.Card; + var modifierIndex = key.IndexOf(';'); + return new PositionalGrouping(key[modifierIndex..]); + } - var container = (GroupViewModel)await ShapeFactory.CreateAsync("CardContainer", m => - { - m.Identifier = Shape.Identifier; - }); + return new PositionalGrouping(); + }, + FlatPositionComparer.Instance + ); + + var container = (GroupViewModel) + await ShapeFactory.CreateAsync( + "CardContainer", + m => + { + m.Identifier = Shape.Identifier; + } + ); container.Classes.Add("accordion"); foreach (var orderedGrouping in orderedGroupings) { - var groupingShape = (GroupingViewModel)await ShapeFactory.CreateAsync("Card", m => - { - m.Identifier = Shape.Identifier; - m.Grouping = orderedGrouping; - }); + var groupingShape = (GroupingViewModel) + await ShapeFactory.CreateAsync( + "Card", + m => + { + m.Identifier = Shape.Identifier; + m.Grouping = orderedGrouping; + } + ); foreach (var item in orderedGrouping) { @@ -232,11 +258,15 @@ public async Task CardGrouping(IDisplayHelper DisplayAsync, Groupi else { // Evaluate for columns. - var groupingShape = (GroupingViewModel)await ShapeFactory.CreateAsync("ColumnGrouping", m => - { - m.Identifier = Shape.Identifier; - m.Grouping = Shape.Grouping; - }); + var groupingShape = (GroupingViewModel) + await ShapeFactory.CreateAsync( + "ColumnGrouping", + m => + { + m.Identifier = Shape.Identifier; + m.Grouping = Shape.Grouping; + } + ); htmlContentBuilder.AppendHtml(await DisplayAsync.ShapeExecuteAsync(groupingShape)); } @@ -285,32 +315,43 @@ public async Task ColumnGrouping(IDisplayHelper DisplayAsync, Grou { var positionModifiers = GetColumnPositions(groupings); - var orderedGroupings = groupings.OrderBy(grouping => - { - if (positionModifiers.TryGetValue(grouping.Key, out var position)) - { - return new PositionalGrouping { Position = position }; - } - else + var orderedGroupings = groupings.OrderBy( + grouping => { - return new PositionalGrouping(); - } - }, FlatPositionComparer.Instance); + if (positionModifiers.TryGetValue(grouping.Key, out var position)) + { + return new PositionalGrouping { Position = position }; + } + else + { + return new PositionalGrouping(); + } + }, + FlatPositionComparer.Instance + ); var columnModifiers = GetColumnModifiers(orderedGroupings); - var container = (GroupViewModel)await ShapeFactory.CreateAsync("ColumnContainer", m => - { - m.Identifier = Shape.Identifier; - }); + var container = (GroupViewModel) + await ShapeFactory.CreateAsync( + "ColumnContainer", + m => + { + m.Identifier = Shape.Identifier; + } + ); foreach (var orderedGrouping in orderedGroupings) { - var groupingShape = (GroupingViewModel)await ShapeFactory.CreateAsync("Column", m => - { - m.Identifier = Shape.Identifier; - m.Grouping = orderedGrouping; - }); + var groupingShape = (GroupingViewModel) + await ShapeFactory.CreateAsync( + "Column", + m => + { + m.Identifier = Shape.Identifier; + m.Grouping = orderedGrouping; + } + ); groupingShape.Classes.Add("ta-col-grouping"); groupingShape.Classes.Add("column-" + orderedGrouping.Key.HtmlClassify()); @@ -352,6 +393,7 @@ public async Task ColumnGrouping(IDisplayHelper DisplayAsync, Grou return htmlContentBuilder; } + private static Dictionary GetColumnPositions(ILookup groupings) { var positionModifiers = new Dictionary(); @@ -440,9 +482,7 @@ private static object FirstGroupingWithModifierOrDefault(IGroupingThe . /// The . /// The . - public SmtpService( - IOptions options, - ILogger logger, - IStringLocalizer stringLocalizer) + public SmtpService(IOptions options, ILogger logger, IStringLocalizer stringLocalizer) { _options = options.Value; _logger = logger; @@ -62,9 +59,7 @@ public async Task SendAsync(MailMessage message) try { // Set the MailMessage.From, to avoid the confusion between _options.DefaultSender (Author) and submitter (Sender) - var senderAddress = string.IsNullOrWhiteSpace(message.From) - ? _options.DefaultSender - : message.From; + var senderAddress = string.IsNullOrWhiteSpace(message.From) ? _options.DefaultSender : message.From; if (!string.IsNullOrWhiteSpace(senderAddress)) { @@ -111,9 +106,7 @@ public async Task SendAsync(MailMessage message) private MimeMessage FromMailMessage(MailMessage message, List errors) { - var submitterAddress = string.IsNullOrWhiteSpace(message.Sender) - ? _options.DefaultSender - : message.Sender; + var submitterAddress = string.IsNullOrWhiteSpace(message.Sender) ? _options.DefaultSender : message.Sender; var mimeMessage = new MimeMessage(); @@ -122,7 +115,6 @@ private MimeMessage FromMailMessage(MailMessage message, List e if (MailboxAddress.TryParse(submitterAddress, out var mailBox)) { mimeMessage.Sender = mailBox; - } else { @@ -297,21 +289,17 @@ private static Task SendOfflineMessageAsync(MimeMessage message, string pickupDi private bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { - const string logErrorMessage = "SMTP Server's certificate {CertificateSubject} issued by {CertificateIssuer} " + - "with thumbprint {CertificateThumbprint} and expiration date {CertificateExpirationDate} " + - "is considered invalid with {SslPolicyErrors} policy errors"; + const string logErrorMessage = + "SMTP Server's certificate {CertificateSubject} issued by {CertificateIssuer} " + + "with thumbprint {CertificateThumbprint} and expiration date {CertificateExpirationDate} " + + "is considered invalid with {SslPolicyErrors} policy errors"; if (sslPolicyErrors == SslPolicyErrors.None) { return true; } - _logger.LogError(logErrorMessage, - certificate.Subject, - certificate.Issuer, - certificate.GetCertHashString(), - certificate.GetExpirationDateString(), - sslPolicyErrors); + _logger.LogError(logErrorMessage, certificate.Subject, certificate.Issuer, certificate.GetCertHashString(), certificate.GetExpirationDateString(), sslPolicyErrors); if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors) && chain?.ChainStatus != null) { diff --git a/src/OrchardCore/OrchardCore.Features.Core/Services/FeatureService.cs b/src/OrchardCore/OrchardCore.Features.Core/Services/FeatureService.cs index 0d23bd7bdf4..3dc22ff69fb 100644 --- a/src/OrchardCore/OrchardCore.Features.Core/Services/FeatureService.cs +++ b/src/OrchardCore/OrchardCore.Features.Core/Services/FeatureService.cs @@ -75,7 +75,12 @@ public async Task> GetModuleFeaturesAsync() return moduleFeatures; } - public async Task EnableOrDisableFeaturesAsync(IEnumerable features, FeaturesBulkAction action, bool? force, Func, bool, Task> notifyAsync) + public async Task EnableOrDisableFeaturesAsync( + IEnumerable features, + FeaturesBulkAction action, + bool? force, + Func, bool, Task> notifyAsync + ) { switch (action) { diff --git a/src/OrchardCore/OrchardCore.Feeds.Abstractions/Extensions/FeedBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Feeds.Abstractions/Extensions/FeedBuilderExtensions.cs index 97b8cde1c89..a9a0df460c2 100644 --- a/src/OrchardCore/OrchardCore.Feeds.Abstractions/Extensions/FeedBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Feeds.Abstractions/Extensions/FeedBuilderExtensions.cs @@ -5,7 +5,7 @@ namespace OrchardCore.Feeds { public static class FeedBuilderExtensions { - public static void AddProperty(this IFeedBuilder feedBuilder, FeedContext context, FeedItem feedItem, string name, string value) - => feedBuilder.AddProperty(context, feedItem, new XElement(name, value)); + public static void AddProperty(this IFeedBuilder feedBuilder, FeedContext context, FeedItem feedItem, string name, string value) => + feedBuilder.AddProperty(context, feedItem, new XElement(name, value)); } } diff --git a/src/OrchardCore/OrchardCore.Feeds.Abstractions/Models/FeedItem.cs b/src/OrchardCore/OrchardCore.Feeds.Abstractions/Models/FeedItem.cs index f59e335f3dd..467ff1edf35 100644 --- a/src/OrchardCore/OrchardCore.Feeds.Abstractions/Models/FeedItem.cs +++ b/src/OrchardCore/OrchardCore.Feeds.Abstractions/Models/FeedItem.cs @@ -5,7 +5,11 @@ namespace OrchardCore.Feeds.Models public class FeedItem { private object _item; - public object Item { get { return _item; } set { SetItem(value); } } + public object Item + { + get { return _item; } + set { SetItem(value); } + } public XElement Element { get; set; } protected virtual void SetItem(object item) @@ -17,7 +21,11 @@ protected virtual void SetItem(object item) public class FeedItem : FeedItem { private TItem _item; - public new TItem Item { get { return _item; } set { SetItem(value); } } + public new TItem Item + { + get { return _item; } + set { SetItem(value); } + } protected override void SetItem(object item) { diff --git a/src/OrchardCore/OrchardCore.Feeds.Abstractions/Models/FeedResponse.cs b/src/OrchardCore/OrchardCore.Feeds.Abstractions/Models/FeedResponse.cs index 357593001ee..946e477c2da 100644 --- a/src/OrchardCore/OrchardCore.Feeds.Abstractions/Models/FeedResponse.cs +++ b/src/OrchardCore/OrchardCore.Feeds.Abstractions/Models/FeedResponse.cs @@ -9,6 +9,7 @@ public class FeedResponse public XElement Element { get; set; } public IList Items { get; } = []; public IList> Contextualizers { get; } = []; + public void Contextualize(Action contextualizer) { Contextualizers.Add(contextualizer); diff --git a/src/OrchardCore/OrchardCore.Feeds.Core/Rss/RssFeedBuilder.cs b/src/OrchardCore/OrchardCore.Feeds.Core/Rss/RssFeedBuilder.cs index c75af64b5e6..db6c84b9bf6 100644 --- a/src/OrchardCore/OrchardCore.Feeds.Core/Rss/RssFeedBuilder.cs +++ b/src/OrchardCore/OrchardCore.Feeds.Core/Rss/RssFeedBuilder.cs @@ -23,11 +23,7 @@ public async Task ProcessAsync(FeedContext context, Func popula public FeedItem AddItem(FeedContext context, TItem item) { - var feedItem = new FeedItem - { - Item = item, - Element = new XElement("item"), - }; + var feedItem = new FeedItem { Item = item, Element = new XElement("item"), }; context.Response.Items.Add(feedItem); context.Response.Element.Add(feedItem.Element); return feedItem; diff --git a/src/OrchardCore/OrchardCore.Feeds.Core/Rss/RssFeedBuilderProvider.cs b/src/OrchardCore/OrchardCore.Feeds.Core/Rss/RssFeedBuilderProvider.cs index 01ff390978c..9dceef92186 100644 --- a/src/OrchardCore/OrchardCore.Feeds.Core/Rss/RssFeedBuilderProvider.cs +++ b/src/OrchardCore/OrchardCore.Feeds.Core/Rss/RssFeedBuilderProvider.cs @@ -8,11 +8,7 @@ public FeedBuilderMatch Match(FeedContext context) { if (context.Format == "rss") { - return new FeedBuilderMatch - { - FeedBuilder = new RssFeedBuilder(), - Priority = -5 - }; + return new FeedBuilderMatch { FeedBuilder = new RssFeedBuilder(), Priority = -5 }; } return null; diff --git a/src/OrchardCore/OrchardCore.FileStorage.Abstractions/FileStoreException.cs b/src/OrchardCore/OrchardCore.FileStorage.Abstractions/FileStoreException.cs index 232952edb7a..99ba57d7387 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.Abstractions/FileStoreException.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.Abstractions/FileStoreException.cs @@ -4,12 +4,10 @@ namespace OrchardCore.FileStorage { public class FileStoreException : Exception { - public FileStoreException(string message) : base(message) - { - } + public FileStoreException(string message) + : base(message) { } - public FileStoreException(string message, Exception innerException) : base(message, innerException) - { - } + public FileStoreException(string message, Exception innerException) + : base(message, innerException) { } } } diff --git a/src/OrchardCore/OrchardCore.FileStorage.Abstractions/IFileStore.cs b/src/OrchardCore/OrchardCore.FileStorage.Abstractions/IFileStore.cs index fb27eac85e0..6a8dae5afd1 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.Abstractions/IFileStore.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.Abstractions/IFileStore.cs @@ -127,11 +127,7 @@ public static string Combine(this IFileStore fileStore, params string[] paths) if (paths.Length == 0) return null; - var normalizedParts = - paths - .Select(x => fileStore.NormalizePath(x)) - .Where(x => !string.IsNullOrEmpty(x)) - .ToArray(); + var normalizedParts = paths.Select(x => fileStore.NormalizePath(x)).Where(x => !string.IsNullOrEmpty(x)).ToArray(); var combined = string.Join("/", normalizedParts); diff --git a/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AmazonWebServiceResponseExtensions.cs b/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AmazonWebServiceResponseExtensions.cs index 03046332eef..90cfe52ba80 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AmazonWebServiceResponseExtensions.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AmazonWebServiceResponseExtensions.cs @@ -5,9 +5,7 @@ namespace OrchardCore.FileStorage.AmazonS3; public static class AmazonWebServiceResponseExtensions { - public static bool IsSuccessful(this AmazonWebServiceResponse response) => - response.HttpStatusCode == HttpStatusCode.OK; + public static bool IsSuccessful(this AmazonWebServiceResponse response) => response.HttpStatusCode == HttpStatusCode.OK; - public static bool IsDeleteSuccessful(this AmazonWebServiceResponse response) => - response.HttpStatusCode == HttpStatusCode.NoContent; + public static bool IsDeleteSuccessful(this AmazonWebServiceResponse response) => response.HttpStatusCode == HttpStatusCode.NoContent; } diff --git a/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs b/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs index e288f6c1176..9f436ce611a 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs @@ -39,11 +39,9 @@ public async Task GetFileInfoAsync(string path) { try { - var objectMetadata = await _amazonS3Client.GetObjectMetadataAsync(new GetObjectMetadataRequest - { - BucketName = _options.BucketName, - Key = this.Combine(_basePrefix, path) - }); + var objectMetadata = await _amazonS3Client.GetObjectMetadataAsync( + new GetObjectMetadataRequest { BucketName = _options.BucketName, Key = this.Combine(_basePrefix, path) } + ); return new AwsFile(path, objectMetadata.ContentLength, objectMetadata.LastModified); } @@ -61,27 +59,30 @@ public async Task GetDirectoryInfoAsync(string path) return new AwsDirectory(path, _clock.UtcNow); } - var awsDirectory = await _amazonS3Client.ListObjectsV2Async(new ListObjectsV2Request - { - BucketName = _options.BucketName, - Prefix = NormalizePrefix(this.Combine(_basePrefix, path)), - MaxKeys = 1, - FetchOwner = false - }); + var awsDirectory = await _amazonS3Client.ListObjectsV2Async( + new ListObjectsV2Request + { + BucketName = _options.BucketName, + Prefix = NormalizePrefix(this.Combine(_basePrefix, path)), + MaxKeys = 1, + FetchOwner = false + } + ); return awsDirectory.S3Objects.Count > 0 ? new AwsDirectory(path, _clock.UtcNow) : null; } - public async IAsyncEnumerable GetDirectoryContentAsync(string path = null, - bool includeSubDirectories = false) + public async IAsyncEnumerable GetDirectoryContentAsync(string path = null, bool includeSubDirectories = false) { - var listObjectsResponse = await _amazonS3Client.ListObjectsV2Async(new ListObjectsV2Request - { - BucketName = _options.BucketName, - Delimiter = "/", - Prefix = NormalizePrefix(this.Combine(_basePrefix, path)), - FetchOwner = false, - }); + var listObjectsResponse = await _amazonS3Client.ListObjectsV2Async( + new ListObjectsV2Request + { + BucketName = _options.BucketName, + Delimiter = "/", + Prefix = NormalizePrefix(this.Combine(_basePrefix, path)), + FetchOwner = false, + } + ); foreach (var file in listObjectsResponse.S3Objects) { @@ -115,11 +116,7 @@ public async Task TryCreateDirectoryAsync(string path) { try { - var response = await _amazonS3Client.PutObjectAsync(new PutObjectRequest - { - BucketName = _options.BucketName, - Key = NormalizePrefix(this.Combine(_basePrefix, path)) - }); + var response = await _amazonS3Client.PutObjectAsync(new PutObjectRequest { BucketName = _options.BucketName, Key = NormalizePrefix(this.Combine(_basePrefix, path)) }); return response.IsSuccessful(); } @@ -133,11 +130,7 @@ public async Task TryDeleteFileAsync(string path) { try { - var response = await _amazonS3Client.DeleteObjectAsync(new DeleteObjectRequest - { - BucketName = _options.BucketName, - Key = this.Combine(_basePrefix, path) - }); + var response = await _amazonS3Client.DeleteObjectAsync(new DeleteObjectRequest { BucketName = _options.BucketName, Key = this.Combine(_basePrefix, path) }); return response.IsDeleteSuccessful(); } @@ -154,19 +147,16 @@ public async Task TryDeleteDirectoryAsync(string path) throw new FileStoreException("Cannot delete root directory."); } - var listObjectsResponse = await _amazonS3Client.ListObjectsV2Async(new ListObjectsV2Request - { - BucketName = _options.BucketName, - Prefix = NormalizePrefix(this.Combine(_basePrefix, path)) - }); + var listObjectsResponse = await _amazonS3Client.ListObjectsV2Async( + new ListObjectsV2Request { BucketName = _options.BucketName, Prefix = NormalizePrefix(this.Combine(_basePrefix, path)) } + ); if (listObjectsResponse.S3Objects.Count > 0) { var deleteObjectsRequest = new DeleteObjectsRequest { BucketName = _options.BucketName, - Objects = listObjectsResponse.S3Objects - .Select(metadata => new KeyVersion { Key = metadata.Key }).ToList() + Objects = listObjectsResponse.S3Objects.Select(metadata => new KeyVersion { Key = metadata.Key }).ToList() }; var response = await _amazonS3Client.DeleteObjectsAsync(deleteObjectsRequest); @@ -191,11 +181,7 @@ public async Task CopyFileAsync(string srcPath, string dstPath) try { - await _amazonS3Client.GetObjectMetadataAsync(new GetObjectMetadataRequest - { - BucketName = _options.BucketName, - Key = this.Combine(_basePrefix, srcPath) - }); + await _amazonS3Client.GetObjectMetadataAsync(new GetObjectMetadataRequest { BucketName = _options.BucketName, Key = this.Combine(_basePrefix, srcPath) }); } catch (AmazonS3Exception) { @@ -204,30 +190,27 @@ await _amazonS3Client.GetObjectMetadataAsync(new GetObjectMetadataRequest try { - var listObjects = await _amazonS3Client.ListObjectsV2Async(new ListObjectsV2Request - { - BucketName = _options.BucketName, - Prefix = this.Combine(_basePrefix, dstPath) - }); + var listObjects = await _amazonS3Client.ListObjectsV2Async(new ListObjectsV2Request { BucketName = _options.BucketName, Prefix = this.Combine(_basePrefix, dstPath) }); if (listObjects.S3Objects.Count > 0) { throw new FileStoreException($"Cannot copy file '{srcPath}' because a file already exists in the new path '{dstPath}'."); } - var copyObjectResponse = await _amazonS3Client.CopyObjectAsync(new CopyObjectRequest - { - SourceBucket = _options.BucketName, - SourceKey = this.Combine(_basePrefix, srcPath), - DestinationBucket = _options.BucketName, - DestinationKey = this.Combine(_basePrefix, dstPath) - }); + var copyObjectResponse = await _amazonS3Client.CopyObjectAsync( + new CopyObjectRequest + { + SourceBucket = _options.BucketName, + SourceKey = this.Combine(_basePrefix, srcPath), + DestinationBucket = _options.BucketName, + DestinationKey = this.Combine(_basePrefix, dstPath) + } + ); if (!copyObjectResponse.IsSuccessful()) { throw new FileStoreException($"Error while copying file '{srcPath}'"); } - } catch (AmazonS3Exception) { @@ -259,11 +242,7 @@ public async Task CreateFileFromStreamAsync(string path, Stream inputStr { if (!overwrite) { - var listObjects = await _amazonS3Client.ListObjectsV2Async(new ListObjectsV2Request - { - BucketName = _options.BucketName, - Prefix = this.Combine(_basePrefix, path) - }); + var listObjects = await _amazonS3Client.ListObjectsV2Async(new ListObjectsV2Request { BucketName = _options.BucketName, Prefix = this.Combine(_basePrefix, path) }); if (listObjects.S3Objects.Count > 0) { @@ -271,12 +250,14 @@ public async Task CreateFileFromStreamAsync(string path, Stream inputStr } } - var response = await _amazonS3Client.PutObjectAsync(new PutObjectRequest - { - BucketName = _options.BucketName, - Key = this.Combine(_basePrefix, path), - InputStream = inputStream - }); + var response = await _amazonS3Client.PutObjectAsync( + new PutObjectRequest + { + BucketName = _options.BucketName, + Key = this.Combine(_basePrefix, path), + InputStream = inputStream + } + ); if (!response.IsSuccessful()) { diff --git a/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFileStore.cs b/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFileStore.cs index 388fd6e86bd..1e899cb2ecf 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFileStore.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFileStore.cs @@ -182,10 +182,7 @@ private async IAsyncEnumerable GetDirectoryContentFlatAsync(str } // Do not include root folder, or current path, or multiple folders in folder listing. - if (!string.IsNullOrEmpty(directory) && - !directories.Contains(directory) && - (string.IsNullOrEmpty(path) || - !directory.EndsWith(path))) + if (!string.IsNullOrEmpty(directory) && !directories.Contains(directory) && (string.IsNullOrEmpty(path) || !directory.EndsWith(path))) { directories.Add(directory); yield return new BlobDirectory(directory, _clock.UtcNow); @@ -332,7 +329,9 @@ public async Task CopyFileAsync(string srcPath, string dstPath) if (properties.Value.CopyStatus != CopyStatus.Success) { - throw new FileStoreException($"Error while copying file '{srcPath}'; copy operation failed with status {properties.Value.CopyStatus} and description {properties.Value.CopyStatusDescription}."); + throw new FileStoreException( + $"Error while copying file '{srcPath}'; copy operation failed with status {properties.Value.CopyStatus} and description {properties.Value.CopyStatusDescription}." + ); } } catch (FileStoreException) @@ -388,10 +387,7 @@ public async Task CreateFileFromStreamAsync(string path, Stream inputStr _contentTypeProvider.TryGetContentType(path, out var contentType); - var headers = new BlobHttpHeaders - { - ContentType = contentType ?? "application/octet-stream" - }; + var headers = new BlobHttpHeaders { ContentType = contentType ?? "application/octet-stream" }; await blob.UploadAsync(inputStream, headers); diff --git a/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStore.cs b/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStore.cs index f98b3f784be..bbdb05a992d 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStore.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStore.cs @@ -80,7 +80,8 @@ public IAsyncEnumerable GetDirectoryContentAsync(string path = var fileRelativePath = f[_fileSystemPath.Length..]; var filePath = this.NormalizePath(fileRelativePath); return new FileSystemStoreEntry(filePath, fileSystemInfo); - })); + }) + ); // Add files. results.AddRange( @@ -92,7 +93,8 @@ public IAsyncEnumerable GetDirectoryContentAsync(string path = var fileRelativePath = f[_fileSystemPath.Length..]; var filePath = this.NormalizePath(fileRelativePath); return new FileSystemStoreEntry(filePath, fileSystemInfo); - })); + }) + ); return results.ToAsyncEnumerable(); } diff --git a/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildFieldIndexContext.cs b/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildFieldIndexContext.cs index 3bb122fa77a..e2d50134be9 100644 --- a/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildFieldIndexContext.cs +++ b/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildFieldIndexContext.cs @@ -13,7 +13,8 @@ public BuildFieldIndexContext( ContentPart contentPart, ContentTypePartDefinition typePartDefinition, ContentPartFieldDefinition partFieldDefinition, - IContentIndexSettings settings) + IContentIndexSettings settings + ) : base(documentIndex, contentItem, keys, typePartDefinition, settings) { ContentPartFieldDefinition = partFieldDefinition; diff --git a/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildIndexContext.cs b/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildIndexContext.cs index 0260768e9d7..c96d2242487 100644 --- a/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildIndexContext.cs +++ b/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildIndexContext.cs @@ -5,12 +5,7 @@ namespace OrchardCore.Indexing { public class BuildIndexContext { - public BuildIndexContext( - DocumentIndex documentIndex, - ContentItem contentItem, - IList keys, - IContentIndexSettings settings - ) + public BuildIndexContext(DocumentIndex documentIndex, ContentItem contentItem, IList keys, IContentIndexSettings settings) { ContentItem = contentItem; DocumentIndex = documentIndex; diff --git a/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildPartIndexContext.cs b/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildPartIndexContext.cs index 6b4a482f30a..cfef5a197b3 100644 --- a/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildPartIndexContext.cs +++ b/src/OrchardCore/OrchardCore.Indexing.Abstractions/BuildPartIndexContext.cs @@ -11,7 +11,8 @@ public BuildPartIndexContext( ContentItem contentItem, IList keys, ContentTypePartDefinition typePartDefinition, - IContentIndexSettings settings) + IContentIndexSettings settings + ) : base(documentIndex, contentItem, keys, settings) { ContentTypePartDefinition = typePartDefinition; diff --git a/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentFieldIndexHandler.cs b/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentFieldIndexHandler.cs index 37b7d638d06..0a4046436b1 100644 --- a/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentFieldIndexHandler.cs +++ b/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentFieldIndexHandler.cs @@ -9,12 +9,18 @@ namespace OrchardCore.Indexing /// An implementation of is able to take part in the rendering of /// a instance. /// - public abstract class ContentFieldIndexHandler : IContentFieldIndexHandler where TField : ContentField + public abstract class ContentFieldIndexHandler : IContentFieldIndexHandler + where TField : ContentField { - Task IContentFieldIndexHandler.BuildIndexAsync(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, ContentPartFieldDefinition partFieldDefinition, BuildIndexContext context, IContentIndexSettings settings) + Task IContentFieldIndexHandler.BuildIndexAsync( + ContentPart contentPart, + ContentTypePartDefinition typePartDefinition, + ContentPartFieldDefinition partFieldDefinition, + BuildIndexContext context, + IContentIndexSettings settings + ) { - if (!string.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && - !string.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) + if (!string.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && !string.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) { return Task.CompletedTask; } @@ -33,7 +39,15 @@ Task IContentFieldIndexHandler.BuildIndexAsync(ContentPart contentPart, ContentT keys.Add($"{typePartDefinition.Name}.{partFieldDefinition.Name}"); } - var buildFieldIndexContext = new BuildFieldIndexContext(context.DocumentIndex, context.ContentItem, keys, contentPart, typePartDefinition, partFieldDefinition, settings); + var buildFieldIndexContext = new BuildFieldIndexContext( + context.DocumentIndex, + context.ContentItem, + keys, + contentPart, + typePartDefinition, + partFieldDefinition, + settings + ); return BuildIndexAsync(field, buildFieldIndexContext); } diff --git a/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentIndexSettings.cs b/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentIndexSettings.cs index f39df0f9fcf..0ef3fcf8665 100644 --- a/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentIndexSettings.cs +++ b/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentIndexSettings.cs @@ -42,4 +42,3 @@ public DocumentIndexOptions ToOptions() } } } - diff --git a/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentPartIndexHandler.cs b/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentPartIndexHandler.cs index 975f5426414..2a0f455f9a7 100644 --- a/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentPartIndexHandler.cs +++ b/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentPartIndexHandler.cs @@ -9,9 +9,15 @@ namespace OrchardCore.Indexing /// An implementation of is able to take part in the rendering of /// a instance. /// - public abstract class ContentPartIndexHandler : IContentPartIndexHandler where TPart : ContentPart + public abstract class ContentPartIndexHandler : IContentPartIndexHandler + where TPart : ContentPart { - Task IContentPartIndexHandler.BuildIndexAsync(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, BuildIndexContext context, IContentIndexSettings settings) + Task IContentPartIndexHandler.BuildIndexAsync( + ContentPart contentPart, + ContentTypePartDefinition typePartDefinition, + BuildIndexContext context, + IContentIndexSettings settings + ) { var part = contentPart as TPart; @@ -20,10 +26,7 @@ Task IContentPartIndexHandler.BuildIndexAsync(ContentPart contentPart, ContentTy return Task.CompletedTask; } - var keys = new List - { - typePartDefinition.Name, - }; + var keys = new List { typePartDefinition.Name, }; foreach (var key in context.Keys) { diff --git a/src/OrchardCore/OrchardCore.Indexing.Abstractions/DocumentIndex.cs b/src/OrchardCore/OrchardCore.Indexing.Abstractions/DocumentIndex.cs index bc759112f0f..2d248382049 100644 --- a/src/OrchardCore/OrchardCore.Indexing.Abstractions/DocumentIndex.cs +++ b/src/OrchardCore/OrchardCore.Indexing.Abstractions/DocumentIndex.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Microsoft.AspNetCore.Html; namespace OrchardCore.Indexing; diff --git a/src/OrchardCore/OrchardCore.Indexing.Abstractions/IContentFieldIndexHandler.cs b/src/OrchardCore/OrchardCore.Indexing.Abstractions/IContentFieldIndexHandler.cs index f3a3af6db5a..c82960fcaa0 100644 --- a/src/OrchardCore/OrchardCore.Indexing.Abstractions/IContentFieldIndexHandler.cs +++ b/src/OrchardCore/OrchardCore.Indexing.Abstractions/IContentFieldIndexHandler.cs @@ -10,6 +10,12 @@ namespace OrchardCore.Indexing /// public interface IContentFieldIndexHandler { - Task BuildIndexAsync(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, ContentPartFieldDefinition partFieldDefinition, BuildIndexContext context, IContentIndexSettings settings); + Task BuildIndexAsync( + ContentPart contentPart, + ContentTypePartDefinition typePartDefinition, + ContentPartFieldDefinition partFieldDefinition, + BuildIndexContext context, + IContentIndexSettings settings + ); } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Cache/ICacheScopeManager.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Cache/ICacheScopeManager.cs index 6d3919865b9..546ef006778 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Cache/ICacheScopeManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Cache/ICacheScopeManager.cs @@ -6,11 +6,13 @@ public interface ICacheScopeManager { void EnterScope(CacheContext context); void ExitScope(); + /// /// Adds the given dependencies to the current innermost cache context. /// /// The dependencies to add. void AddDependencies(params string[] dependencies); + /// /// Adds the given contexts to the current innermost cache context. /// diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/DefaultCommandHandler.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/DefaultCommandHandler.cs index a61af845b51..da6d312c287 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/DefaultCommandHandler.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/DefaultCommandHandler.cs @@ -39,8 +39,8 @@ private void SetSwitchValues(CommandContext context) private void SetSwitchValue(KeyValuePair commandSwitch) { // Find the property. - var propertyInfo = GetType() - .GetProperty(commandSwitch.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase) + var propertyInfo = + GetType().GetProperty(commandSwitch.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase) ?? throw new InvalidOperationException(S["Switch \"{0}\" was not found", commandSwitch.Key]); if (propertyInfo.GetCustomAttributes(typeof(OrchardSwitchAttribute), false).Length == 0) @@ -52,15 +52,16 @@ private void SetSwitchValue(KeyValuePair commandSwitch) try { var value = ConvertToType(propertyInfo.PropertyType, commandSwitch.Value); - propertyInfo.SetValue(this, value, null /*index*/); + propertyInfo.SetValue( + this, + value, + null /*index*/ + ); } catch (Exception ex) when (!ex.IsFatal()) { // TODO: (ngm) fix this message. - var message = S["Error converting value \"{0}\" to \"{1}\" for switch \"{2}\"", - commandSwitch.Value, - propertyInfo.PropertyType.FullName, - commandSwitch.Key]; + var message = S["Error converting value \"{0}\" to \"{1}\" for switch \"{2}\"", commandSwitch.Value, propertyInfo.PropertyType.FullName, commandSwitch.Key]; throw new InvalidOperationException(message, ex); } @@ -71,7 +72,8 @@ private async Task InvokeAsync(CommandContext context) CheckMethodForSwitches(context.CommandDescriptor.MethodInfo, context.Switches); var arguments = (context.Arguments ?? []).ToArray(); - var invokeParameters = GetInvokeParametersForMethod(context.CommandDescriptor.MethodInfo, arguments) + var invokeParameters = + GetInvokeParametersForMethod(context.CommandDescriptor.MethodInfo, arguments) ?? throw new InvalidOperationException(S["Command arguments \"{0}\" don't match command definition", string.Join(" ", arguments)]); Context = context; @@ -119,8 +121,10 @@ private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, ILis var requiredMethodParameters = methodParameters.Where(x => !x.HasDefaultValue).ToArray(); - if (!methodHasParams && args.Count < requiredMethodParameters.Length) return null; - if (methodHasParams && (methodParameters.Length - args.Count >= 2)) return null; + if (!methodHasParams && args.Count < requiredMethodParameters.Length) + return null; + if (methodHasParams && (methodParameters.Length - args.Count >= 2)) + return null; for (var i = 0; i < methodParameters.Length; i++) { @@ -133,7 +137,8 @@ private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, ILis if (i < arguments.Count) { var val = ConvertToType(methodParameters[i].ParameterType, arguments[i]); - if (val == null) return null; + if (val == null) + return null; invokeParameters.Add(val); } @@ -143,10 +148,7 @@ private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, ILis } } - var lastParameterIsParams = methodParameters - .LastOrDefault() - ?.GetCustomAttributes(typeof(ParamArrayAttribute), false) - ?.Length > 0; + var lastParameterIsParams = methodParameters.LastOrDefault()?.GetCustomAttributes(typeof(ParamArrayAttribute), false)?.Length > 0; if (methodHasParams && (methodParameters.Length - args.Count == 1) && !lastParameterIsParams) { diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/OrchardSwitchAttribute.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/OrchardSwitchAttribute.cs index 10da8cb83eb..f07cf72f6d0 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/OrchardSwitchAttribute.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/OrchardSwitchAttribute.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Environment.Commands { [AttributeUsage(AttributeTargets.Property)] - public class OrchardSwitchAttribute : Attribute - { - } + public class OrchardSwitchAttribute : Attribute { } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/OrchardSwitchesAttribute.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/OrchardSwitchesAttribute.cs index fd7d3c3a65d..1c203016895 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/OrchardSwitchesAttribute.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/OrchardSwitchesAttribute.cs @@ -16,10 +16,7 @@ public OrchardSwitchesAttribute(string switches) public IEnumerable Switches { - get - { - return (_switches ?? "").Trim().Split(',').Select(s => s.Trim()); - } + get { return (_switches ?? "").Trim().Split(',').Select(s => s.Trim()); } } } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/Parameters/ICommandParser.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/Parameters/ICommandParser.cs index 533caaf7aae..3ac9ec32a81 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/Parameters/ICommandParser.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/Parameters/ICommandParser.cs @@ -31,10 +31,22 @@ public State(string commandLine) _arguments = []; } - public StringBuilder StringBuilder { get { return _stringBuilder; } } - public bool EOF { get { return _index >= _commandLine.Length; } } - public char Current { get { return _commandLine[_index]; } } - public IEnumerable Arguments { get { return _arguments; } } + public StringBuilder StringBuilder + { + get { return _stringBuilder; } + } + public bool EOF + { + get { return _index >= _commandLine.Length; } + } + public char Current + { + get { return _commandLine[_index]; } + } + public IEnumerable Arguments + { + get { return _arguments; } + } public void AddArgument() { diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntity.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntity.cs index fe5463183e8..a157128f72c 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntity.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntity.cs @@ -6,7 +6,5 @@ namespace OrchardCore.Documents /// /// An being an . /// - public interface IDocumentEntity : IDocument, IEntity - { - } + public interface IDocumentEntity : IDocument, IEntity { } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntityManager.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntityManager.cs index 6b7bea65eec..b67b23c7ac4 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntityManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntityManager.cs @@ -5,17 +5,20 @@ namespace OrchardCore.Documents /// /// A generic service to keep in sync any single between a document store and a shared cache. /// - public interface IDocumentEntityManager where TDocumentEntity : class, IDocumentEntity, new() + public interface IDocumentEntityManager + where TDocumentEntity : class, IDocumentEntity, new() { /// /// Gets a persistent property of a given type. /// - Task GetAsync(string name) where T : new(); + Task GetAsync(string name) + where T : new(); /// /// Sets a persistent property once the ambient session is committed. /// - Task SetAsync(string name, T value) where T : new(); + Task SetAsync(string name, T value) + where T : new(); /// /// Removes a persistent property once the ambient session is committed. diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntityManagerOfT.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntityManagerOfT.cs index 367fdf61b34..b8123932840 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntityManagerOfT.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentEntityManagerOfT.cs @@ -6,7 +6,6 @@ namespace OrchardCore.Documents /// An using a given type of . /// public interface IDocumentEntityManager : IDocumentEntityManager - where TDocumentStore : IDocumentStore where TDocumentEntity : class, IDocumentEntity, new() - { - } + where TDocumentStore : IDocumentStore + where TDocumentEntity : class, IDocumentEntity, new() { } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentManager.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentManager.cs index 5e725f8f6a6..3c9ebddfe05 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentManager.cs @@ -7,7 +7,8 @@ namespace OrchardCore.Documents /// /// A generic service to keep in sync any single between a document store and a shared cache. /// - public interface IDocumentManager where TDocument : class, IDocument, new() + public interface IDocumentManager + where TDocument : class, IDocument, new() { /// /// Loads a single document from the store (or create a new one) for updating and that should not be cached. diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentManagerOfT.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentManagerOfT.cs index 28ca30faf00..7bc1c7a1ce8 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentManagerOfT.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentManagerOfT.cs @@ -6,7 +6,6 @@ namespace OrchardCore.Documents /// An using a given type of . /// public interface IDocumentManager : IDocumentManager - where TDocumentStore : IDocumentStore where TDocument : class, IDocument, new() - { - } + where TDocumentStore : IDocumentStore + where TDocument : class, IDocument, new() { } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentSerializer.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentSerializer.cs index 5972125fc37..861c5f21171 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentSerializer.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IDocumentSerializer.cs @@ -11,11 +11,13 @@ public interface IDocumentSerializer /// /// Serializes an into a sequence of bytes. /// - Task SerializeAsync(TDocument document, int compressThreshold = int.MaxValue) where TDocument : class, IDocument, new(); + Task SerializeAsync(TDocument document, int compressThreshold = int.MaxValue) + where TDocument : class, IDocument, new(); /// /// Deserializes an from a sequence of bytes. /// - Task DeserializeAsync(byte[] data) where TDocument : class, IDocument, new(); + Task DeserializeAsync(byte[] data) + where TDocument : class, IDocument, new(); } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IVolatileDocumentEntityManager.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IVolatileDocumentEntityManager.cs index 44b47fe6117..a77253d7ec8 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IVolatileDocumentEntityManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IVolatileDocumentEntityManager.cs @@ -3,7 +3,6 @@ namespace OrchardCore.Documents /// /// An using a shared cache but without any persistent storage. /// - public interface IVolatileDocumentEntityManager : IDocumentEntityManager where TDocumentEntity : class, IDocumentEntity, new() - { - } + public interface IVolatileDocumentEntityManager : IDocumentEntityManager + where TDocumentEntity : class, IDocumentEntity, new() { } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IVolatileDocumentManager.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IVolatileDocumentManager.cs index 7f1f7e072f4..c2dc4a20a11 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IVolatileDocumentManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Documents/IVolatileDocumentManager.cs @@ -7,7 +7,8 @@ namespace OrchardCore.Documents /// /// An using a shared cache but without any persistent storage. /// - public interface IVolatileDocumentManager : IDocumentManager where TDocument : class, IDocument, new() + public interface IVolatileDocumentManager : IDocumentManager + where TDocument : class, IDocument, new() { /// /// Executes the provided delegate and updates the cache, the whole being done atomically and after the session is committed, diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Entities/EntityExtensions.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Entities/EntityExtensions.cs index 358c4fa54fc..b4bdf29110f 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Entities/EntityExtensions.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Entities/EntityExtensions.cs @@ -12,7 +12,8 @@ public static class EntityExtensions /// The . /// The type of the property to extract. /// A new instance of the requested type if the property was not found. - public static T As(this IEntity entity) where T : new() + public static T As(this IEntity entity) + where T : new() { var typeName = typeof(T).Name; return entity.As(typeName); @@ -25,7 +26,8 @@ public static class EntityExtensions /// The . /// The name of the property to extract. /// A new instance of the requested type if the property was not found. - public static T As(this IEntity entity, string name) where T : new() + public static T As(this IEntity entity, string name) + where T : new() { JsonNode value; if (entity.Properties.TryGetPropertyValue(name, out value)) @@ -54,13 +56,13 @@ public static bool Has(this IEntity entity) /// The . /// The name of the property to check. /// True if the property was found, otherwise false. - public static bool Has(this IEntity entity, string name) - => entity.Properties[name] != null; + public static bool Has(this IEntity entity, string name) => entity.Properties[name] != null; - public static IEntity Put(this IEntity entity, T aspect) where T : new() - => entity.Put(typeof(T).Name, aspect); + public static IEntity Put(this IEntity entity, T aspect) + where T : new() => entity.Put(typeof(T).Name, aspect); - public static bool TryGet(this IEntity entity, out T aspect) where T : new() + public static bool TryGet(this IEntity entity, out T aspect) + where T : new() { if (entity.Properties.TryGetPropertyValue(typeof(T).Name, out var value)) { @@ -87,7 +89,8 @@ public static IEntity Put(this IEntity entity, string name, object property) /// The name of the aspect. /// An action to apply on the aspect. /// The current instance. - public static IEntity Alter(this IEntity entity, string name, Action action) where TAspect : new() + public static IEntity Alter(this IEntity entity, string name, Action action) + where TAspect : new() { JsonNode value; TAspect obj; diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Files/PathExtensions.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Files/PathExtensions.cs index 5c197a9352c..1972605969a 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Files/PathExtensions.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Files/PathExtensions.cs @@ -77,9 +77,7 @@ public static string ResolvePath(string path) { // Determine if we need to do any path resolution. // We need to resolve paths with multiple path separators (e.g "//" or "\\") or, directory traversals e.g. ("../" or "./"). - if (segment.Length == 0 || - segment.Equals(ParentDirectoryToken) || - segment.Equals(CurrentDirectoryToken)) + if (segment.Length == 0 || segment.Equals(ParentDirectoryToken) || segment.Equals(CurrentDirectoryToken)) { requiresResolution = true; break; diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Scripting/IScriptingScope.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Scripting/IScriptingScope.cs index 427c66946f1..1e1ae3c9eac 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Scripting/IScriptingScope.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Scripting/IScriptingScope.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Scripting { - public interface IScriptingScope - { - } + public interface IScriptingScope { } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Permissions/Permission.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Permissions/Permission.cs index cf059734e68..9d73abb3c8c 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Permissions/Permission.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Permissions/Permission.cs @@ -15,13 +15,15 @@ public Permission(string name) Name = name; } - public Permission(string name, string description, bool isSecurityCritical = false) : this(name) + public Permission(string name, string description, bool isSecurityCritical = false) + : this(name) { Description = description; IsSecurityCritical = isSecurityCritical; } - public Permission(string name, string description, IEnumerable impliedBy, bool isSecurityCritical = false) : this(name, description, isSecurityCritical) + public Permission(string name, string description, IEnumerable impliedBy, bool isSecurityCritical = false) + : this(name, description, isSecurityCritical) { ImpliedBy = impliedBy; } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Services/RoleHelper.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Services/RoleHelper.cs index ca17a1564d8..714710dd38d 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Services/RoleHelper.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Services/RoleHelper.cs @@ -5,10 +5,6 @@ namespace OrchardCore.Security.Services { public class RoleHelper { - public static readonly HashSet SystemRoleNames = new(StringComparer.OrdinalIgnoreCase) - { - "Anonymous", - "Authenticated", - }; + public static readonly HashSet SystemRoleNames = new(StringComparer.OrdinalIgnoreCase) { "Anonymous", "Authenticated", }; } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Services/RoleServiceExtensions.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Services/RoleServiceExtensions.cs index 94e36ac220a..39870b56a09 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Services/RoleServiceExtensions.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/Services/RoleServiceExtensions.cs @@ -16,7 +16,12 @@ public static async Task> GetRoleNamesAsync(this IRoleServic return roles.Select(r => r.RoleName); } - public static async Task> GetAccessibleRolesAsync(this IRoleService roleService, IAuthorizationService authorizationService, ClaimsPrincipal user, Permission permission) + public static async Task> GetAccessibleRolesAsync( + this IRoleService roleService, + IAuthorizationService authorizationService, + ClaimsPrincipal user, + Permission permission + ) { var roles = await roleService.GetRolesAsync(); @@ -39,7 +44,12 @@ public static async Task> GetAccessibleRolesAsync(this IRoleS return accessibleRoles; } - public static async Task> GetAccessibleRoleNamesAsync(this IRoleService roleService, IAuthorizationService authorizationService, ClaimsPrincipal user, Permission permission) + public static async Task> GetAccessibleRoleNamesAsync( + this IRoleService roleService, + IAuthorizationService authorizationService, + ClaimsPrincipal user, + Permission permission + ) { var roles = await roleService.GetAccessibleRolesAsync(authorizationService, user, permission); diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Settings/ISite.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Settings/ISite.cs index db89e4fd214..11668fdee00 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Settings/ISite.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Settings/ISite.cs @@ -37,5 +37,6 @@ public interface ISite : IEntity CacheMode CacheMode { get; set; } - T As() where T : new(); + T As() + where T : new(); } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/QueryCacheContextProvider.cs b/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/QueryCacheContextProvider.cs index cbadd36fdd3..137d1f81f59 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/QueryCacheContextProvider.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/QueryCacheContextProvider.cs @@ -23,11 +23,7 @@ public Task PopulateContextEntriesAsync(IEnumerable contexts, List x).ToArray(); - entries.AddRange(allKeys - .Select(x => new CacheContextEntry( - key: x.ToLowerInvariant(), - value: query[x].ToString().ToLowerInvariant()) - )); + entries.AddRange(allKeys.Select(x => new CacheContextEntry(key: x.ToLowerInvariant(), value: query[x].ToString().ToLowerInvariant()))); // If we track any query value, we don't need to look into specific ones. return Task.CompletedTask; @@ -39,10 +35,7 @@ public Task PopulateContextEntriesAsync(IEnumerable contexts, List _tagRemovedEventHandlers; private readonly ILogger _logger; - public DefaultTagCache( - IEnumerable tagRemovedEventHandlers, - IMemoryCache memoryCache, - ILogger logger) + public DefaultTagCache(IEnumerable tagRemovedEventHandlers, IMemoryCache memoryCache, ILogger logger) { // We use the memory cache as the state holder and keep this class transient as it has // dependencies on non-singletons diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Commands/Builtin/HelpCommand.cs b/src/OrchardCore/OrchardCore.Infrastructure/Commands/Builtin/HelpCommand.cs index a6055da50e5..5790ef7787b 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Commands/Builtin/HelpCommand.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Commands/Builtin/HelpCommand.cs @@ -12,8 +12,8 @@ public class HelpCommand : DefaultCommandHandler private readonly IServiceProvider _serviceProvider; private readonly CommandHandlerDescriptorBuilder _builder = new(); - public HelpCommand(IServiceProvider serviceProvider, - IStringLocalizer localizer) : base(localizer) + public HelpCommand(IServiceProvider serviceProvider, IStringLocalizer localizer) + : base(localizer) { _serviceProvider = serviceProvider; } @@ -40,9 +40,7 @@ public async Task AllCommandsAsync() public async Task SingleCommandAsync(string[] commandNameStrings) { var command = string.Join(" ", commandNameStrings); - var descriptors = GetCommandDescriptors() - .Where(t => t.Names.Any(x => x.StartsWith(command, StringComparison.OrdinalIgnoreCase))) - .OrderBy(d => d.Names); + var descriptors = GetCommandDescriptors().Where(t => t.Names.Any(x => x.StartsWith(command, StringComparison.OrdinalIgnoreCase))).OrderBy(d => d.Names); if (!descriptors.Any()) { @@ -57,6 +55,7 @@ public async Task SingleCommandAsync(string[] commandNameStrings) } } } + private IEnumerable GetCommandDescriptors() { var commandhandlers = _serviceProvider.GetServices(); diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Commands/CommandHandlerDescriptorBuilder.cs b/src/OrchardCore/OrchardCore.Infrastructure/Commands/CommandHandlerDescriptorBuilder.cs index 25b90e2707c..a8e3ed6b206 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Commands/CommandHandlerDescriptorBuilder.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Commands/CommandHandlerDescriptorBuilder.cs @@ -16,9 +16,7 @@ public CommandHandlerDescriptor Build(Type type) private static IEnumerable CollectMethods(Type type) { - var methods = type - .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) - .Where(m => !m.IsSpecialName); + var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).Where(m => !m.IsSpecialName); foreach (var methodInfo in methods) { @@ -38,7 +36,10 @@ private static CommandDescriptor BuildMethod(MethodInfo methodInfo) private static string GetCommandHelpText(MethodInfo methodInfo) { - var attributes = methodInfo.GetCustomAttributes(typeof(CommandHelpAttribute), false/*inherit*/); + var attributes = methodInfo.GetCustomAttributes( + typeof(CommandHelpAttribute), + false /*inherit*/ + ); if (attributes != null && attributes.Length > 0) { return attributes.Cast().Single().HelpText; @@ -48,7 +49,10 @@ private static string GetCommandHelpText(MethodInfo methodInfo) private static string[] GetCommandNames(MethodInfo methodInfo) { - var attributes = methodInfo.GetCustomAttributes(typeof(CommandNameAttribute), false/*inherit*/); + var attributes = methodInfo.GetCustomAttributes( + typeof(CommandNameAttribute), + false /*inherit*/ + ); if (attributes != null && attributes.Length > 0) { return attributes.Cast().Single().Commands; diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs b/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs index 130a6b8c303..4a7345f66eb 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs @@ -12,8 +12,7 @@ public class DefaultCommandManager : ICommandManager private readonly CommandHandlerDescriptorBuilder _builder = new(); protected readonly IStringLocalizer S; - public DefaultCommandManager(IEnumerable commandHandlers, - IStringLocalizer localizer) + public DefaultCommandManager(IEnumerable commandHandlers, IStringLocalizer localizer) { _commandHandlers = commandHandlers; @@ -35,11 +34,9 @@ public async Task ExecuteAsync(CommandParameters parameters) var commandList = string.Join(",", GetCommandDescriptors().SelectMany(d => d.Names).ToArray()); if (matches.Count > 0) { - throw new Exception(S["Multiple commands found matching arguments \"{0}\". Commands available: {1}.", - commandMatch, commandList]); + throw new Exception(S["Multiple commands found matching arguments \"{0}\". Commands available: {1}.", commandMatch, commandList]); } - throw new Exception(S["No command found matching arguments \"{0}\". Commands available: {1}.", - commandMatch, commandList]); + throw new Exception(S["No command found matching arguments \"{0}\". Commands available: {1}.", commandMatch, commandList]); } } @@ -52,8 +49,7 @@ private List MatchCommands(CommandParameters parameters) { // Commands are matched with arguments. first argument // is the command others are arguments to the command. - return _commandHandlers.SelectMany(h => - MatchCommands(parameters, parameters.Arguments.Count(), _builder.Build(h.GetType()), h)).ToList(); + return _commandHandlers.SelectMany(h => MatchCommands(parameters, parameters.Arguments.Count(), _builder.Build(h.GetType()), h)).ToList(); } private static IEnumerable MatchCommands(CommandParameters parameters, int argCount, CommandHandlerDescriptor descriptor, ICommandHandler handler) diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Commands/Parameters/CommandParametersParser.cs b/src/OrchardCore/OrchardCore.Infrastructure/Commands/Parameters/CommandParametersParser.cs index d190d8ffeae..0b86a5e0420 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Commands/Parameters/CommandParametersParser.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Commands/Parameters/CommandParametersParser.cs @@ -34,11 +34,7 @@ public CommandParameters Parse(IEnumerable args) } } - return new CommandParameters - { - Arguments = arguments, - Switches = switches - }; + return new CommandParameters { Arguments = arguments, Switches = switches }; } } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DefaultDocumentSerializer.cs b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DefaultDocumentSerializer.cs index 32470e8d71f..d144bc2ed0f 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DefaultDocumentSerializer.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DefaultDocumentSerializer.cs @@ -14,11 +14,10 @@ public class DefaultDocumentSerializer : IDocumentSerializer { public static readonly DefaultDocumentSerializer Instance = new(); - public DefaultDocumentSerializer() - { - } + public DefaultDocumentSerializer() { } - public Task SerializeAsync(TDocument document, int compressThreshold = int.MaxValue) where TDocument : class, IDocument, new() + public Task SerializeAsync(TDocument document, int compressThreshold = int.MaxValue) + where TDocument : class, IDocument, new() { var data = Encoding.UTF8.GetBytes(JConvert.SerializeObject(document)); if (data.Length >= compressThreshold) @@ -29,7 +28,8 @@ public DefaultDocumentSerializer() return Task.FromResult(data); } - public Task DeserializeAsync(byte[] data) where TDocument : class, IDocument, new() + public Task DeserializeAsync(byte[] data) + where TDocument : class, IDocument, new() { if (IsCompressed(data)) { diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentEntityManager.cs b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentEntityManager.cs index 14b7714994b..06faee37fd3 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentEntityManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentEntityManager.cs @@ -8,13 +8,15 @@ namespace OrchardCore.Documents /// /// A generic service to keep in sync any single between an and a multi level cache. /// - public class DocumentEntityManager : IDocumentEntityManager where TDocumentEntity : class, IDocumentEntity, new() + public class DocumentEntityManager : IDocumentEntityManager + where TDocumentEntity : class, IDocumentEntity, new() { private readonly IDocumentManager _documentManager; public DocumentEntityManager(IDocumentManager documentManager) => _documentManager = documentManager; - public async Task GetAsync(string key) where T : new() + public async Task GetAsync(string key) + where T : new() { var document = await _documentManager.GetOrCreateImmutableAsync(); if (document.Properties.TryGetPropertyValue(key, out var value)) @@ -25,7 +27,8 @@ namespace OrchardCore.Documents return new T(); } - public async Task SetAsync(string key, T value) where T : new() + public async Task SetAsync(string key, T value) + where T : new() { var document = await _documentManager.GetOrCreateMutableAsync(); document.Properties[key] = JObject.FromObject(value); diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentEntityManagerOfT.cs b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentEntityManagerOfT.cs index e6f4cc0030a..07defe08b4f 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentEntityManagerOfT.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentEntityManagerOfT.cs @@ -6,10 +6,10 @@ namespace OrchardCore.Documents /// A using a given type of . /// public class DocumentEntityManager : DocumentEntityManager, IDocumentEntityManager - where TDocumentStore : IDocumentStore where TDocumentEntity : class, IDocumentEntity, new() + where TDocumentStore : IDocumentStore + where TDocumentEntity : class, IDocumentEntity, new() { - public DocumentEntityManager(IDocumentManager documentManager) : base(documentManager) - { - } + public DocumentEntityManager(IDocumentManager documentManager) + : base(documentManager) { } } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentManager.cs b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentManager.cs index 239b946eef4..68c0869bab3 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentManager.cs @@ -14,7 +14,8 @@ namespace OrchardCore.Documents /// /// A generic service to keep in sync any single between an and a multi level cache. /// - public class DocumentManager : IDocumentManager where TDocument : class, IDocument, new() + public class DocumentManager : IDocumentManager + where TDocument : class, IDocument, new() { public const string FailoverKey = "OrchardCore_Documents_FailoverKey"; @@ -26,11 +27,7 @@ namespace OrchardCore.Documents protected readonly bool _isDistributed; protected bool _isVolatile; - public DocumentManager( - IDistributedCache distributedCache, - IMemoryCache memoryCache, - IOptionsMonitor options, - ILogger> logger) + public DocumentManager(IDistributedCache distributedCache, IMemoryCache memoryCache, IOptionsMonitor options, ILogger> logger) { _distributedCache = distributedCache; _memoryCache = memoryCache; @@ -84,9 +81,7 @@ public async Task GetOrCreateMutableAsync(Func> facto } else { - document = await GetFromDistributedCacheAsync() - ?? await (factoryAsync?.Invoke() ?? Task.FromResult((TDocument)null)) - ?? new TDocument(); + document = await GetFromDistributedCacheAsync() ?? await (factoryAsync?.Invoke() ?? Task.FromResult((TDocument)null)) ?? new TDocument(); ShellScope.Set(typeof(TDocument), document); } @@ -128,10 +123,7 @@ public async Task GetOrCreateImmutableAsync(Func> fac _logger.LogError(e, "Failed to read the '{DocumentName}' from the distributed cache", typeof(TDocument).Name); failover = true; - _memoryCache.Set(FailoverKey, failover, new MemoryCacheEntryOptions() - { - AbsoluteExpirationRelativeToNow = _options.FailoverRetryLatency - }); + _memoryCache.Set(FailoverKey, failover, new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = _options.FailoverRetryLatency }); } if (document is null) @@ -144,9 +136,7 @@ public async Task GetOrCreateImmutableAsync(Func> fac } else { - document = await (factoryAsync?.Invoke() - ?? Task.FromResult((TDocument)null)) - ?? new TDocument(); + document = await (factoryAsync?.Invoke() ?? Task.FromResult((TDocument)null)) ?? new TDocument(); } if (cacheable) @@ -185,17 +175,20 @@ public async Task UpdateAsync(TDocument document, Func afterUpd if (!_isVolatile) { - await DocumentStore.UpdateAsync(document, async document => - { - // A non volatile document can be invalidated. - await InvalidateInternalAsync(document); - - if (afterUpdateAsync != null) + await DocumentStore.UpdateAsync( + document, + async document => { - await afterUpdateAsync(document); - } - }, - _options.CheckConcurrency.Value); + // A non volatile document can be invalidated. + await InvalidateInternalAsync(document); + + if (afterUpdateAsync != null) + { + await afterUpdateAsync(document); + } + }, + _options.CheckConcurrency.Value + ); return; } @@ -224,17 +217,20 @@ private async Task GetInternalAsync(bool failover = false) if (_isDistributed) { // Cache the id locally for the synchronization latency time. - id = await _memoryCache.GetOrCreateAsync(_options.CacheIdKey, entry => - { - entry.AbsoluteExpirationRelativeToNow = _options.SynchronizationLatency; - - if (failover) + id = await _memoryCache.GetOrCreateAsync( + _options.CacheIdKey, + entry => { - return Task.FromResult(null); - } + entry.AbsoluteExpirationRelativeToNow = _options.SynchronizationLatency; + + if (failover) + { + return Task.FromResult(null); + } - return _distributedCache.GetStringAsync(_options.CacheIdKey); - }); + return _distributedCache.GetStringAsync(_options.CacheIdKey); + } + ); } else { @@ -292,12 +288,16 @@ private async Task GetInternalAsync(bool failover = false) return null; } - _memoryCache.Set(_options.CacheKey, document, new MemoryCacheEntryOptions() - { - AbsoluteExpiration = _options.AbsoluteExpiration, - AbsoluteExpirationRelativeToNow = _options.AbsoluteExpirationRelativeToNow, - SlidingExpiration = _options.SlidingExpiration - }); + _memoryCache.Set( + _options.CacheKey, + document, + new MemoryCacheEntryOptions() + { + AbsoluteExpiration = _options.AbsoluteExpiration, + AbsoluteExpirationRelativeToNow = _options.AbsoluteExpirationRelativeToNow, + SlidingExpiration = _options.SlidingExpiration + } + ); // Remove the id from the one second cache. _memoryCache.Remove(_options.CacheIdKey); @@ -314,20 +314,25 @@ protected async Task SetInternalAsync(TDocument document, bool failover = false) await UpdateDistributedCacheAsync(document); } - _memoryCache.Set(_options.CacheKey, document, new MemoryCacheEntryOptions() - { - AbsoluteExpiration = _options.AbsoluteExpiration, - AbsoluteExpirationRelativeToNow = _options.AbsoluteExpirationRelativeToNow, - SlidingExpiration = _options.SlidingExpiration - }); + _memoryCache.Set( + _options.CacheKey, + document, + new MemoryCacheEntryOptions() + { + AbsoluteExpiration = _options.AbsoluteExpiration, + AbsoluteExpirationRelativeToNow = _options.AbsoluteExpirationRelativeToNow, + SlidingExpiration = _options.SlidingExpiration + } + ); if (failover) { // Cache the id locally so that the memory cache is used during the 'FailoverRetryLatency'. - _memoryCache.Set(_options.CacheIdKey, document.Identifier ?? "NULL", new MemoryCacheEntryOptions() - { - AbsoluteExpirationRelativeToNow = _options.FailoverRetryLatency - }); + _memoryCache.Set( + _options.CacheIdKey, + document.Identifier ?? "NULL", + new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = _options.FailoverRetryLatency } + ); return; } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentManagerOfT.cs b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentManagerOfT.cs index 587872ffacf..0e464d55392 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentManagerOfT.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DocumentManagerOfT.cs @@ -11,13 +11,10 @@ namespace OrchardCore.Documents /// A using a given type of . /// public class DocumentManager : DocumentManager, IDocumentManager - where TDocumentStore : IDocumentStore where TDocument : class, IDocument, new() + where TDocumentStore : IDocumentStore + where TDocument : class, IDocument, new() { - public DocumentManager( - IDistributedCache distributedCache, - IMemoryCache memoryCache, - IOptionsMonitor options, - ILogger> logger) + public DocumentManager(IDistributedCache distributedCache, IMemoryCache memoryCache, IOptionsMonitor options, ILogger> logger) : base(distributedCache, memoryCache, options, logger) { DocumentStoreServiceType = typeof(TDocumentStore); diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Documents/Options/DocumentOptionsSetup.cs b/src/OrchardCore/OrchardCore.Infrastructure/Documents/Options/DocumentOptionsSetup.cs index 99bfad145c3..041414c537d 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Documents/Options/DocumentOptionsSetup.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Documents/Options/DocumentOptionsSetup.cs @@ -21,15 +21,9 @@ public DocumentOptionsSetup(IShellConfiguration shellConfiguration) public void Configure(string name, DocumentOptions options) { - var sharedConfig = _shellConfiguration - .GetSection("OrchardCore_Documents") - .Get() - ?? new DocumentSharedOptions(); + var sharedConfig = _shellConfiguration.GetSection("OrchardCore_Documents").Get() ?? new DocumentSharedOptions(); - var namedConfig = _shellConfiguration - .GetSection(name) - .Get() - ?? new DocumentNamedOptions(); + var namedConfig = _shellConfiguration.GetSection(name).Get() ?? new DocumentNamedOptions(); // Only from the named config or default. options.CacheKey = namedConfig.CacheKey ?? name; @@ -42,9 +36,7 @@ public void Configure(string name, DocumentOptions options) options.CheckConcurrency = namedConfig.CheckConcurrency ?? sharedConfig.CheckConcurrency ?? true; options.CheckConsistency = namedConfig.CheckConsistency ?? sharedConfig.CheckConsistency ?? true; - options.SynchronizationLatency = namedConfig.SynchronizationLatency - ?? sharedConfig.SynchronizationLatency - ?? TimeSpan.FromSeconds(1); + options.SynchronizationLatency = namedConfig.SynchronizationLatency ?? sharedConfig.SynchronizationLatency ?? TimeSpan.FromSeconds(1); options.Serializer = DefaultDocumentSerializer.Instance; diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Documents/VolatileDocumentEntityManager.cs b/src/OrchardCore/OrchardCore.Infrastructure/Documents/VolatileDocumentEntityManager.cs index 352ebf227b7..21c09ba9e51 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Documents/VolatileDocumentEntityManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Documents/VolatileDocumentEntityManager.cs @@ -3,10 +3,10 @@ namespace OrchardCore.Documents /// /// A using a multi level cache but without any persistent storage. /// - public class VolatileDocumentEntityManager : DocumentEntityManager, IVolatileDocumentEntityManager where TDocumentEntity : class, IDocumentEntity, new() + public class VolatileDocumentEntityManager : DocumentEntityManager, IVolatileDocumentEntityManager + where TDocumentEntity : class, IDocumentEntity, new() { - public VolatileDocumentEntityManager(IVolatileDocumentManager documentManager) : base(documentManager) - { - } + public VolatileDocumentEntityManager(IVolatileDocumentManager documentManager) + : base(documentManager) { } } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Documents/VolatileDocumentManager.cs b/src/OrchardCore/OrchardCore.Infrastructure/Documents/VolatileDocumentManager.cs index edb20522515..b5e50bb99c6 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Documents/VolatileDocumentManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Documents/VolatileDocumentManager.cs @@ -29,7 +29,8 @@ public VolatileDocumentManager( IDistributedLock distributedLock, IMemoryCache memoryCache, IOptionsMonitor options, - ILogger> logger) + ILogger> logger + ) : base(distributedCache, memoryCache, options, logger) { _isVolatile = true; @@ -77,7 +78,8 @@ public async Task UpdateAtomicAsync(Func> updateAsync, Func - public bool Validate(string emailAddress) - => emailAddress?.IndexOf('@') > -1 && MailboxAddress.TryParse(emailAddress, out _); + public bool Validate(string emailAddress) => emailAddress?.IndexOf('@') > -1 && MailboxAddress.TryParse(emailAddress, out _); } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Entities/Scripting/IdGeneratorMethod.cs b/src/OrchardCore/OrchardCore.Infrastructure/Entities/Scripting/IdGeneratorMethod.cs index 1c0c694d994..998f9f786c9 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Entities/Scripting/IdGeneratorMethod.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Entities/Scripting/IdGeneratorMethod.cs @@ -6,15 +6,17 @@ namespace OrchardCore.Entities.Scripting { public class IdGeneratorMethod : IGlobalMethodProvider { - private static readonly GlobalMethod _uuid = new() - { - Name = "uuid", - Method = serviceProvider => () => - { - var idGenerator = serviceProvider.GetRequiredService(); - return idGenerator.GenerateUniqueId(); - }, - }; + private static readonly GlobalMethod _uuid = + new() + { + Name = "uuid", + Method = serviceProvider => + () => + { + var idGenerator = serviceProvider.GetRequiredService(); + return idGenerator.GenerateUniqueId(); + }, + }; public IEnumerable GetMethods() { diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Html/OrchardCoreBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Infrastructure/Html/OrchardCoreBuilderExtensions.cs index 35ef302e2c5..1029e0e33ed 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Html/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Html/OrchardCoreBuilderExtensions.cs @@ -14,11 +14,13 @@ public static OrchardCoreBuilder AddHtmlSanitizer(this OrchardCoreBuilder builde { services.AddOptions(); - services.ConfigureHtmlSanitizer((sanitizer) => - { - sanitizer.AllowedAttributes.Add("class"); - sanitizer.AllowedTags.Remove("form"); - }); + services.ConfigureHtmlSanitizer( + (sanitizer) => + { + sanitizer.AllowedAttributes.Add("class"); + sanitizer.AllowedTags.Remove("form"); + } + ); services.AddSingleton(); }); diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Scripting/CommonGeneratorMethods.cs b/src/OrchardCore/OrchardCore.Infrastructure/Scripting/CommonGeneratorMethods.cs index fcdc082b6f6..6eebe174247 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Scripting/CommonGeneratorMethods.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Scripting/CommonGeneratorMethods.cs @@ -9,48 +9,60 @@ namespace OrchardCore.Scripting { public class CommonGeneratorMethods : IGlobalMethodProvider { - private static readonly GlobalMethod _base64 = new() - { - Name = "base64", - Method = serviceProvider => (Func)(encoded => + private static readonly GlobalMethod _base64 = + new() { - return Encoding.UTF8.GetString(Convert.FromBase64String(encoded)); - }), - }; + Name = "base64", + Method = serviceProvider => + (Func)( + encoded => + { + return Encoding.UTF8.GetString(Convert.FromBase64String(encoded)); + } + ), + }; - private static readonly GlobalMethod _html = new() - { - Name = "html", - Method = serviceProvider => (Func)(encoded => + private static readonly GlobalMethod _html = + new() { - return WebUtility.HtmlDecode(encoded); - }), - }; + Name = "html", + Method = serviceProvider => + (Func)( + encoded => + { + return WebUtility.HtmlDecode(encoded); + } + ), + }; /// /// Converts a Base64 encoded gzip stream to an uncompressed Base64 string. /// See http://www.txtwizard.net/compression. /// - private static readonly GlobalMethod _gZip = new() - { - Name = "gzip", - Method = serviceProvider => (Func)(encoded => + private static readonly GlobalMethod _gZip = + new() { - var bytes = Convert.FromBase64String(encoded); - using var gzip = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress); + Name = "gzip", + Method = serviceProvider => + (Func)( + encoded => + { + var bytes = Convert.FromBase64String(encoded); + using var gzip = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress); - var decompressed = new MemoryStream(); - var buffer = new byte[1024]; - int nRead; + var decompressed = new MemoryStream(); + var buffer = new byte[1024]; + int nRead; - while ((nRead = gzip.Read(buffer, 0, buffer.Length)) > 0) - { - decompressed.Write(buffer, 0, nRead); - } + while ((nRead = gzip.Read(buffer, 0, buffer.Length)) > 0) + { + decompressed.Write(buffer, 0, nRead); + } - return Convert.ToBase64String(decompressed.ToArray()); - }), - }; + return Convert.ToBase64String(decompressed.ToArray()); + } + ), + }; public IEnumerable GetMethods() => new[] { _base64, _html, _gZip }; } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Scripting/DefaultScriptingManager.cs b/src/OrchardCore/OrchardCore.Infrastructure/Scripting/DefaultScriptingManager.cs index 52f72476ff3..b9f5d01a229 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Scripting/DefaultScriptingManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Scripting/DefaultScriptingManager.cs @@ -9,9 +9,7 @@ public class DefaultScriptingManager : IScriptingManager { private readonly IEnumerable _engines; - public DefaultScriptingManager( - IEnumerable engines, - IEnumerable globalMethodProviders) + public DefaultScriptingManager(IEnumerable engines, IEnumerable globalMethodProviders) { _engines = engines; GlobalMethodProviders = new List(globalMethodProviders).AsReadOnly(); @@ -19,10 +17,7 @@ public DefaultScriptingManager( public IReadOnlyList GlobalMethodProviders { get; } - public object Evaluate(string directive, - IFileProvider fileProvider, - string basePath, - IEnumerable scopedMethodProviders) + public object Evaluate(string directive, IFileProvider fileProvider, string basePath, IEnumerable scopedMethodProviders) { var directiveIndex = directive.IndexOf(':'); if (directiveIndex == -1 || directiveIndex >= directive.Length - 2) diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Security/ApiAuthenticationHandler.cs b/src/OrchardCore/OrchardCore.Infrastructure/Security/ApiAuthenticationHandler.cs index e0ea44c392e..85553776a0c 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Security/ApiAuthenticationHandler.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Security/ApiAuthenticationHandler.cs @@ -19,7 +19,8 @@ public ApiAuthenticationHandler( IOptions authenticationOptions, IOptionsMonitor options, ILoggerFactory logger, - UrlEncoder encoder) + UrlEncoder encoder + ) : base(options, logger, encoder) { _authenticationOptions = authenticationOptions; diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Security/DefaultPermissionGrantingService.cs b/src/OrchardCore/OrchardCore.Infrastructure/Security/DefaultPermissionGrantingService.cs index 71073926ef6..4071c7c256e 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Security/DefaultPermissionGrantingService.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Security/DefaultPermissionGrantingService.cs @@ -26,8 +26,7 @@ public bool IsGranted(PermissionRequirement requirement, IEnumerable clai // SiteOwner permission grants them all grantingNames.Add(StandardPermissions.SiteOwner.Name); - return claims.Any(claim => string.Equals(claim.Type, Permission.ClaimType, StringComparison.OrdinalIgnoreCase) - && grantingNames.Contains(claim.Value)); + return claims.Any(claim => string.Equals(claim.Type, Permission.ClaimType, StringComparison.OrdinalIgnoreCase) && grantingNames.Contains(claim.Value)); } private static void GetGrantingNamesInternal(Permission permission, HashSet stack) diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Security/OrchardCoreBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Infrastructure/Security/OrchardCoreBuilderExtensions.cs index 34ff82bb070..da598816fb7 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Security/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Security/OrchardCoreBuilderExtensions.cs @@ -17,13 +17,15 @@ public static OrchardCoreBuilder AddSecurity(this OrchardCoreBuilder builder) { services.AddAuthorization(); - services.Configure((options) => - { - if (!options.Schemes.Any(x => x.Name == "Api")) + services.Configure( + (options) => { - options.AddScheme("Api", null); + if (!options.Schemes.Any(x => x.Name == "Api")) + { + options.AddScheme("Api", null); + } } - }); + ); services.AddScoped(); services.AddScoped(); diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Shell/ShellDescriptorManager.cs b/src/OrchardCore/OrchardCore.Infrastructure/Shell/ShellDescriptorManager.cs index fee78484560..2378bd1660f 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Shell/ShellDescriptorManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Shell/ShellDescriptorManager.cs @@ -36,7 +36,8 @@ public ShellDescriptorManager( IEnumerable shellDescriptorManagerEventHandlers, IExtensionManager extensionManager, IDocumentStore documentStore, - ILogger logger) + ILogger logger + ) { _shellSettings = shellSettings; _shellConfiguration = shellConfiguration; @@ -64,11 +65,7 @@ public async Task GetShellDescriptorAsync() if (!cacheable) { // Clone ShellDescriptor - shellDescriptor = new ShellDescriptor - { - SerialNumber = shellDescriptor.SerialNumber, - Installed = new List(shellDescriptor.Installed), - }; + shellDescriptor = new ShellDescriptor { SerialNumber = shellDescriptor.SerialNumber, Installed = new List(shellDescriptor.Installed), }; } // Init shell descriptor and load features @@ -87,9 +84,7 @@ public async Task GetShellDescriptorAsync() .Except(featureIds) .Select(id => new ShellFeature(id)); - shellDescriptor.Features = features - .Concat(missingDependencies) - .ToList(); + shellDescriptor.Features = features.Concat(missingDependencies).ToList(); return _shellDescriptor = shellDescriptor; } @@ -118,10 +113,7 @@ public async Task UpdateShellDescriptorAsync(int priorSerialNumber, IEnumerable< continue; } - var installed = new InstalledShellFeature(feature) - { - SerialNumber = shellDescriptor.SerialNumber - }; + var installed = new InstalledShellFeature(feature) { SerialNumber = shellDescriptor.SerialNumber }; shellDescriptor.Installed.Add(installed); } @@ -136,8 +128,12 @@ public async Task UpdateShellDescriptorAsync(int priorSerialNumber, IEnumerable< // In the 'ChangedAsync()' event the shell will be released so that, on request, a new one will be built. // So, we commit the session earlier to prevent a new shell from being built from an outdated descriptor. - await _shellDescriptorManagerEventHandlers.InvokeAsync((handler, shellDescriptor, _shellSettings) => - handler.ChangedAsync(shellDescriptor, _shellSettings), shellDescriptor, _shellSettings, _logger); + await _shellDescriptorManagerEventHandlers.InvokeAsync( + (handler, shellDescriptor, _shellSettings) => handler.ChangedAsync(shellDescriptor, _shellSettings), + shellDescriptor, + _shellSettings, + _logger + ); } private class ConfiguredFeatures diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Shell/ShellOrchardCoreBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Infrastructure/Shell/ShellOrchardCoreBuilderExtensions.cs index 0db4d4c1ea7..334507a0598 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Shell/ShellOrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Shell/ShellOrchardCoreBuilderExtensions.cs @@ -14,7 +14,8 @@ public static class ShellOrchardCoreBuilderExtensions /// public static OrchardCoreBuilder AddDataStorage(this OrchardCoreBuilder builder) { - builder.AddSitesFolder() + builder + .AddSitesFolder() .ConfigureServices(services => { services.AddScoped(); diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellConfigurationSources.cs b/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellConfigurationSources.cs index e1433bb7f0c..5931ddf7738 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellConfigurationSources.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellConfigurationSources.cs @@ -26,14 +26,11 @@ public class DatabaseShellConfigurationSources : IShellConfigurationSources public DatabaseShellConfigurationSources( Microsoft.Extensions.Configuration.IConfiguration configuration, IShellContextFactory shellContextFactory, - IOptions shellOptions) - + IOptions shellOptions + ) { - _options = configuration - .GetSection("OrchardCore") - .GetSectionCompat("OrchardCore_Shells_Database") - .Get() - ?? new DatabaseShellsStorageOptions(); + _options = + configuration.GetSection("OrchardCore").GetSectionCompat("OrchardCore_Shells_Database").Get() ?? new DatabaseShellsStorageOptions(); _shellContextFactory = shellContextFactory; diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellsSettingsSources.cs b/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellsSettingsSources.cs index 8f7d90872f4..dc4f5604f2a 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellsSettingsSources.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellsSettingsSources.cs @@ -25,14 +25,11 @@ public class DatabaseShellsSettingsSources : IShellsSettingsSources public DatabaseShellsSettingsSources( Microsoft.Extensions.Configuration.IConfiguration configuration, IShellContextFactory shellContextFactory, - IOptions shellOptions) - + IOptions shellOptions + ) { - _options = configuration - .GetSection("OrchardCore") - .GetSectionCompat("OrchardCore_Shells_Database") - .Get() - ?? new DatabaseShellsStorageOptions(); + _options = + configuration.GetSection("OrchardCore").GetSectionCompat("OrchardCore_Shells_Database").Get() ?? new DatabaseShellsStorageOptions(); _shellContextFactory = shellContextFactory; diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Extensions/DatabaseShellContextFactoryExtensions.cs b/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Extensions/DatabaseShellContextFactoryExtensions.cs index 3887e63607a..41aedbed1e2 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Extensions/DatabaseShellContextFactoryExtensions.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Extensions/DatabaseShellContextFactoryExtensions.cs @@ -9,18 +9,14 @@ namespace OrchardCore.Shells.Database.Extensions { public static class DatabaseShellContextFactoryExtensions { - internal static Task GetDatabaseContextAsync( - this IShellContextFactory shellContextFactory, DatabaseShellsStorageOptions options) + internal static Task GetDatabaseContextAsync(this IShellContextFactory shellContextFactory, DatabaseShellsStorageOptions options) { if (options.DatabaseProvider is null) { throw new InvalidOperationException("The 'OrchardCore.Shells.Database' configuration section should define a 'DatabaseProvider'"); } - var settings = new ShellSettings() - .AsDefaultShell() - .AsDisposable() - .AsRunning(); + var settings = new ShellSettings().AsDefaultShell().AsDisposable().AsRunning(); settings["DatabaseProvider"] = options.DatabaseProvider; settings["ConnectionString"] = options.ConnectionString; diff --git a/src/OrchardCore/OrchardCore.Liquid.Abstractions/ILiquidTemplateManager.cs b/src/OrchardCore/OrchardCore.Liquid.Abstractions/ILiquidTemplateManager.cs index dc2cc480cc6..aeac858144b 100644 --- a/src/OrchardCore/OrchardCore.Liquid.Abstractions/ILiquidTemplateManager.cs +++ b/src/OrchardCore/OrchardCore.Liquid.Abstractions/ILiquidTemplateManager.cs @@ -35,31 +35,44 @@ public interface ILiquidTemplateManager public static class LiquidTemplateManagerExtensions { - public static Task RenderStringAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder) - => manager.RenderStringAsync(template, encoder, model: null, properties: null); + public static Task RenderStringAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder) => + manager.RenderStringAsync(template, encoder, model: null, properties: null); - public static Task RenderStringAsync(this ILiquidTemplateManager manager, string template, TextWriter writer, TextEncoder encoder) - => manager.RenderAsync(template, writer, encoder, model: null, properties: null); + public static Task RenderStringAsync(this ILiquidTemplateManager manager, string template, TextWriter writer, TextEncoder encoder) => + manager.RenderAsync(template, writer, encoder, model: null, properties: null); - public static Task RenderStringAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder, object model) - => manager.RenderStringAsync(template, encoder, model, properties: null); + public static Task RenderStringAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder, object model) => + manager.RenderStringAsync(template, encoder, model, properties: null); - public static Task RenderStringAsync(this ILiquidTemplateManager manager, string template, TextWriter writer, TextEncoder encoder, object model) - => manager.RenderAsync(template, writer, encoder, model, properties: null); + public static Task RenderStringAsync(this ILiquidTemplateManager manager, string template, TextWriter writer, TextEncoder encoder, object model) => + manager.RenderAsync(template, writer, encoder, model, properties: null); - public static Task RenderStringAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder, IEnumerable> properties) - => manager.RenderStringAsync(template, encoder, model: null, properties); + public static Task RenderStringAsync( + this ILiquidTemplateManager manager, + string template, + TextEncoder encoder, + IEnumerable> properties + ) => manager.RenderStringAsync(template, encoder, model: null, properties); - public static Task RenderStringAsync(this ILiquidTemplateManager manager, string template, TextWriter writer, TextEncoder encoder, IEnumerable> properties) - => manager.RenderAsync(template, writer, encoder, model: null, properties); + public static Task RenderStringAsync( + this ILiquidTemplateManager manager, + string template, + TextWriter writer, + TextEncoder encoder, + IEnumerable> properties + ) => manager.RenderAsync(template, writer, encoder, model: null, properties); - public static Task RenderHtmlContentAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder) - => manager.RenderHtmlContentAsync(template, encoder, model: null, properties: null); + public static Task RenderHtmlContentAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder) => + manager.RenderHtmlContentAsync(template, encoder, model: null, properties: null); - public static Task RenderHtmlContentAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder, object model) - => manager.RenderHtmlContentAsync(template, encoder, model, properties: null); + public static Task RenderHtmlContentAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder, object model) => + manager.RenderHtmlContentAsync(template, encoder, model, properties: null); - public static Task RenderHtmlContentAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder, IEnumerable> properties) - => manager.RenderHtmlContentAsync(template, encoder, model: null, properties); + public static Task RenderHtmlContentAsync( + this ILiquidTemplateManager manager, + string template, + TextEncoder encoder, + IEnumerable> properties + ) => manager.RenderHtmlContentAsync(template, encoder, model: null, properties); } } diff --git a/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidContentAccessor.cs b/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidContentAccessor.cs index 8676d63e0a5..6fc4cee6a01 100644 --- a/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidContentAccessor.cs +++ b/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidContentAccessor.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Liquid /// /// This is a placeholder class that allows modules to extend the `Content` property in the current Liquid scope. /// - public class LiquidContentAccessor - { - } + public class LiquidContentAccessor { } } diff --git a/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidFilterDelegateResolver.cs b/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidFilterDelegateResolver.cs index 5e9123e2c47..2be824f48d5 100644 --- a/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidFilterDelegateResolver.cs +++ b/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidFilterDelegateResolver.cs @@ -6,12 +6,12 @@ namespace OrchardCore.Liquid { - public class LiquidFilterDelegateResolver where TLiquidFilter : class, ILiquidFilter + public class LiquidFilterDelegateResolver + where TLiquidFilter : class, ILiquidFilter { public ValueTask ResolveAsync(FluidValue input, FilterArguments arguments, TemplateContext context) { - var ctx = context as LiquidTemplateContext - ?? throw new InvalidOperationException("An implementation of 'LiquidTemplateContext' is required"); + var ctx = context as LiquidTemplateContext ?? throw new InvalidOperationException("An implementation of 'LiquidTemplateContext' is required"); var services = ctx.Services; var filter = services.GetRequiredService(); diff --git a/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidTemplateContext.cs b/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidTemplateContext.cs index 691bb2284cb..fe86ed23ecf 100644 --- a/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidTemplateContext.cs +++ b/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidTemplateContext.cs @@ -8,7 +8,8 @@ public class LiquidTemplateContext : TemplateContext { public const int MaxShapeRecursions = 3; - public LiquidTemplateContext(IServiceProvider services, TemplateOptions options) : base(options) + public LiquidTemplateContext(IServiceProvider services, TemplateOptions options) + : base(options) { Services = services; } diff --git a/src/OrchardCore/OrchardCore.Liquid.Abstractions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Liquid.Abstractions/ServiceCollectionExtensions.cs index eb4a00b87fb..01b2ede5ad3 100644 --- a/src/OrchardCore/OrchardCore.Liquid.Abstractions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Liquid.Abstractions/ServiceCollectionExtensions.cs @@ -5,7 +5,8 @@ namespace OrchardCore.Liquid { public static class ServiceCollectionExtensions { - public static IServiceCollection AddLiquidFilter(this IServiceCollection services, string name) where TLiquidFilter : class, ILiquidFilter + public static IServiceCollection AddLiquidFilter(this IServiceCollection services, string name) + where TLiquidFilter : class, ILiquidFilter { services.Configure(o => o.Filters.AddFilter(name, new LiquidFilterDelegateResolver().ResolveAsync)); services.AddScoped(); diff --git a/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionary.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionary.cs index da2330ba8d0..f82db398ace 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionary.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionary.cs @@ -57,7 +57,10 @@ public CultureDictionary(string cultureName, PluralizationRuleDelegate pluralRul var pluralForm = count.HasValue ? PluralRule(count.Value) : 0; if (pluralForm >= translations.Length) { - throw new PluralFormNotFoundException($"Plural form '{pluralForm}' doesn't exist for the key '{key}' in the '{CultureName}' culture.", new PluralForm(key, pluralForm, CultureInfo.GetCultureInfo(CultureName))); + throw new PluralFormNotFoundException( + $"Plural form '{pluralForm}' doesn't exist for the key '{key}' in the '{CultureName}' culture.", + new PluralForm(key, pluralForm, CultureInfo.GetCultureInfo(CultureName)) + ); } return translations[pluralForm]; diff --git a/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecord.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecord.cs index 61be036dda5..9ad10403298 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecord.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecord.cs @@ -13,10 +13,7 @@ public class CultureDictionaryRecord /// The message Id. /// a list of translations. public CultureDictionaryRecord(string messageId, params string[] translations) - : this(messageId, null, translations) - { - - } + : this(messageId, null, translations) { } /// /// Creates new instance of . diff --git a/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecordKey.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecordKey.cs index 1f67ec5add6..d5976448bf0 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecordKey.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecordKey.cs @@ -14,10 +14,8 @@ namespace OrchardCore.Localization /// Creates new instance of . /// /// The message Id. - public CultureDictionaryRecordKey(string messageId) : this(messageId, null) - { - - } + public CultureDictionaryRecordKey(string messageId) + : this(messageId, null) { } /// /// Creates new instance of . @@ -30,8 +28,7 @@ public CultureDictionaryRecordKey(string messageId, string context) _context = context; } - public static implicit operator string(CultureDictionaryRecordKey cultureDictionaryRecordKey) - => cultureDictionaryRecordKey.ToString(); + public static implicit operator string(CultureDictionaryRecordKey cultureDictionaryRecordKey) => cultureDictionaryRecordKey.ToString(); /// public override bool Equals(object obj) @@ -45,16 +42,12 @@ public override bool Equals(object obj) } /// - public bool Equals(CultureDictionaryRecordKey other) - => string.Equals(_messageId, other._messageId) && string.Equals(_context, other._context); + public bool Equals(CultureDictionaryRecordKey other) => string.Equals(_messageId, other._messageId) && string.Equals(_context, other._context); /// public override int GetHashCode() => HashCode.Combine(_messageId, _context); - public override string ToString() - => string.IsNullOrEmpty(_context) - ? _messageId - : _context.ToLowerInvariant() + "|" + _messageId; + public override string ToString() => string.IsNullOrEmpty(_context) ? _messageId : _context.ToLowerInvariant() + "|" + _messageId; public static bool operator ==(CultureDictionaryRecordKey left, CultureDictionaryRecordKey right) => left.Equals(right); diff --git a/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/CultureInfoExtensions.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/CultureInfoExtensions.cs index 92ffee6d3f8..fb55a80a8cf 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/CultureInfoExtensions.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/CultureInfoExtensions.cs @@ -11,9 +11,7 @@ public static class CultureInfoExtensions /// Gets the language direction for a given culture. /// /// The . - public static string GetLanguageDirection(this CultureInfo culture) => culture.IsRightToLeft() - ? LanguageDirection.RTL - : LanguageDirection.LTR; + public static string GetLanguageDirection(this CultureInfo culture) => culture.IsRightToLeft() ? LanguageDirection.RTL : LanguageDirection.LTR; /// /// Gets whether the culture is RTL or not. diff --git a/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/HtmlLocalizerExtensions.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/HtmlLocalizerExtensions.cs index 37b1b404a46..5139200fdd3 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/HtmlLocalizerExtensions.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/HtmlLocalizerExtensions.cs @@ -20,10 +20,21 @@ public static LocalizedHtmlString Plural(this IHtmlLocalizer localizer, int coun { if (plural == null) { - throw new ArgumentNullException(nameof(plural), "Plural text can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension."); + throw new ArgumentNullException( + nameof(plural), + "Plural text can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension." + ); } - return localizer[singular, new PluralizationArgument { Count = count, Forms = [singular, plural], Arguments = arguments }]; + return localizer[ + singular, + new PluralizationArgument + { + Count = count, + Forms = [singular, plural], + Arguments = arguments + } + ]; } /// @@ -37,17 +48,31 @@ public static LocalizedHtmlString Plural(this IHtmlLocalizer localizer, int coun { if (pluralForms == null) { - throw new ArgumentNullException(nameof(pluralForms), "PluralForms array can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension."); + throw new ArgumentNullException( + nameof(pluralForms), + "PluralForms array can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension." + ); } if (pluralForms.Length == 0) { - throw new ArgumentException("PluralForms array can't be empty, it must contain at least one element. If you don't want to specify the plural text, use IStringLocalizer without Plural extension.", nameof(pluralForms)); + throw new ArgumentException( + "PluralForms array can't be empty, it must contain at least one element. If you don't want to specify the plural text, use IStringLocalizer without Plural extension.", + nameof(pluralForms) + ); } var name = pluralForms[0]; - return localizer[name, new PluralizationArgument { Count = count, Forms = pluralForms, Arguments = arguments }]; + return localizer[ + name, + new PluralizationArgument + { + Count = count, + Forms = pluralForms, + Arguments = arguments + } + ]; } } } diff --git a/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/StringLocalizerExtensions.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/StringLocalizerExtensions.cs index 3262404d92b..829b4495cb5 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/StringLocalizerExtensions.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/StringLocalizerExtensions.cs @@ -20,10 +20,21 @@ public static LocalizedString Plural(this IStringLocalizer localizer, int count, { if (plural == null) { - throw new ArgumentNullException(nameof(plural), "Plural text can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension."); + throw new ArgumentNullException( + nameof(plural), + "Plural text can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension." + ); } - return localizer[singular, new PluralizationArgument { Count = count, Forms = [singular, plural], Arguments = arguments }]; + return localizer[ + singular, + new PluralizationArgument + { + Count = count, + Forms = [singular, plural], + Arguments = arguments + } + ]; } /// @@ -37,15 +48,29 @@ public static LocalizedString Plural(this IStringLocalizer localizer, int count, { if (pluralForms == null) { - throw new ArgumentNullException(nameof(pluralForms), "PluralForms array can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension."); + throw new ArgumentNullException( + nameof(pluralForms), + "PluralForms array can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension." + ); } if (pluralForms.Length == 0) { - throw new ArgumentException("PluralForms array can't be empty, it must contain at least one element. If you don't want to specify the plural text, use IStringLocalizer without Plural extension.", nameof(pluralForms)); + throw new ArgumentException( + "PluralForms array can't be empty, it must contain at least one element. If you don't want to specify the plural text, use IStringLocalizer without Plural extension.", + nameof(pluralForms) + ); } - return localizer[pluralForms[0], new PluralizationArgument { Count = count, Forms = pluralForms, Arguments = arguments }]; + return localizer[ + pluralForms[0], + new PluralizationArgument + { + Count = count, + Forms = pluralForms, + Arguments = arguments + } + ]; } } } diff --git a/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/ViewLocalizerExtensions.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/ViewLocalizerExtensions.cs index 0cf9e980dd7..e24a8b50c21 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/ViewLocalizerExtensions.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/Extensions/ViewLocalizerExtensions.cs @@ -21,10 +21,21 @@ public static LocalizedHtmlString Plural(this IViewLocalizer localizer, int coun { if (plural == null) { - throw new ArgumentNullException(nameof(plural), "Plural text can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension."); + throw new ArgumentNullException( + nameof(plural), + "Plural text can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension." + ); } - return localizer[singular, new PluralizationArgument { Count = count, Forms = [singular, plural], Arguments = arguments }]; + return localizer[ + singular, + new PluralizationArgument + { + Count = count, + Forms = [singular, plural], + Arguments = arguments + } + ]; } /// @@ -38,15 +49,29 @@ public static LocalizedHtmlString Plural(this IViewLocalizer localizer, int coun { if (pluralForms == null) { - throw new ArgumentNullException(nameof(pluralForms), "PluralForms array can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension."); + throw new ArgumentNullException( + nameof(pluralForms), + "PluralForms array can't be null. If you don't want to specify the plural text, use IStringLocalizer without Plural extension." + ); } if (pluralForms.Length == 0) { - throw new ArgumentException("PluralForms array can't be empty, it must contain at least one element. If you don't want to specify the plural text, use IStringLocalizer without Plural extension.", nameof(pluralForms)); + throw new ArgumentException( + "PluralForms array can't be empty, it must contain at least one element. If you don't want to specify the plural text, use IStringLocalizer without Plural extension.", + nameof(pluralForms) + ); } - return localizer[pluralForms[0], new PluralizationArgument { Count = count, Forms = pluralForms, Arguments = arguments }]; + return localizer[ + pluralForms[0], + new PluralizationArgument + { + Count = count, + Forms = pluralForms, + Arguments = arguments + } + ]; } } } diff --git a/src/OrchardCore/OrchardCore.Localization.Abstractions/PluralForm.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/PluralForm.cs index c6dbae04552..e0db0cc16e5 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/PluralForm.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/PluralForm.cs @@ -13,10 +13,7 @@ public class PluralForm /// The localized string. /// The plural form. public PluralForm(string key, int form) - : this(key, form, CultureInfo.CurrentUICulture) - { - - } + : this(key, form, CultureInfo.CurrentUICulture) { } /// /// Creates new instance of with key, form and culture. diff --git a/src/OrchardCore/OrchardCore.Localization.Abstractions/PluralFormNotFoundException.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/PluralFormNotFoundException.cs index 23705a52c28..a2e58b4e42c 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/PluralFormNotFoundException.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/PluralFormNotFoundException.cs @@ -10,26 +10,22 @@ public class PluralFormNotFoundException : Exception /// /// Creates new instance of . /// - public PluralFormNotFoundException() - { - - } + public PluralFormNotFoundException() { } /// /// Creates new instance of with a message. /// /// The exception message. - public PluralFormNotFoundException(string message) : base(message) - { - - } + public PluralFormNotFoundException(string message) + : base(message) { } /// /// Creates new instance of with a message. /// /// The exception message. /// The that causes the exception. - public PluralFormNotFoundException(string message, PluralForm form) : base(message) + public PluralFormNotFoundException(string message, PluralForm form) + : base(message) { Form = form; } @@ -39,10 +35,8 @@ public PluralFormNotFoundException(string message, PluralForm form) : base(messa /// /// The exception message. /// The inner . - public PluralFormNotFoundException(string message, Exception innerException) : base(message, innerException) - { - - } + public PluralFormNotFoundException(string message, Exception innerException) + : base(message, innerException) { } /// /// Gets the pluralization form. diff --git a/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/DataAnnotationsDefaultErrorMessages.cs b/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/DataAnnotationsDefaultErrorMessages.cs index 3d955613fc9..4c18b2dd278 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/DataAnnotationsDefaultErrorMessages.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/DataAnnotationsDefaultErrorMessages.cs @@ -11,7 +11,10 @@ internal sealed class DataAnnotationsDefaultErrorMessages private readonly IStringLocalizer S = null; #pragma warning restore IDE1006 // Naming Styles - public string AssociatedMetadataTypeTypeDescriptorMetadataTypeContainsUnknownProperties => S["The associated metadata type for type '{0}' contains the following unknown properties or fields: {1}. Please make sure that the names of these members match the names of the properties on the main type."]; + public string AssociatedMetadataTypeTypeDescriptorMetadataTypeContainsUnknownProperties => + S[ + "The associated metadata type for type '{0}' contains the following unknown properties or fields: {1}. Please make sure that the names of these members match the names of the properties on the main type." + ]; public string AttributeStoreUnknownProperty => S["The type '{0}' does not contain a public property named '{1}'."]; @@ -23,13 +26,19 @@ internal sealed class DataAnnotationsDefaultErrorMessages public string CreditCardAttributeInvalid => S["The {0} field is not a valid credit card number."]; - public string CustomValidationAttributeMethodMustReturnValidationResult => S["The CustomValidationAttribute method '{0}' in type '{1}' must return System.ComponentModel.DataAnnotations.ValidationResult. Use System.ComponentModel.DataAnnotations.ValidationResult.Success to represent success."]; + public string CustomValidationAttributeMethodMustReturnValidationResult => + S[ + "The CustomValidationAttribute method '{0}' in type '{1}' must return System.ComponentModel.DataAnnotations.ValidationResult. Use System.ComponentModel.DataAnnotations.ValidationResult.Success to represent success." + ]; public string CustomValidationAttributeMethodNotFound => S["The CustomValidationAttribute method '{0}' does not exist in type '{1}' or is not public and static."]; public string CustomValidationAttributeMethodRequired => S["The CustomValidationAttribute.Method was not specified."]; - public string CustomValidationAttributeMethodSignature => S["The CustomValidationAttribute method '{0}' in type '{1}' must match the expected signature: public static ValidationResult {0}(object value, ValidationContext context). The value can be strongly typed. The ValidationContext parameter is optional."]; + public string CustomValidationAttributeMethodSignature => + S[ + "The CustomValidationAttribute method '{0}' in type '{1}' must match the expected signature: public static ValidationResult {0}(object value, ValidationContext context). The value can be strongly typed. The ValidationContext parameter is optional." + ]; public string CustomValidationAttributeTypeConversionFailed => S["Could not convert the value of type '{0}' to '{1}' as expected by method {2}.{3}."]; @@ -51,9 +60,13 @@ internal sealed class DataAnnotationsDefaultErrorMessages public string FileExtensionsAttributeInvalid => S["The {0} field only accepts files with the following extensions: {1}."]; - public string LocalizableStringLocalizationFailed => S["Cannot retrieve property '{0}' because localization failed. Type '{1}' is not public or does not contain a public static string property with the name '{2}'."]; + public string LocalizableStringLocalizationFailed => + S["Cannot retrieve property '{0}' because localization failed. Type '{1}' is not public or does not contain a public static string property with the name '{2}'."]; - public string MaxLengthAttributeInvalidMaxLength => S["MaxLengthAttribute must have a Length value that is greater than zero. Use MaxLength() without parameters to indicate that the string or array can have the maximum allowable length."]; + public string MaxLengthAttributeInvalidMaxLength => + S[ + "MaxLengthAttribute must have a Length value that is greater than zero. Use MaxLength() without parameters to indicate that the string or array can have the maximum allowable length." + ]; public string MaxLengthAttributeValidationError => S["The field {0} must be a string or array type with a maximum length of '{1}'."]; @@ -89,7 +102,8 @@ internal sealed class DataAnnotationsDefaultErrorMessages public string StringLengthAttributeValidationErrorIncludingMinimum => S["The field {0} must be a string with a minimum length of {2} and a maximum length of {1}."]; - public string UIHintImplementationControlParameterKeyIsNotAString => S["The key parameter at position {0} with value '{1}' is not a string. Every key control parameter must be a string."]; + public string UIHintImplementationControlParameterKeyIsNotAString => + S["The key parameter at position {0} with value '{1}' is not a string. Every key control parameter must be a string."]; public string UIHintImplementationControlParameterKeyIsNull => S["The key parameter at position {0} is null. Every key control parameter must be a string."]; @@ -101,7 +115,10 @@ internal sealed class DataAnnotationsDefaultErrorMessages public string ValidationAttributeCannotSetErrorMessageAndResource => S["Either ErrorMessageString or ErrorMessageResourceName must be set, but not both."]; - public string ValidationAttributeIsValidNotImplemented => S["IsValid(object value) has not been implemented by this class. The preferred entry point is GetValidationResult() and classes should override IsValid(object value, ValidationContext context)."]; + public string ValidationAttributeIsValidNotImplemented => + S[ + "IsValid(object value) has not been implemented by this class. The preferred entry point is GetValidationResult() and classes should override IsValid(object value, ValidationContext context)." + ]; public string ValidationAttributeNeedBothResourceTypeAndResourceName => S["Both ErrorMessageResourceType and ErrorMessageResourceName need to be set on this attribute."]; diff --git a/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/LocalizedValidationMetadataProvider.cs b/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/LocalizedValidationMetadataProvider.cs index aac783d2c8c..78322f11e7f 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/LocalizedValidationMetadataProvider.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/LocalizedValidationMetadataProvider.cs @@ -35,9 +35,8 @@ public void CreateValidationMetadata(ValidationMetadataProviderContext context) var displayName = context.Attributes.OfType().FirstOrDefault()?.Name; // Use DisplayName if present var argument = displayName ?? context.Key.Name; - var errorMessageString = attribute.ErrorMessage == null && attribute.ErrorMessageResourceName == null - ? attribute.FormatErrorMessage(argument) - : attribute.ErrorMessage; + var errorMessageString = + attribute.ErrorMessage == null && attribute.ErrorMessageResourceName == null ? attribute.FormatErrorMessage(argument) : attribute.ErrorMessage; // Localize the parameterized error message var localizedString = _stringLocalizer[errorMessageString]; diff --git a/src/OrchardCore/OrchardCore.Localization.Core/DefaultPluralRuleProvider.cs b/src/OrchardCore/OrchardCore.Localization.Core/DefaultPluralRuleProvider.cs index 74c022dabdd..6942b1108b0 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/DefaultPluralRuleProvider.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/DefaultPluralRuleProvider.cs @@ -10,7 +10,7 @@ namespace OrchardCore.Localization /// public class DefaultPluralRuleProvider : IPluralRuleProvider { - private readonly static Dictionary _rules; + private static readonly Dictionary _rules; static DefaultPluralRuleProvider() { @@ -18,25 +18,274 @@ static DefaultPluralRuleProvider() AddRule(["ay", "bo", "cgg", "dz", "fa", "id", "ja", "jbo", "ka", "kk", "km", "ko", "ky", "lo", "ms", "my", "sah", "su", "th", "tt", "ug", "vi", "wo", "zh"], n => 0); AddRule(["ach", "ak", "am", "arn", "br", "fil", "fr", "gun", "ln", "mfe", "mg", "mi", "oc", "pt-BR", "tg", "ti", "tr", "uz", "wa"], n => (n > 1 ? 1 : 0)); - AddRule(["af", "an", "anp", "as", "ast", "az", "bg", "bn", "brx", "ca", "da", "de", "doi", "el", "en", "eo", "es", "es-AR", "et", "eu", "ff", "fi", "fo", "fur", "fy", "gl", "gu", "ha", "he", "hi", "hne", "hu", "hy", "ia", "it", "kl", "kn", "ku", "lb", "mai", "ml", "mn", "mni", "mr", "nah", "nap", "nb", "ne", "nl", "nn", "no", "nso", "or", "pa", "pap", "pms", "ps", "pt", "rm", "rw", "sat", "sco", "sd", "se", "si", "so", "son", "sq", "sv", "sw", "ta", "te", "tk", "ur", "yo"], n => (n != 1 ? 1 : 0)); + AddRule( + [ + "af", + "an", + "anp", + "as", + "ast", + "az", + "bg", + "bn", + "brx", + "ca", + "da", + "de", + "doi", + "el", + "en", + "eo", + "es", + "es-AR", + "et", + "eu", + "ff", + "fi", + "fo", + "fur", + "fy", + "gl", + "gu", + "ha", + "he", + "hi", + "hne", + "hu", + "hy", + "ia", + "it", + "kl", + "kn", + "ku", + "lb", + "mai", + "ml", + "mn", + "mni", + "mr", + "nah", + "nap", + "nb", + "ne", + "nl", + "nn", + "no", + "nso", + "or", + "pa", + "pap", + "pms", + "ps", + "pt", + "rm", + "rw", + "sat", + "sco", + "sd", + "se", + "si", + "so", + "son", + "sq", + "sv", + "sw", + "ta", + "te", + "tk", + "ur", + "yo" + ], + n => (n != 1 ? 1 : 0) + ); AddRule(["is"], n => (n % 10 != 1 || n % 100 == 11 ? 1 : 0)); AddRule(["jv"], n => (n != 0 ? 1 : 0)); AddRule(["mk"], n => (n == 1 || n % 10 == 1 ? 0 : 1)); - AddRule(["be", "bs", "hr", "lt"], n => (n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2)); - AddRule(["cs"], n => ((n == 1) ? 0 : (n >= 2 && n <= 4) ? 1 : 2)); - AddRule(["csb", "pl"], n => ((n == 1) ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2)); - AddRule(["lv"], n => (n % 10 == 1 && n % 100 != 11 ? 0 : n != 0 ? 1 : 2)); - AddRule(["mnk"], n => (n == 0 ? 0 : n == 1 ? 1 : 2)); - AddRule(["ro"], n => (n == 1 ? 0 : (n == 0 || (n % 100 > 0 && n % 100 < 20)) ? 1 : 2)); - AddRule(["cy"], n => ((n == 1) ? 0 : (n == 2) ? 1 : (n != 8 && n != 11) ? 2 : 3)); - AddRule(["gd"], n => ((n == 1 || n == 11) ? 0 : (n == 2 || n == 12) ? 1 : (n > 2 && n < 20) ? 2 : 3)); - AddRule(["kw"], n => ((n == 1) ? 0 : (n == 2) ? 1 : (n == 3) ? 2 : 3)); - AddRule(["mt"], n => (n == 1 ? 0 : n == 0 || (n % 100 > 1 && n % 100 < 11) ? 1 : (n % 100 > 10 && n % 100 < 20) ? 2 : 3)); - AddRule(["sl"], n => (n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0)); - AddRule(["ru", "sr", "uk"], n => (n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2)); - AddRule(["sk"], n => ((n == 1) ? 0 : (n >= 2 && n <= 4) ? 1 : 2)); - AddRule(["ga"], n => (n == 1 ? 0 : n == 2 ? 1 : (n > 2 && n < 7) ? 2 : (n > 6 && n < 11) ? 3 : 4)); - AddRule(["ar"], n => (n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5)); + AddRule( + ["be", "bs", "hr", "lt"], + n => + ( + n % 10 == 1 && n % 100 != 11 + ? 0 + : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) + ? 1 + : 2 + ) + ); + AddRule( + ["cs"], + n => + ( + (n == 1) + ? 0 + : (n >= 2 && n <= 4) + ? 1 + : 2 + ) + ); + AddRule( + ["csb", "pl"], + n => + ( + (n == 1) + ? 0 + : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) + ? 1 + : 2 + ) + ); + AddRule( + ["lv"], + n => + ( + n % 10 == 1 && n % 100 != 11 + ? 0 + : n != 0 + ? 1 + : 2 + ) + ); + AddRule( + ["mnk"], + n => + ( + n == 0 + ? 0 + : n == 1 + ? 1 + : 2 + ) + ); + AddRule( + ["ro"], + n => + ( + n == 1 + ? 0 + : (n == 0 || (n % 100 > 0 && n % 100 < 20)) + ? 1 + : 2 + ) + ); + AddRule( + ["cy"], + n => + ( + (n == 1) + ? 0 + : (n == 2) + ? 1 + : (n != 8 && n != 11) + ? 2 + : 3 + ) + ); + AddRule( + ["gd"], + n => + ( + (n == 1 || n == 11) + ? 0 + : (n == 2 || n == 12) + ? 1 + : (n > 2 && n < 20) + ? 2 + : 3 + ) + ); + AddRule( + ["kw"], + n => + ( + (n == 1) + ? 0 + : (n == 2) + ? 1 + : (n == 3) + ? 2 + : 3 + ) + ); + AddRule( + ["mt"], + n => + ( + n == 1 + ? 0 + : n == 0 || (n % 100 > 1 && n % 100 < 11) + ? 1 + : (n % 100 > 10 && n % 100 < 20) + ? 2 + : 3 + ) + ); + AddRule( + ["sl"], + n => + ( + n % 100 == 1 + ? 1 + : n % 100 == 2 + ? 2 + : n % 100 == 3 || n % 100 == 4 + ? 3 + : 0 + ) + ); + AddRule( + ["ru", "sr", "uk"], + n => + ( + n % 10 == 1 && n % 100 != 11 + ? 0 + : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) + ? 1 + : 2 + ) + ); + AddRule( + ["sk"], + n => + ( + (n == 1) + ? 0 + : (n >= 2 && n <= 4) + ? 1 + : 2 + ) + ); + AddRule( + ["ga"], + n => + ( + n == 1 + ? 0 + : n == 2 + ? 1 + : (n > 2 && n < 7) + ? 2 + : (n > 6 && n < 11) + ? 3 + : 4 + ) + ); + AddRule( + ["ar"], + n => + ( + n == 0 + ? 0 + : n == 1 + ? 1 + : n == 2 + ? 2 + : n % 100 >= 3 && n % 100 <= 10 + ? 3 + : n % 100 >= 11 + ? 4 + : 5 + ) + ); } /// diff --git a/src/OrchardCore/OrchardCore.Localization.Core/Extensions/LocalizationServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Localization.Core/Extensions/LocalizationServiceCollectionExtensions.cs index 8604b7f291d..7544b63cb23 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/Extensions/LocalizationServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/Extensions/LocalizationServiceCollectionExtensions.cs @@ -48,7 +48,7 @@ public static IServiceCollection AddPortableObjectLocalization(this IServiceColl } /// - /// Localize data annotations attributes from portable object files. + /// Localize data annotations attributes from portable object files. /// /// The . public static IServiceCollection AddDataAnnotationsPortableObjectLocalization(this IServiceCollection services) diff --git a/src/OrchardCore/OrchardCore.Localization.Core/LocalizationManager.cs b/src/OrchardCore/OrchardCore.Localization.Core/LocalizationManager.cs index 828b9d5848c..cb0a58d0ffa 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/LocalizationManager.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/LocalizationManager.cs @@ -26,10 +26,7 @@ public class LocalizationManager : ILocalizationManager /// A list of s. /// The list of available . /// The . - public LocalizationManager( - IEnumerable pluralRuleProviders, - IEnumerable translationProviders, - IMemoryCache cache) + public LocalizationManager(IEnumerable pluralRuleProviders, IEnumerable translationProviders, IMemoryCache cache) { _pluralRuleProviders = pluralRuleProviders.OrderBy(o => o.Order).ToArray(); _translationProviders = translationProviders; @@ -39,26 +36,32 @@ public LocalizationManager( /// public CultureDictionary GetDictionary(CultureInfo culture) { - var cachedDictionary = _cache.GetOrCreate(CacheKeyPrefix + culture.Name, k => new Lazy(() => - { - var rule = _defaultPluralRule; - - foreach (var provider in _pluralRuleProviders) - { - if (provider.TryGetRule(culture, out rule)) + var cachedDictionary = _cache.GetOrCreate( + CacheKeyPrefix + culture.Name, + k => new Lazy( + () => { - break; - } - } + var rule = _defaultPluralRule; + + foreach (var provider in _pluralRuleProviders) + { + if (provider.TryGetRule(culture, out rule)) + { + break; + } + } - var dictionary = new CultureDictionary(culture.Name, rule ?? _defaultPluralRule); - foreach (var translationProvider in _translationProviders) - { - translationProvider.LoadTranslations(culture.Name, dictionary); - } + var dictionary = new CultureDictionary(culture.Name, rule ?? _defaultPluralRule); + foreach (var translationProvider in _translationProviders) + { + translationProvider.LoadTranslations(culture.Name, dictionary); + } - return dictionary; - }, LazyThreadSafetyMode.ExecutionAndPublication)); + return dictionary; + }, + LazyThreadSafetyMode.ExecutionAndPublication + ) + ); return cachedDictionary.Value; } diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoParser.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoParser.cs index 5bfaf8a3fb7..6d919199b6b 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoParser.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoParser.cs @@ -11,12 +11,13 @@ namespace OrchardCore.Localization.PortableObject /// public class PoParser { - private static readonly Dictionary _escapeTranslations = new() - { - { 'n', '\n' }, - { 'r', '\r' }, - { 't', '\t' }, - }; + private static readonly Dictionary _escapeTranslations = + new() + { + { 'n', '\n' }, + { 'r', '\r' }, + { 't', '\t' }, + }; /// /// Parses a .po file. @@ -162,20 +163,26 @@ public void Set(PoContext context, string text) switch (context) { case PoContext.MessageId: + { + // If the MessageId has been set to an empty string and now gets set again + // before flushing the values should be reset. + if (string.IsNullOrEmpty(MessageId)) { - // If the MessageId has been set to an empty string and now gets set again - // before flushing the values should be reset. - if (string.IsNullOrEmpty(MessageId)) - { - _values.Clear(); - } - - MessageId = text; - break; + _values.Clear(); } - case PoContext.MessageContext: MessageContext = text; break; - case PoContext.Translation: _values.Add(text); break; - case PoContext.Text: AppendText(text); return; // We don't want to set context to Text. + + MessageId = text; + break; + } + case PoContext.MessageContext: + MessageContext = text; + break; + case PoContext.Translation: + _values.Add(text); + break; + case PoContext.Text: + AppendText(text); + return; // We don't want to set context to Text. } _context = context; @@ -185,8 +192,12 @@ private void AppendText(string text) { switch (_context) { - case PoContext.MessageId: MessageId += text; break; - case PoContext.MessageContext: MessageContext += text; break; + case PoContext.MessageId: + MessageId += text; + break; + case PoContext.MessageContext: + MessageContext += text; + break; case PoContext.Translation: if (_values.Count > 0) { diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizer.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizer.cs index 03285d9017f..11993dadbbf 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizer.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizer.cs @@ -14,14 +14,14 @@ public class PortableObjectHtmlLocalizer : HtmlLocalizer /// Creates a new instance of . /// /// - public PortableObjectHtmlLocalizer(IStringLocalizer localizer) : base(localizer) + public PortableObjectHtmlLocalizer(IStringLocalizer localizer) + : base(localizer) { _localizer = localizer; } /// - public override LocalizedHtmlString this[string name] - => ToHtmlString(_localizer[name]); + public override LocalizedHtmlString this[string name] => ToHtmlString(_localizer[name]); /// public override LocalizedHtmlString this[string name, params object[] arguments] diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizerFactory.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizerFactory.cs index 18dfea17442..2a62fd24df7 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizerFactory.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizerFactory.cs @@ -15,15 +15,12 @@ public class PortableObjectHtmlLocalizerFactory : IHtmlLocalizerFactory /// Creates a new instance of . /// /// The . - public PortableObjectHtmlLocalizerFactory(IStringLocalizerFactory stringLocalizerFactory) => - _stringLocalizerFactory = stringLocalizerFactory; + public PortableObjectHtmlLocalizerFactory(IStringLocalizerFactory stringLocalizerFactory) => _stringLocalizerFactory = stringLocalizerFactory; /// - public IHtmlLocalizer Create(Type resourceSource) => - new PortableObjectHtmlLocalizer(_stringLocalizerFactory.Create(resourceSource)); + public IHtmlLocalizer Create(Type resourceSource) => new PortableObjectHtmlLocalizer(_stringLocalizerFactory.Create(resourceSource)); /// - public IHtmlLocalizer Create(string baseName, string location) => - new PortableObjectHtmlLocalizer(_stringLocalizerFactory.Create(baseName, location)); + public IHtmlLocalizer Create(string baseName, string location) => new PortableObjectHtmlLocalizer(_stringLocalizerFactory.Create(baseName, location)); } } diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs index 79120b6ec16..e7cdf862f0e 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs @@ -28,11 +28,7 @@ public class PortableObjectStringLocalizer : IPluralStringLocalizer /// /// /// - public PortableObjectStringLocalizer( - string context, - ILocalizationManager localizationManager, - bool fallBackToParentCulture, - ILogger logger) + public PortableObjectStringLocalizer(string context, ILocalizationManager localizationManager, bool fallBackToParentCulture, ILogger logger) { _context = context; _localizationManager = localizationManager; @@ -70,9 +66,7 @@ public virtual IEnumerable GetAllStrings(bool includeParentCult { var culture = CultureInfo.CurrentUICulture; - return includeParentCultures - ? GetAllStringsFromCultureHierarchy(culture) - : GetAllStrings(culture); + return includeParentCultures ? GetAllStringsFromCultureHierarchy(culture) : GetAllStrings(culture); } /// @@ -155,7 +149,11 @@ protected string GetTranslation(string[] pluralForms, CultureInfo culture, int? { if (_logger.IsEnabled(LogLevel.Warning)) { - _logger.LogWarning("Plural form '{PluralForm}' doesn't exist in values provided by the 'IStringLocalizer.Plural' method. Provided values: {PluralForms}", pluralForm, string.Join(", ", pluralForms)); + _logger.LogWarning( + "Plural form '{PluralForm}' doesn't exist in values provided by the 'IStringLocalizer.Plural' method. Provided values: {PluralForms}", + pluralForm, + string.Join(", ", pluralForms) + ); } // Use the latest available form. @@ -180,8 +178,7 @@ protected string GetTranslation(string name, string context, CultureInfo culture } culture = culture.Parent; - } - while (culture != CultureInfo.InvariantCulture); + } while (culture != CultureInfo.InvariantCulture); } else { diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizerFactory.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizerFactory.cs index 75cfa796f4d..09232db1e11 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizerFactory.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizerFactory.cs @@ -24,7 +24,8 @@ public class PortableObjectStringLocalizerFactory : IStringLocalizerFactory public PortableObjectStringLocalizerFactory( ILocalizationManager localizationManager, IOptions requestLocalizationOptions, - ILogger logger) + ILogger logger + ) { _localizationManager = localizationManager; _fallBackToParentCulture = requestLocalizationOptions.Value.FallBackToParentUICultures; diff --git a/src/OrchardCore/OrchardCore.Logging.NLog/HostBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Logging.NLog/HostBuilderExtensions.cs index a4229b207e3..c1282170bcf 100644 --- a/src/OrchardCore/OrchardCore.Logging.NLog/HostBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Logging.NLog/HostBuilderExtensions.cs @@ -8,15 +8,16 @@ public static class HostBuilderExtensions { public static IHostBuilder UseNLogHost(this IHostBuilder builder) { - LogManager.Setup().SetupExtensions(ext => - ext.RegisterLayoutRenderer(TenantLayoutRenderer.LayoutRendererName)); + LogManager.Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer(TenantLayoutRenderer.LayoutRendererName)); return builder .UseNLog() - .ConfigureAppConfiguration((context, _) => - { - var environment = context.HostingEnvironment; - LogManager.Configuration.Variables["configDir"] = environment.ContentRootPath; - }); + .ConfigureAppConfiguration( + (context, _) => + { + var environment = context.HostingEnvironment; + LogManager.Configuration.Variables["configDir"] = environment.ContentRootPath; + } + ); } } diff --git a/src/OrchardCore/OrchardCore.Logging.NLog/WebHostBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Logging.NLog/WebHostBuilderExtensions.cs index c0407a2c797..8c97c544830 100644 --- a/src/OrchardCore/OrchardCore.Logging.NLog/WebHostBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Logging.NLog/WebHostBuilderExtensions.cs @@ -11,16 +11,17 @@ public static class WebHostBuilderExtensions { public static IWebHostBuilder UseNLogWeb(this IWebHostBuilder builder) { - LogManager.Setup().SetupExtensions(ext => - ext.RegisterLayoutRenderer(TenantLayoutRenderer.LayoutRendererName)); + LogManager.Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer(TenantLayoutRenderer.LayoutRendererName)); return builder .UseNLog() - .ConfigureAppConfiguration((context, _) => - { - var environment = context.HostingEnvironment; - LogManager.Configuration.Variables["configDir"] = environment.ContentRootPath; - }); + .ConfigureAppConfiguration( + (context, _) => + { + var environment = context.HostingEnvironment; + LogManager.Configuration.Variables["configDir"] = environment.ContentRootPath; + } + ); } } @@ -30,7 +31,8 @@ public static LoggingConfiguration ConfigureNLog(this IHostEnvironment env, stri { var fileName = Path.Combine(env.ContentRootPath, configFileRelativePath); - LogManager.Setup() + LogManager + .Setup() .SetupLogFactory(factory => factory.AddCallSiteHiddenAssembly(typeof(AspNetExtensions).GetType().Assembly)) .SetupExtensions(ext => { diff --git a/src/OrchardCore/OrchardCore.Logging.Serilog/WebHostBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Logging.Serilog/WebHostBuilderExtensions.cs index c3f23994e5b..7f61116666f 100644 --- a/src/OrchardCore/OrchardCore.Logging.Serilog/WebHostBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Logging.Serilog/WebHostBuilderExtensions.cs @@ -7,11 +7,12 @@ public static class WebHostBuilderExtensions { public static IHostBuilder UseSerilogWeb(this IHostBuilder builder) { - return builder.UseSerilog((hostingContext, configBuilder) => - { - configBuilder.ReadFrom.Configuration(hostingContext.Configuration) - .Enrich.FromLogContext(); - }); + return builder.UseSerilog( + (hostingContext, configBuilder) => + { + configBuilder.ReadFrom.Configuration(hostingContext.Configuration).Enrich.FromLogContext(); + } + ); } } } diff --git a/src/OrchardCore/OrchardCore.Media.Abstractions/Events/MediaCreatingContext.cs b/src/OrchardCore/OrchardCore.Media.Abstractions/Events/MediaCreatingContext.cs index 5f6d1e81b12..0a696dc658e 100644 --- a/src/OrchardCore/OrchardCore.Media.Abstractions/Events/MediaCreatingContext.cs +++ b/src/OrchardCore/OrchardCore.Media.Abstractions/Events/MediaCreatingContext.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Media.Events { - public class MediaCreatingContext : MediaContextBase - { - } + public class MediaCreatingContext : MediaContextBase { } } diff --git a/src/OrchardCore/OrchardCore.Media.Abstractions/Events/MediaDeletingContext.cs b/src/OrchardCore/OrchardCore.Media.Abstractions/Events/MediaDeletingContext.cs index e6e6b273386..b5a1f1b9843 100644 --- a/src/OrchardCore/OrchardCore.Media.Abstractions/Events/MediaDeletingContext.cs +++ b/src/OrchardCore/OrchardCore.Media.Abstractions/Events/MediaDeletingContext.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Media.Events { - public class MediaDeletingContext : MediaContextBase - { - } + public class MediaDeletingContext : MediaContextBase { } } diff --git a/src/OrchardCore/OrchardCore.Media.Abstractions/IChunkFileUploadService.cs b/src/OrchardCore/OrchardCore.Media.Abstractions/IChunkFileUploadService.cs index fddd1db26a7..c28062feddc 100644 --- a/src/OrchardCore/OrchardCore.Media.Abstractions/IChunkFileUploadService.cs +++ b/src/OrchardCore/OrchardCore.Media.Abstractions/IChunkFileUploadService.cs @@ -24,7 +24,8 @@ public interface IChunkFileUploadService Task ProcessRequestAsync( HttpRequest request, Func> chunkAsync, - Func, Task> completedAsync); + Func, Task> completedAsync + ); /// /// Purges temporary files left by abandoned uploads from the temporary directory. diff --git a/src/OrchardCore/OrchardCore.Media.Abstractions/IMediaFileProvider.cs b/src/OrchardCore/OrchardCore.Media.Abstractions/IMediaFileProvider.cs index 45a95de47b3..7ff36bacc4d 100644 --- a/src/OrchardCore/OrchardCore.Media.Abstractions/IMediaFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Media.Abstractions/IMediaFileProvider.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Media { - public interface IMediaFileProvider : IStaticFileProvider, IVirtualPathBaseProvider - { - } + public interface IMediaFileProvider : IStaticFileProvider, IVirtualPathBaseProvider { } } diff --git a/src/OrchardCore/OrchardCore.Media.Abstractions/IMediaFileStoreCacheFileProvider.cs b/src/OrchardCore/OrchardCore.Media.Abstractions/IMediaFileStoreCacheFileProvider.cs index 763302b3a37..b371a93db9c 100644 --- a/src/OrchardCore/OrchardCore.Media.Abstractions/IMediaFileStoreCacheFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Media.Abstractions/IMediaFileStoreCacheFileProvider.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Media /// /// Identifier for when a file provider serves as a cache provider for a file store. /// - public interface IMediaFileStoreCacheFileProvider : IMediaFileProvider, IMediaFileStoreCache - { - } + public interface IMediaFileStoreCacheFileProvider : IMediaFileProvider, IMediaFileStoreCache { } } diff --git a/src/OrchardCore/OrchardCore.Media.Abstractions/MediaConfigurationException.cs b/src/OrchardCore/OrchardCore.Media.Abstractions/MediaConfigurationException.cs index 66bf9c7114f..ca456c8e9ff 100644 --- a/src/OrchardCore/OrchardCore.Media.Abstractions/MediaConfigurationException.cs +++ b/src/OrchardCore/OrchardCore.Media.Abstractions/MediaConfigurationException.cs @@ -4,11 +4,9 @@ namespace OrchardCore.Media; public class MediaConfigurationException : Exception { - public MediaConfigurationException(string message) : base(message) - { - } + public MediaConfigurationException(string message) + : base(message) { } - public MediaConfigurationException(string message, Exception innerException) : base(message, innerException) - { - } + public MediaConfigurationException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStore.cs b/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStore.cs index 56283cbf9c2..df18729f47f 100644 --- a/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStore.cs +++ b/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStore.cs @@ -32,7 +32,7 @@ public DefaultMediaFileStore( IEnumerable mediaEventHandlers, IEnumerable mediaCreatingEventHandlers, ILogger logger - ) + ) { _fileStore = fileStore; @@ -69,20 +69,13 @@ public virtual Task TryCreateDirectoryAsync(string path) public virtual async Task TryDeleteFileAsync(string path) { - var deletingContext = new MediaDeletingContext - { - Path = path - }; + var deletingContext = new MediaDeletingContext { Path = path }; await _mediaEventHandlers.InvokeAsync((handler, context) => handler.MediaDeletingFileAsync(context), deletingContext, _logger); var result = await _fileStore.TryDeleteFileAsync(deletingContext.Path); - var deletedContext = new MediaDeletedContext - { - Path = path, - Result = result - }; + var deletedContext = new MediaDeletedContext { Path = path, Result = result }; await _mediaEventHandlers.InvokeAsync((handler, deletedContext) => handler.MediaDeletedFileAsync(deletedContext), deletedContext, _logger); @@ -91,20 +84,13 @@ public virtual async Task TryDeleteFileAsync(string path) public virtual async Task TryDeleteDirectoryAsync(string path) { - var deletingContext = new MediaDeletingContext - { - Path = path - }; + var deletingContext = new MediaDeletingContext { Path = path }; await _mediaEventHandlers.InvokeAsync((handler, context) => handler.MediaDeletingDirectoryAsync(context), deletingContext, _logger); var result = await _fileStore.TryDeleteDirectoryAsync(path); - var deletedContext = new MediaDeletedContext - { - Path = path, - Result = result - }; + var deletedContext = new MediaDeletedContext { Path = path, Result = result }; await _mediaEventHandlers.InvokeAsync((handler, deletedContext) => handler.MediaDeletedDirectoryAsync(deletedContext), deletedContext, _logger); @@ -113,11 +99,7 @@ public virtual async Task TryDeleteDirectoryAsync(string path) public virtual async Task MoveFileAsync(string oldPath, string newPath) { - var context = new MediaMoveContext - { - OldPath = oldPath, - NewPath = newPath - }; + var context = new MediaMoveContext { OldPath = oldPath, NewPath = newPath }; await _mediaEventHandlers.InvokeAsync((handler, context) => handler.MediaMovingAsync(context), context, _logger); @@ -150,10 +132,7 @@ public virtual async Task CreateFileFromStreamAsync(string path, Stream var outputStream = inputStream; try { - var context = new MediaCreatingContext - { - Path = path - }; + var context = new MediaCreatingContext { Path = path }; foreach (var mediaCreatingEventHandler in _mediaCreatingEventHandlers) { diff --git a/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStoreCacheFileProvider.cs b/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStoreCacheFileProvider.cs index 69dd8dbb5bc..475fd9ffa46 100644 --- a/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStoreCacheFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStoreCacheFileProvider.cs @@ -23,13 +23,15 @@ public class DefaultMediaFileStoreCacheFileProvider : PhysicalFileProvider, IMed private readonly ILogger _logger; - public DefaultMediaFileStoreCacheFileProvider(ILogger logger, PathString virtualPathBase, string root) : base(root) + public DefaultMediaFileStoreCacheFileProvider(ILogger logger, PathString virtualPathBase, string root) + : base(root) { _logger = logger; VirtualPathBase = virtualPathBase; } - public DefaultMediaFileStoreCacheFileProvider(ILogger logger, PathString virtualPathBase, string root, ExclusionFilters filters) : base(root, filters) + public DefaultMediaFileStoreCacheFileProvider(ILogger logger, PathString virtualPathBase, string root, ExclusionFilters filters) + : base(root, filters) { _logger = logger; VirtualPathBase = virtualPathBase; diff --git a/src/OrchardCore/OrchardCore.Media.Core/Services/MediaSizeLimitAttribute.cs b/src/OrchardCore/OrchardCore.Media.Core/Services/MediaSizeLimitAttribute.cs index ba1414cb3ef..2215cc4a950 100644 --- a/src/OrchardCore/OrchardCore.Media.Core/Services/MediaSizeLimitAttribute.cs +++ b/src/OrchardCore/OrchardCore.Media.Core/Services/MediaSizeLimitAttribute.cs @@ -45,10 +45,7 @@ public void OnAuthorization(AuthorizationFilterContext context) if (formFeature == null || formFeature.Form == null) { // Request form has not been read yet, so set the limits - var formOptions = new FormOptions - { - MultipartBodyLengthLimit = _maxFileSize - }; + var formOptions = new FormOptions { MultipartBodyLengthLimit = _maxFileSize }; features.Set(new FormFeature(context.HttpContext.Request, formOptions)); } diff --git a/src/OrchardCore/OrchardCore.MetaWeblog.Abstractions/MetaWeblogDriver.cs b/src/OrchardCore/OrchardCore.MetaWeblog.Abstractions/MetaWeblogDriver.cs index 329ff47da1b..1972bd17127 100644 --- a/src/OrchardCore/OrchardCore.MetaWeblog.Abstractions/MetaWeblogDriver.cs +++ b/src/OrchardCore/OrchardCore.MetaWeblog.Abstractions/MetaWeblogDriver.cs @@ -7,16 +7,10 @@ namespace OrchardCore.MetaWeblog { public abstract class MetaWeblogDriver : IMetaWeblogDriver { - public virtual void BuildPost(XRpcStruct rpcStruct, XmlRpcContext context, ContentItem contentItem) - { - } + public virtual void BuildPost(XRpcStruct rpcStruct, XmlRpcContext context, ContentItem contentItem) { } - public virtual void EditPost(XRpcStruct rpcStruct, ContentItem contentItem) - { - } + public virtual void EditPost(XRpcStruct rpcStruct, ContentItem contentItem) { } - public virtual void SetCapabilities(Action setCapability) - { - } + public virtual void SetCapabilities(Action setCapability) { } } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/DevelopmentViewsFeature.cs b/src/OrchardCore/OrchardCore.Mvc.Core/DevelopmentViewsFeature.cs index 28e9cd32050..5fb237c651d 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/DevelopmentViewsFeature.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/DevelopmentViewsFeature.cs @@ -2,7 +2,5 @@ namespace OrchardCore.Mvc { - public class DevelopmentViewsFeature : ViewsFeature - { - } + public class DevelopmentViewsFeature : ViewsFeature { } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/Extensions/ControllerExtensions.cs b/src/OrchardCore/OrchardCore.Mvc.Core/Extensions/ControllerExtensions.cs index a69afabaaf9..0b4b074d830 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/Extensions/ControllerExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/Extensions/ControllerExtensions.cs @@ -12,8 +12,8 @@ public static class ControllerExtensions /// /// /// The proper actionresult based upon if the user is authenticated. - public static ActionResult ChallengeOrForbid(this Controller controller) - => controller.User?.Identity?.IsAuthenticated ?? false ? (ActionResult)controller.Forbid() : controller.Challenge(); + public static ActionResult ChallengeOrForbid(this Controller controller) => + controller.User?.Identity?.IsAuthenticated ?? false ? (ActionResult)controller.Forbid() : controller.Challenge(); /// /// Returns the proper actionresult for unauthorized or unauthenticated users @@ -25,16 +25,15 @@ public static ActionResult ChallengeOrForbid(this Controller controller) /// /// The authentication schemes to challenge. /// The proper actionresult based upon if the user is authenticated. - public static ActionResult ChallengeOrForbid(this Controller controller, params string[] authenticationSchemes) - => controller.User?.Identity?.IsAuthenticated ?? false ? (ActionResult)controller.Forbid(authenticationSchemes) : controller.Challenge(authenticationSchemes); + public static ActionResult ChallengeOrForbid(this Controller controller, params string[] authenticationSchemes) => + controller.User?.Identity?.IsAuthenticated ?? false ? (ActionResult)controller.Forbid(authenticationSchemes) : controller.Challenge(authenticationSchemes); /// /// Creates that produces a response. /// /// The . /// An optional value to set on . - public static ActionResult InternalServerError(this Controller controller, object value = null) - => controller.StatusCode((int)HttpStatusCode.InternalServerError, value); + public static ActionResult InternalServerError(this Controller controller, object value = null) => controller.StatusCode((int)HttpStatusCode.InternalServerError, value); /// /// Creates a object that redirects to the specified local localUrl. @@ -52,7 +51,6 @@ public static ActionResult LocalRedirect(this Controller controller, string loca return controller.LocalRedirect(localUrl.ToUriComponents()); } - /// /// Creates a object that redirects to the specified url. /// diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/Extensions/OrchardCoreBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Mvc.Core/Extensions/OrchardCoreBuilderExtensions.cs index aec445b493c..884c183845c 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/Extensions/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/Extensions/OrchardCoreBuilderExtensions.cs @@ -11,13 +11,15 @@ public static class OrchardCoreBuilderExtensions /// public static OrchardCoreBuilder AddMvc(this OrchardCoreBuilder builder) { - builder.ConfigureServices(collection => - { - // Allows a tenant to add its own route endpoint schemes for link generation. - collection.AddSingleton, ShellRouteValuesAddressScheme>(); - }, - // Need to be registered last. - order: int.MaxValue - 100); + builder.ConfigureServices( + collection => + { + // Allows a tenant to add its own route endpoint schemes for link generation. + collection.AddSingleton, ShellRouteValuesAddressScheme>(); + }, + // Need to be registered last. + order: int.MaxValue - 100 + ); return builder.RegisterStartup(); } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/FileProviders/FileProviderExtensions.cs b/src/OrchardCore/OrchardCore.Mvc.Core/FileProviders/FileProviderExtensions.cs index 5d398ffebf6..508f355e172 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/FileProviders/FileProviderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/FileProviders/FileProviderExtensions.cs @@ -8,12 +8,14 @@ namespace OrchardCore.Mvc.FileProviders { public static class FileProviderExtensions { - public static IEnumerable GetViewFilePaths(this IFileProvider fileProvider, + public static IEnumerable GetViewFilePaths( + this IFileProvider fileProvider, string subPath, string[] extensions, string viewsFolder = null, bool inViewsFolder = false, - bool inDepth = true) + bool inDepth = true + ) { var contents = fileProvider.GetDirectoryContents(subPath); diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/ComponentViewLocationExpanderProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/ComponentViewLocationExpanderProvider.cs index 26f672bc538..320d4c2cd78 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/ComponentViewLocationExpanderProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/ComponentViewLocationExpanderProvider.cs @@ -28,7 +28,8 @@ public ComponentViewLocationExpanderProvider( RazorCompilationFileProviderAccessor fileProviderAccessor, IExtensionManager extensionManager, ShellDescriptor shellDescriptor, - IMemoryCache memoryCache) + IMemoryCache memoryCache + ) { _extensionManager = extensionManager; _shellDescriptor = shellDescriptor; @@ -46,15 +47,17 @@ public ComponentViewLocationExpanderProvider( var modulesWithComponentViews = new List(); var modulesWithPagesComponentViews = new List(); - var orderedModules = _extensionManager.GetExtensions() - .Where(e => e.Manifest.Type.Equals("module", StringComparison.OrdinalIgnoreCase)) - .Reverse(); + var orderedModules = _extensionManager.GetExtensions().Where(e => e.Manifest.Type.Equals("module", StringComparison.OrdinalIgnoreCase)).Reverse(); foreach (var module in orderedModules) { var moduleComponentsViewFilePaths = fileProviderAccessor.FileProvider.GetViewFilePaths( - module.SubPath + "/Views/Shared/Components", _razorExtensions, - viewsFolder: null, inViewsFolder: true, inDepth: true); + module.SubPath + "/Views/Shared/Components", + _razorExtensions, + viewsFolder: null, + inViewsFolder: true, + inDepth: true + ); if (moduleComponentsViewFilePaths.Any()) { @@ -62,8 +65,12 @@ public ComponentViewLocationExpanderProvider( } var modulePagesComponentsViewFilePaths = fileProviderAccessor.FileProvider.GetViewFilePaths( - module.SubPath + "/Pages/Shared/Components", _razorExtensions, - viewsFolder: null, inViewsFolder: true, inDepth: true); + module.SubPath + "/Pages/Shared/Components", + _razorExtensions, + viewsFolder: null, + inViewsFolder: true, + inDepth: true + ); if (modulePagesComponentsViewFilePaths.Any()) { @@ -82,13 +89,10 @@ public ComponentViewLocationExpanderProvider( public int Priority => 5; /// - public void PopulateValues(ViewLocationExpanderContext context) - { - } + public void PopulateValues(ViewLocationExpanderContext context) { } /// - public virtual IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, - IEnumerable viewLocations) + public virtual IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable viewLocations) { if (context.AreaName == null) { @@ -101,21 +105,14 @@ public virtual IEnumerable ExpandViewLocations(ViewLocationExpanderConte { if (!_memoryCache.TryGetValue(CacheKey, out string[] moduleComponentViewLocations)) { - var enabledIds = _extensionManager.GetFeatures().Where(f => _shellDescriptor - .Features.Any(sf => sf.Id == f.Id)).Select(f => f.Extension.Id).ToHashSet(); + var enabledIds = _extensionManager.GetFeatures().Where(f => _shellDescriptor.Features.Any(sf => sf.Id == f.Id)).Select(f => f.Extension.Id).ToHashSet(); - var enabledExtensionIds = _extensionManager - .GetExtensions() - .Where(e => enabledIds.Contains(e.Id)) - .Select(x => x.Id) - .ToHashSet(); + var enabledExtensionIds = _extensionManager.GetExtensions().Where(e => enabledIds.Contains(e.Id)).Select(x => x.Id).ToHashSet(); moduleComponentViewLocations = _modulesWithComponentViews .Where(m => enabledExtensionIds.Contains(m.Id)) .Select(m => '/' + m.SubPath + _sharedViewsPath) - .Concat(_modulesWithPagesComponentViews - .Where(m => enabledExtensionIds.Contains(m.Id)) - .Select(m => '/' + m.SubPath + _sharedPagesPath)) + .Concat(_modulesWithPagesComponentViews.Where(m => enabledExtensionIds.Contains(m.Id)).Select(m => '/' + m.SubPath + _sharedPagesPath)) .ToArray(); _memoryCache.Set(CacheKey, moduleComponentViewLocations); diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/CompositeViewLocationExpanderProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/CompositeViewLocationExpanderProvider.cs index 8518c6fc4cd..74bfd59fd14 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/CompositeViewLocationExpanderProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/CompositeViewLocationExpanderProvider.cs @@ -37,11 +37,7 @@ public void PopulateValues(ViewLocationExpanderContext context) private static IEnumerable DiscoverProviders(ViewLocationExpanderContext context) { - return context - .ActionContext - .HttpContext - .RequestServices - .GetServices(); + return context.ActionContext.HttpContext.RequestServices.GetServices(); } } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/SharedViewLocationExpanderProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/SharedViewLocationExpanderProvider.cs index 859a119c5be..dcec5e31a1e 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/SharedViewLocationExpanderProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/SharedViewLocationExpanderProvider.cs @@ -29,7 +29,8 @@ public SharedViewLocationExpanderProvider( RazorCompilationFileProviderAccessor fileProviderAccessor, IExtensionManager extensionManager, ShellDescriptor shellDescriptor, - IMemoryCache memoryCache) + IMemoryCache memoryCache + ) { _extensionManager = extensionManager; _shellDescriptor = shellDescriptor; @@ -44,9 +45,7 @@ public SharedViewLocationExpanderProvider( { if (_modulesWithSharedViews == null) { - var orderedModules = _extensionManager.GetExtensions() - .Where(e => e.Manifest.Type.Equals("module", StringComparison.OrdinalIgnoreCase)) - .Reverse(); + var orderedModules = _extensionManager.GetExtensions().Where(e => e.Manifest.Type.Equals("module", StringComparison.OrdinalIgnoreCase)).Reverse(); var modulesWithPageSharedViews = new List(); var modulesWithSharedViews = new List(); @@ -54,8 +53,12 @@ public SharedViewLocationExpanderProvider( foreach (var module in orderedModules) { var modulePageSharedViewFilePaths = fileProviderAccessor.FileProvider.GetViewFilePaths( - module.SubPath + "/Pages/Shared", _razorExtensions, - viewsFolder: null, inViewsFolder: true, inDepth: true); + module.SubPath + "/Pages/Shared", + _razorExtensions, + viewsFolder: null, + inViewsFolder: true, + inDepth: true + ); if (modulePageSharedViewFilePaths.Any()) { @@ -63,8 +66,12 @@ public SharedViewLocationExpanderProvider( } var moduleSharedViewFilePaths = fileProviderAccessor.FileProvider.GetViewFilePaths( - module.SubPath + "/Views/Shared", _razorExtensions, - viewsFolder: null, inViewsFolder: true, inDepth: true); + module.SubPath + "/Views/Shared", + _razorExtensions, + viewsFolder: null, + inViewsFolder: true, + inDepth: true + ); if (moduleSharedViewFilePaths.Any()) { @@ -81,13 +88,10 @@ public SharedViewLocationExpanderProvider( public int Priority => 5; /// - public void PopulateValues(ViewLocationExpanderContext context) - { - } + public void PopulateValues(ViewLocationExpanderContext context) { } /// - public virtual IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, - IEnumerable viewLocations) + public virtual IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable viewLocations) { if (context.AreaName == null) { @@ -114,9 +118,7 @@ public virtual IEnumerable ExpandViewLocations(ViewLocationExpanderConte if (!_memoryCache.TryGetValue(CacheKey, out IEnumerable moduleSharedViewLocations)) { - moduleSharedViewLocations = _modulesWithSharedViews - .Where(m => GetEnabledExtensionIds().Contains(m.Id)) - .Select(m => '/' + m.SubPath + _sharedViewsPath); + moduleSharedViewLocations = _modulesWithSharedViews.Where(m => GetEnabledExtensionIds().Contains(m.Id)).Select(m => '/' + m.SubPath + _sharedViewsPath); _memoryCache.Set(CacheKey, moduleSharedViewLocations); } @@ -133,11 +135,9 @@ HashSet GetEnabledExtensionIds() return enabledExtensionIds; } - var enabledIds = _extensionManager.GetFeatures().Where(f => _shellDescriptor - .Features.Any(sf => sf.Id == f.Id)).Select(f => f.Extension.Id).ToHashSet(); + var enabledIds = _extensionManager.GetFeatures().Where(f => _shellDescriptor.Features.Any(sf => sf.Id == f.Id)).Select(f => f.Extension.Id).ToHashSet(); - return enabledExtensionIds = _extensionManager.GetExtensions() - .Where(e => enabledIds.Contains(e.Id)).Select(x => x.Id).ToHashSet(); + return enabledExtensionIds = _extensionManager.GetExtensions().Where(e => enabledIds.Contains(e.Id)).Select(x => x.Id).ToHashSet(); } } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ModularApplicationModelProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ModularApplicationModelProvider.cs index 4a5946af9b2..b6aec4c6b4c 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ModularApplicationModelProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ModularApplicationModelProvider.cs @@ -15,10 +15,7 @@ public class ModularApplicationModelProvider : IApplicationModelProvider private readonly IHostEnvironment _hostingEnvironment; private readonly ShellSettings _shellSettings; - public ModularApplicationModelProvider( - ITypeFeatureProvider typeFeatureProvider, - IHostEnvironment hostingEnvironment, - ShellSettings shellSettings) + public ModularApplicationModelProvider(ITypeFeatureProvider typeFeatureProvider, IHostEnvironment hostingEnvironment, ShellSettings shellSettings) { _typeFeatureProvider = typeFeatureProvider; _hostingEnvironment = hostingEnvironment; @@ -27,10 +24,7 @@ public ModularApplicationModelProvider( public int Order { - get - { - return 1000; - } + get { return 1000; } } public void OnProvidersExecuted(ApplicationModelProviderContext context) @@ -65,8 +59,6 @@ public void OnProvidersExecuted(ApplicationModelProviderContext context) } } - public void OnProvidersExecuting(ApplicationModelProviderContext context) - { - } + public void OnProvidersExecuting(ApplicationModelProviderContext context) { } } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ModularRazorViewEngineOptionsSetup.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ModularRazorViewEngineOptionsSetup.cs index fcb3e7c4dde..24aae91c80b 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ModularRazorViewEngineOptionsSetup.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ModularRazorViewEngineOptionsSetup.cs @@ -6,9 +6,7 @@ namespace OrchardCore.Mvc { public class ModularRazorViewEngineOptionsSetup : IConfigureOptions { - public ModularRazorViewEngineOptionsSetup() - { - } + public ModularRazorViewEngineOptionsSetup() { } public void Configure(RazorViewEngineOptions options) { diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs index f02f499c934..802fde7bc6a 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs @@ -41,15 +41,13 @@ public ModuleProjectRazorFileProvider(IApplicationContext applicationContext) { // If the module and the application assemblies are not at the same location, // this means that the module is referenced as a package, not as a project in dev. - if (module.Assembly == null || Path.GetDirectoryName(module.Assembly.Location) - != Path.GetDirectoryName(application.Assembly.Location)) + if (module.Assembly == null || Path.GetDirectoryName(module.Assembly.Location) != Path.GetDirectoryName(application.Assembly.Location)) { continue; } // Get module assets which are razor files. - var assets = module.Assets.Where(a => a.ModuleAssetPath - .EndsWith(".cshtml", StringComparison.Ordinal)); + var assets = module.Assets.Where(a => a.ModuleAssetPath.EndsWith(".cshtml", StringComparison.Ordinal)); if (assets.Any()) { @@ -113,9 +111,12 @@ public IDirectoryContents GetDirectoryContents(string subpath) var module = folder[..index]; // Try to get the module project root. - if (_roots.TryGetValue(module, out var root) && + if ( + _roots.TryGetValue(module, out var root) + && // Check for a final or an intermadiate "Pages" segment. - (folder.EndsWith("/Pages", StringComparison.Ordinal) || folder.Contains("/Pages/"))) + (folder.EndsWith("/Pages", StringComparison.Ordinal) || folder.Contains("/Pages/")) + ) { // Resolve the subpath relative to "{ModuleProjectDirectory}". folder = string.Concat(root, folder.AsSpan(module.Length + 1)); @@ -213,7 +214,6 @@ public IChangeToken Watch(string filter) } } } - // The view engine uses a watch on "Pages/**/*.cshtml" but only for razor pages. // So here, we only use file providers for modules which have a "Pages" folder. else if (path.Equals("Pages/**/*.cshtml")) diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageApplicationModelProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageApplicationModelProvider.cs index 36a442a2093..0bc4bd2b666 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageApplicationModelProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageApplicationModelProvider.cs @@ -12,21 +12,15 @@ public class ModularPageApplicationModelProvider : IPageApplicationModelProvider { private readonly ILookup _featureIdsByArea; - public ModularPageApplicationModelProvider( - IExtensionManager extensionManager, - ShellDescriptor shellDescriptor) + public ModularPageApplicationModelProvider(IExtensionManager extensionManager, ShellDescriptor shellDescriptor) { - // Available features by area in the current shell. - _featureIdsByArea = extensionManager.GetFeatures() - .Where(f => shellDescriptor.Features.Any(sf => sf.Id == f.Id)) - .ToLookup(f => f.Extension.Id, f => f.Id); + // Available features by area in the current shell. + _featureIdsByArea = extensionManager.GetFeatures().Where(f => shellDescriptor.Features.Any(sf => sf.Id == f.Id)).ToLookup(f => f.Extension.Id, f => f.Id); } public int Order => -1000 + 10; - public void OnProvidersExecuting(PageApplicationModelProviderContext context) - { - } + public void OnProvidersExecuting(PageApplicationModelProviderContext context) { } // Called the 1st time a page is requested or if any page has been updated. public void OnProvidersExecuted(PageApplicationModelProviderContext context) diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageMvcCoreBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageMvcCoreBuilderExtensions.cs index 479b26648e0..9db60df93ea 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageMvcCoreBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageMvcCoreBuilderExtensions.cs @@ -20,11 +20,9 @@ internal static IServiceCollection AddModularRazorPages(this IServiceCollection { services.TryAddEnumerable(ServiceDescriptor.Singleton()); - services.TryAddEnumerable( - ServiceDescriptor.Transient, ModularPageRazorPagesOptionsSetup>()); + services.TryAddEnumerable(ServiceDescriptor.Transient, ModularPageRazorPagesOptionsSetup>()); - services.TryAddEnumerable( - ServiceDescriptor.Singleton()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); return services; } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageRazorPagesOptionsSetup.cs b/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageRazorPagesOptionsSetup.cs index f8db9613796..78396b9994e 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageRazorPagesOptionsSetup.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageRazorPagesOptionsSetup.cs @@ -25,8 +25,7 @@ public void Configure(RazorPagesOptions options) if (!_shellSettings.IsRunning()) { // Don't serve any page of the application'module which is enabled during a setup. - options.Conventions.AddAreaFolderRouteModelConvention(_applicationContext.Application.Name, "/", - model => model.Selectors.Clear()); + options.Conventions.AddAreaFolderRouteModelConvention(_applicationContext.Application.Name, "/", model => model.Selectors.Clear()); } else { diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/PageConventionCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/PageConventionCollectionExtensions.cs index 7efda4f3c05..50e10708882 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/PageConventionCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/PageConventionCollectionExtensions.cs @@ -12,8 +12,7 @@ public static class PageConventionCollectionExtensions /// Note: Applied to all pages whose razor view file path doesn't contain any '/Admin/' segment /// and whose route model properties doesn't contains an 'Admin' key. /// - public static PageConventionCollection AddAreaFolderRoute(this PageConventionCollection conventions, - string areaName, string folderPath, string folderRoute) + public static PageConventionCollection AddAreaFolderRoute(this PageConventionCollection conventions, string areaName, string folderPath, string folderRoute) { return conventions.AddAreaFolderRouteInternal(areaName, folderPath, folderRoute, isAdmin: false); } @@ -25,54 +24,56 @@ public static PageConventionCollection AddAreaFolderRoute(this PageConventionCol /// Note: Applied to all pages whose razor view file path contains an '/Admin/' segment /// or whose route model properties contains an 'Admin' key. /// - public static PageConventionCollection AddAdminAreaFolderRoute(this PageConventionCollection conventions, - string areaName, string folderPath, string folderRoute) + public static PageConventionCollection AddAdminAreaFolderRoute(this PageConventionCollection conventions, string areaName, string folderPath, string folderRoute) { return conventions.AddAreaFolderRouteInternal(areaName, folderPath, folderRoute, isAdmin: true); } - internal static PageConventionCollection AddAreaFolderRouteInternal(this PageConventionCollection conventions, - string areaName, string folderPath, string folderRoute, bool isAdmin) + internal static PageConventionCollection AddAreaFolderRouteInternal( + this PageConventionCollection conventions, + string areaName, + string folderPath, + string folderRoute, + bool isAdmin + ) { - conventions.AddAreaFolderRouteModelConvention(areaName, folderPath, model => - { - if (isAdmin != (model.ViewEnginePath.Contains("/Admin/") || model.Properties.ContainsKey("Admin"))) + conventions.AddAreaFolderRouteModelConvention( + areaName, + folderPath, + model => { - return; - } - - var areaFolder = areaName + folderPath; + if (isAdmin != (model.ViewEnginePath.Contains("/Admin/") || model.Properties.ContainsKey("Admin"))) + { + return; + } - foreach (var selector in model.Selectors.ToArray()) - { - var route = selector.AttributeRouteModel; + var areaFolder = areaName + folderPath; - if (route.Template.StartsWith(areaFolder, StringComparison.Ordinal) || (route.Template == areaName && folderPath == "/")) + foreach (var selector in model.Selectors.ToArray()) { - route.SuppressLinkGeneration = true; - - string template; + var route = selector.AttributeRouteModel; - if (route.Template == areaName && folderPath == "/") - { - template = folderRoute; - } - else + if (route.Template.StartsWith(areaFolder, StringComparison.Ordinal) || (route.Template == areaName && folderPath == "/")) { - var cleanSubTemplate = route.Template[areaFolder.Length..].TrimStart('/'); - template = AttributeRouteModel.CombineTemplates(folderRoute, cleanSubTemplate); - } + route.SuppressLinkGeneration = true; - model.Selectors.Add(new SelectorModel - { - AttributeRouteModel = new AttributeRouteModel + string template; + + if (route.Template == areaName && folderPath == "/") { - Template = template + template = folderRoute; } - }); + else + { + var cleanSubTemplate = route.Template[areaFolder.Length..].TrimStart('/'); + template = AttributeRouteModel.CombineTemplates(folderRoute, cleanSubTemplate); + } + + model.Selectors.Add(new SelectorModel { AttributeRouteModel = new AttributeRouteModel { Template = template } }); + } } } - }); + ); return conventions; } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/Routing/DefaultAreaControllerRouteMapper.cs b/src/OrchardCore/OrchardCore.Mvc.Core/Routing/DefaultAreaControllerRouteMapper.cs index b0540484154..636fc5c3e65 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/Routing/DefaultAreaControllerRouteMapper.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/Routing/DefaultAreaControllerRouteMapper.cs @@ -13,10 +13,10 @@ public class DefaultAreaControllerRouteMapper : IAreaControllerRouteMapper public bool TryMapAreaControllerRoute(IEndpointRouteBuilder routes, ControllerActionDescriptor descriptor) { routes.MapAreaControllerRoute( - name: descriptor.DisplayName, - areaName: descriptor.RouteValues["area"], - pattern: DefaultAreaPattern.Replace("{action}", descriptor.ActionName), - defaults: new { controller = descriptor.ControllerName, action = descriptor.ActionName } + name: descriptor.DisplayName, + areaName: descriptor.RouteValues["area"], + pattern: DefaultAreaPattern.Replace("{action}", descriptor.ActionName), + defaults: new { controller = descriptor.ControllerName, action = descriptor.ActionName } ); return true; diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/SharedViewCompilerProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/SharedViewCompilerProvider.cs index 77e407fe8b8..fef578c82e9 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/SharedViewCompilerProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/SharedViewCompilerProvider.cs @@ -33,10 +33,7 @@ public IViewCompiler GetCompiler() return _compiler; } - _compiler = _services - .GetServices() - .FirstOrDefault() - .GetCompiler(); + _compiler = _services.GetServices().FirstOrDefault().GetCompiler(); } return _compiler; diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ShellFeatureApplicationPart.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ShellFeatureApplicationPart.cs index 1954505d039..5a3eca29ee5 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ShellFeatureApplicationPart.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ShellFeatureApplicationPart.cs @@ -13,10 +13,7 @@ namespace OrchardCore.Mvc /// /// An backed by an . /// - public class ShellFeatureApplicationPart : - ApplicationPart, - IApplicationPartTypeProvider, - ICompilationReferencesProvider + public class ShellFeatureApplicationPart : ApplicationPart, IApplicationPartTypeProvider, ICompilationReferencesProvider { private static IEnumerable _referencePaths; private static readonly object _synLock = new(); @@ -26,16 +23,11 @@ public class ShellFeatureApplicationPart : /// /// Initalizes a new instance. /// - public ShellFeatureApplicationPart() - { - } + public ShellFeatureApplicationPart() { } public override string Name { - get - { - return nameof(ShellFeatureApplicationPart); - } + get { return nameof(ShellFeatureApplicationPart); } } /// @@ -60,10 +52,7 @@ public IEnumerable Types } } - return _shellBlueprint - .Dependencies.Keys - .Concat(_tagHelpers.SelectMany(p => p.GetTypes())) - .Select(x => x.GetTypeInfo()); + return _shellBlueprint.Dependencies.Keys.Concat(_tagHelpers.SelectMany(p => p.GetTypes())).Select(x => x.GetTypeInfo()); } } @@ -82,8 +71,7 @@ public IEnumerable GetReferencePaths() return _referencePaths; } - _referencePaths = DependencyContext.Default.CompileLibraries - .SelectMany(library => library.ResolveReferencePaths()); + _referencePaths = DependencyContext.Default.CompileLibraries.SelectMany(library => library.ResolveReferencePaths()); } return _referencePaths; diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ShellFileVersionProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ShellFileVersionProvider.cs index 8888d4ca701..cf71fbb5f1e 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ShellFileVersionProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ShellFileVersionProvider.cs @@ -25,14 +25,9 @@ public class ShellFileVersionProvider : IFileVersionProvider private readonly IFileProvider[] _fileProviders; private readonly IMemoryCache _cache; - public ShellFileVersionProvider( - IEnumerable staticFileProviders, - IWebHostEnvironment environment, - IMemoryCache cache) + public ShellFileVersionProvider(IEnumerable staticFileProviders, IWebHostEnvironment environment, IMemoryCache cache) { - _fileProviders = staticFileProviders - .Concat(new[] { environment.WebRootFileProvider }) - .ToArray(); + _fileProviders = staticFileProviders.Concat(new[] { environment.WebRootFileProvider }).ToArray(); _cache = cache; } @@ -84,9 +79,7 @@ public string AddFileVersionToPath(PathString requestPathBase, string path) var fileInfo = fileProvider.GetFileInfo(resolvedPath); // Perform check against requestPathBase. - if (!fileInfo.Exists && - requestPathBase.HasValue && - resolvedPath.StartsWith(requestPathBase.Value, StringComparison.OrdinalIgnoreCase)) + if (!fileInfo.Exists && requestPathBase.HasValue && resolvedPath.StartsWith(requestPathBase.Value, StringComparison.OrdinalIgnoreCase)) { resolvedPath = resolvedPath[requestPathBase.Value.Length..]; cacheEntryOptions.AddExpirationToken(fileProvider.Watch(resolvedPath)); @@ -94,10 +87,12 @@ public string AddFileVersionToPath(PathString requestPathBase, string path) } // Perform check against VirtualPathBase. - if (!fileInfo.Exists && - fileProvider is IVirtualPathBaseProvider virtualPathBaseProvider && - virtualPathBaseProvider.VirtualPathBase.HasValue && - resolvedPath.StartsWith(virtualPathBaseProvider.VirtualPathBase.Value, StringComparison.OrdinalIgnoreCase)) + if ( + !fileInfo.Exists + && fileProvider is IVirtualPathBaseProvider virtualPathBaseProvider + && virtualPathBaseProvider.VirtualPathBase.HasValue + && resolvedPath.StartsWith(virtualPathBaseProvider.VirtualPathBase.Value, StringComparison.OrdinalIgnoreCase) + ) { resolvedPath = resolvedPath[virtualPathBaseProvider.VirtualPathBase.Value.Length..]; cacheEntryOptions.AddExpirationToken(fileProvider.Watch(resolvedPath)); diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ShellViewFeatureProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ShellViewFeatureProvider.cs index 857ec1e46dd..b5339c7cbcb 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ShellViewFeatureProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ShellViewFeatureProvider.cs @@ -84,8 +84,8 @@ public void PopulateFeature(IEnumerable parts, DevelopmentViews private void PopulateFeatureInternal(ViewsFeature feature) { // Retrieve mvc views feature providers but not this one. - var mvcFeatureProviders = _applicationPartManager.FeatureProviders - .OfType>() + var mvcFeatureProviders = _applicationPartManager + .FeatureProviders.OfType>() .Where(p => p.GetType() != typeof(ShellViewFeatureProvider)); var modules = _applicationContext.Application.Modules; diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/Startup.cs b/src/OrchardCore/OrchardCore.Mvc.Core/Startup.cs index 380a760c0c4..95caa5a5904 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/Startup.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/Startup.cs @@ -41,11 +41,7 @@ public Startup(IHostEnvironment hostingEnvironment, IServiceProvider serviceProv public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { - var descriptors = serviceProvider.GetRequiredService() - .ActionDescriptors.Items - .OfType() - .ToArray() - ; + var descriptors = serviceProvider.GetRequiredService().ActionDescriptors.Items.OfType().ToArray(); var mappers = serviceProvider.GetServices().OrderBy(x => x.Order); @@ -97,8 +93,7 @@ public override void ConfigureServices(IServiceCollection services) builder.AddViewLocalization(); builder.AddDataAnnotationsLocalization(); - services.TryAddEnumerable( - ServiceDescriptor.Transient, ModularRazorViewEngineOptionsSetup>()); + services.TryAddEnumerable(ServiceDescriptor.Transient, ModularRazorViewEngineOptionsSetup>()); // Support razor runtime compilation only if in dev mode and if the 'refs' folder exists. var refsFolderExists = Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "refs")); @@ -112,8 +107,7 @@ public override void ConfigureServices(IServiceCollection services) // because the compiler still uses its internal cache to retrieve compiled items. services.AddSingleton(); - services.TryAddEnumerable( - ServiceDescriptor.Transient, RazorCompilationOptionsSetup>()); + services.TryAddEnumerable(ServiceDescriptor.Transient, RazorCompilationOptionsSetup>()); services.AddSingleton(); @@ -139,8 +133,7 @@ internal static void AddMvcModuleCoreServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); - services.TryAddEnumerable( - ServiceDescriptor.Singleton()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); } } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/ControllerTypeExtensions.cs b/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/ControllerTypeExtensions.cs index f47b346c06d..e9bed765032 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/ControllerTypeExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/ControllerTypeExtensions.cs @@ -12,9 +12,7 @@ public static string ControllerName(this Type controllerType) throw new ArgumentException($"The specified type must inherit from '{nameof(Controller)}'", nameof(controllerType)); } - return controllerType.Name.EndsWith(nameof(Controller), StringComparison.OrdinalIgnoreCase) - ? controllerType.Name[..^nameof(Controller).Length] - : controllerType.Name; + return controllerType.Name.EndsWith(nameof(Controller), StringComparison.OrdinalIgnoreCase) ? controllerType.Name[..^nameof(Controller).Length] : controllerType.Name; } } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/StringExtensions.cs b/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/StringExtensions.cs index fcf2247b0a0..4194cd6ed1d 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/StringExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/StringExtensions.cs @@ -110,9 +110,7 @@ public static string HtmlClassify(this string text) public static LocalizedString OrDefault(this string text, LocalizedString defaultValue) { - return string.IsNullOrEmpty(text) - ? defaultValue - : new LocalizedString(null, text); + return string.IsNullOrEmpty(text) ? defaultValue : new LocalizedString(null, text); } public static string RemoveTags(this string html, bool htmlDecode = false) @@ -160,14 +158,12 @@ public static string RemoveTags(this string html, bool htmlDecode = false) public static string ReplaceNewLinesWith(this string text, string replacement) { return string.IsNullOrWhiteSpace(text) - ? string.Empty - : text - .Replace("\r\n", "\r\r") - .Replace("\n", string.Format(replacement, "\r\n")) - .Replace("\r\r", string.Format(replacement, "\r\n")); + ? string.Empty + : text.Replace("\r\n", "\r\r").Replace("\n", string.Format(replacement, "\r\n")).Replace("\r\r", string.Format(replacement, "\r\n")); } private static readonly char[] _validSegmentChars = "/?#[]@\"^{}|`<>\t\r\n\f ".ToCharArray(); + public static bool IsValidUrlSegment(this string segment) { // Valid isegment from rfc3987 - http://tools.ietf.org/html/rfc3987#page-8 @@ -198,10 +194,7 @@ public static string ToSafeName(this string name) } name = RemoveDiacritics(name); - name = name.Strip(c => - !c.IsLetter() - && !char.IsDigit(c) - ); + name = name.Strip(c => !c.IsLetter() && !char.IsDigit(c)); name = name.Trim(); @@ -406,9 +399,7 @@ public static string TrimEnd(this string rough, string trim = "") return null; } - return rough.EndsWith(trim, StringComparison.Ordinal) - ? rough[..^trim.Length] - : rough; + return rough.EndsWith(trim, StringComparison.Ordinal) ? rough[..^trim.Length] : rough; } public static string ReplaceLastOccurrence(this string source, string find, string replace) @@ -465,35 +456,39 @@ public static string ToPascalCase(this string attribute, char upperAfterDelimite } } - var result = string.Create(attribute.Length - delimitersCount, new { attribute, upperAfterDelimiter }, (buffer, state) => - { - var nextIsUpper = true; - var k = 0; - - for (var i = 0; i < state.attribute.Length; i++) + var result = string.Create( + attribute.Length - delimitersCount, + new { attribute, upperAfterDelimiter }, + (buffer, state) => { - var c = state.attribute[i]; + var nextIsUpper = true; + var k = 0; - if (c == state.upperAfterDelimiter) + for (var i = 0; i < state.attribute.Length; i++) { - nextIsUpper = true; - continue; + var c = state.attribute[i]; + + if (c == state.upperAfterDelimiter) + { + nextIsUpper = true; + continue; + } + + if (nextIsUpper) + { + buffer[k] = char.ToUpperInvariant(c); + } + else + { + buffer[k] = c; + } + + nextIsUpper = false; + + k++; } - - if (nextIsUpper) - { - buffer[k] = char.ToUpperInvariant(c); - } - else - { - buffer[k] = c; - } - - nextIsUpper = false; - - k++; } - }); + ); return result; } diff --git a/src/OrchardCore/OrchardCore.Navigation.Core/INavigationProvider.cs b/src/OrchardCore/OrchardCore.Navigation.Core/INavigationProvider.cs index a55648ea5ef..9bb77a2fdc5 100644 --- a/src/OrchardCore/OrchardCore.Navigation.Core/INavigationProvider.cs +++ b/src/OrchardCore/OrchardCore.Navigation.Core/INavigationProvider.cs @@ -1,7 +1,6 @@ using System.Threading.Tasks; namespace OrchardCore.Navigation - { public interface INavigationProvider { diff --git a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationBuilder.cs b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationBuilder.cs index 1d6bc5350c5..1a7c3ed4683 100644 --- a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationBuilder.cs +++ b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationBuilder.cs @@ -15,7 +15,13 @@ public NavigationBuilder() Contained = []; } - public async Task AddAsync(LocalizedString caption, string position, Func itemBuilder, IEnumerable classes = null, int priority = 0) + public async Task AddAsync( + LocalizedString caption, + string position, + Func itemBuilder, + IEnumerable classes = null, + int priority = 0 + ) { var childBuilder = new NavigationItemBuilder(); @@ -61,6 +67,7 @@ public Task AddAsync(LocalizedString caption, Func AddAsync(Func itemBuilder, IEnumerable classes = null) { return AddAsync(new LocalizedString(null, null), null, itemBuilder, classes); @@ -70,6 +77,7 @@ public NavigationBuilder Add(LocalizedString caption, Action itemBuilder, IEnumerable classes = null) { return Add(new LocalizedString(null, null), null, itemBuilder, classes); @@ -79,6 +87,7 @@ public NavigationBuilder Add(LocalizedString caption, string position, IEnumerab { return Add(caption, position, x => { }, classes); } + public NavigationBuilder Add(LocalizedString caption, IEnumerable classes = null) { return Add(caption, null, x => { }, classes); diff --git a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationHelper.cs b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationHelper.cs index 598341f1726..9c774b316d4 100644 --- a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationHelper.cs +++ b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationHelper.cs @@ -14,8 +14,7 @@ public class NavigationHelper /// /// /// boolean. - public static bool IsAdminMenu(string name) - => NavigationConstants.AdminId == name; + public static bool IsAdminMenu(string name) => NavigationConstants.AdminId == name; /// /// Populates the menu shapes. diff --git a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationItemBuilder.cs b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationItemBuilder.cs index 22b47ca9ce2..650db30396a 100644 --- a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationItemBuilder.cs +++ b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationItemBuilder.cs @@ -119,9 +119,7 @@ public override List Build() public NavigationItemBuilder Action(RouteValueDictionary values) { - return values != null - ? Action(values["action"] as string, values["controller"] as string, values) - : Action(null, null, new RouteValueDictionary()); + return values != null ? Action(values["action"] as string, values["controller"] as string, values) : Action(null, null, new RouteValueDictionary()); } public NavigationItemBuilder Action(string actionName) diff --git a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs index a810d5767cb..9d568e379c8 100644 --- a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs +++ b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs @@ -27,7 +27,8 @@ public NavigationManager( ILogger logger, ShellSettings shellSettings, IUrlHelperFactory urlHelperFactory, - IAuthorizationService authorizationService) + IAuthorizationService authorizationService + ) { _navigationProviders = navigationProviders; _logger = logger; diff --git a/src/OrchardCore/OrchardCore.Navigation.Core/Pager.cs b/src/OrchardCore/OrchardCore.Navigation.Core/Pager.cs index ffa2c9dd057..6dc794b109b 100644 --- a/src/OrchardCore/OrchardCore.Navigation.Core/Pager.cs +++ b/src/OrchardCore/OrchardCore.Navigation.Core/Pager.cs @@ -13,9 +13,7 @@ public class Pager /// The pager parameters. /// The default page size. public Pager(PagerParameters pagerParameters, int defaultPageSize) - : this(pagerParameters.Page, pagerParameters.PageSize, defaultPageSize) - { - } + : this(pagerParameters.Page, pagerParameters.PageSize, defaultPageSize) { } /// /// Constructs a new pager. diff --git a/src/OrchardCore/OrchardCore.Navigation.Core/PagerSlim.cs b/src/OrchardCore/OrchardCore.Navigation.Core/PagerSlim.cs index 881737333ca..d3c10ba1448 100644 --- a/src/OrchardCore/OrchardCore.Navigation.Core/PagerSlim.cs +++ b/src/OrchardCore/OrchardCore.Navigation.Core/PagerSlim.cs @@ -8,9 +8,7 @@ public class PagerSlim /// The pager parameters. /// The page size parameter. public PagerSlim(PagerSlimParameters pagerParameters, int pageSize) - : this(pagerParameters.Before, pagerParameters.After, pageSize) - { - } + : this(pagerParameters.Before, pagerParameters.After, pageSize) { } /// /// Constructs a new pager. diff --git a/src/OrchardCore/OrchardCore.Navigation.Core/ShapeFactoryExtensions.cs b/src/OrchardCore/OrchardCore.Navigation.Core/ShapeFactoryExtensions.cs index 62c08f92a77..20d0c305a28 100644 --- a/src/OrchardCore/OrchardCore.Navigation.Core/ShapeFactoryExtensions.cs +++ b/src/OrchardCore/OrchardCore.Navigation.Core/ShapeFactoryExtensions.cs @@ -7,13 +7,18 @@ namespace OrchardCore.DisplayManagement; public static class ShapeFactoryExtensions { - public static ValueTask PagerAsync(this IShapeFactory _shapeFactory, Pager pager, int totalItemCount) - => _shapeFactory.CreateAsync("Pager", Arguments.From(new - { - pager.Page, - pager.PageSize, - TotalItemCount = totalItemCount, - })); + public static ValueTask PagerAsync(this IShapeFactory _shapeFactory, Pager pager, int totalItemCount) => + _shapeFactory.CreateAsync( + "Pager", + Arguments.From( + new + { + pager.Page, + pager.PageSize, + TotalItemCount = totalItemCount, + } + ) + ); public static async ValueTask PagerAsync(this IShapeFactory _shapeFactory, Pager pager, int totalItemCount, RouteData routeData) { @@ -27,25 +32,35 @@ public static async ValueTask PagerAsync(this IShapeFactory _shapeFactor return pagerShape; } - public static ValueTask PagerAsync(this IShapeFactory _shapeFactory, Pager pager, int totalItemCount, RouteValueDictionary routeValues) - => _shapeFactory.PagerAsync(pager, totalItemCount, routeValues == null ? null : new RouteData(routeValues)); + public static ValueTask PagerAsync(this IShapeFactory _shapeFactory, Pager pager, int totalItemCount, RouteValueDictionary routeValues) => + _shapeFactory.PagerAsync(pager, totalItemCount, routeValues == null ? null : new RouteData(routeValues)); - public static ValueTask PagerSlimAsync(this IShapeFactory _shapeFactory, PagerSlim pager) - => _shapeFactory.CreateAsync("PagerSlim", Arguments.From(new - { - pager.Before, - pager.After, - pager.PageSize, - })); + public static ValueTask PagerSlimAsync(this IShapeFactory _shapeFactory, PagerSlim pager) => + _shapeFactory.CreateAsync( + "PagerSlim", + Arguments.From( + new + { + pager.Before, + pager.After, + pager.PageSize, + } + ) + ); public static async ValueTask PagerSlimAsync(this IShapeFactory _shapeFactory, PagerSlim pager, IDictionary values) { - dynamic shape = await _shapeFactory.CreateAsync("PagerSlim", Arguments.From(new - { - pager.Before, - pager.After, - pager.PageSize, - })); + dynamic shape = await _shapeFactory.CreateAsync( + "PagerSlim", + Arguments.From( + new + { + pager.Before, + pager.After, + pager.PageSize, + } + ) + ); if (values != null && values.Count > 0) { diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/DefaultNotificationsAdminListFilterProvider.cs b/src/OrchardCore/OrchardCore.Notifications.Core/DefaultNotificationsAdminListFilterProvider.cs index 86f0021206a..c1190152e4f 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/DefaultNotificationsAdminListFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/DefaultNotificationsAdminListFilterProvider.cs @@ -17,90 +17,115 @@ public class DefaultNotificationsAdminListFilterProvider : INotificationAdminLis public void Build(QueryEngineBuilder builder) { builder - .WithNamedTerm("status", builder => builder - .OneCondition((val, query, ctx) => - { - if (Enum.TryParse(val, true, out var status)) - { - switch (status) - { - case NotificationStatus.Read: - query.With(x => x.IsRead); - break; - case NotificationStatus.Unread: - query.With(x => !x.IsRead); - break; - default: - break; - } - } + .WithNamedTerm( + "status", + builder => + builder + .OneCondition( + (val, query, ctx) => + { + if (Enum.TryParse(val, true, out var status)) + { + switch (status) + { + case NotificationStatus.Read: + query.With(x => x.IsRead); + break; + case NotificationStatus.Unread: + query.With(x => !x.IsRead); + break; + default: + break; + } + } - return new ValueTask>(query); - }) - .MapTo((val, model) => - { - if (Enum.TryParse(val, true, out var status)) - { - model.Status = status; - } - }) - .MapFrom((model) => - { - if (model.Status.HasValue) - { - return (true, model.Status.ToString()); - } + return new ValueTask>(query); + } + ) + .MapTo( + (val, model) => + { + if (Enum.TryParse(val, true, out var status)) + { + model.Status = status; + } + } + ) + .MapFrom( + (model) => + { + if (model.Status.HasValue) + { + return (true, model.Status.ToString()); + } - return (false, string.Empty); - }) - .AlwaysRun() - ) - .WithNamedTerm("sort", builder => builder - .OneCondition((val, query, ctx) => - { - if (Enum.TryParse(val, true, out var sort) && sort == NotificationOrder.Oldest) - { - return new ValueTask>(query.With().OrderBy(x => x.CreatedAtUtc)); - } + return (false, string.Empty); + } + ) + .AlwaysRun() + ) + .WithNamedTerm( + "sort", + builder => + builder + .OneCondition( + (val, query, ctx) => + { + if (Enum.TryParse(val, true, out var sort) && sort == NotificationOrder.Oldest) + { + return new ValueTask>(query.With().OrderBy(x => x.CreatedAtUtc)); + } - return new ValueTask>(query.With().OrderByDescending(x => x.CreatedAtUtc)); - }) - .MapTo((val, model) => - { - if (Enum.TryParse(val, true, out var sort)) - { - model.OrderBy = sort; - } - }) - .MapFrom((model) => - { - if (model.OrderBy.HasValue) - { - return (true, model.OrderBy.ToString()); - } + return new ValueTask>(query.With().OrderByDescending(x => x.CreatedAtUtc)); + } + ) + .MapTo( + (val, model) => + { + if (Enum.TryParse(val, true, out var sort)) + { + model.OrderBy = sort; + } + } + ) + .MapFrom( + (model) => + { + if (model.OrderBy.HasValue) + { + return (true, model.OrderBy.ToString()); + } - return (false, string.Empty); - }) - .AlwaysRun() + return (false, string.Empty); + } + ) + .AlwaysRun() ) - .WithDefaultTerm("text", builder => builder - .ManyCondition( + .WithDefaultTerm( + "text", + builder => + builder.ManyCondition( (val, query) => query.With(x => x.Content.Contains(val)), (val, query) => query.With(x => x.Content.NotContains(val)) - ) + ) ) // Always filter by owner to ensure we only query notification that belong to the current user. - .WithDefaultTerm("owner", builder => builder - .OneCondition((val, query, ctx) => - { - var context = (NotificationQueryContext)ctx; - var httpAccessor = context.ServiceProvider.GetRequiredService(); + .WithDefaultTerm( + "owner", + builder => + builder + .OneCondition( + (val, query, ctx) => + { + var context = (NotificationQueryContext)ctx; + var httpAccessor = context.ServiceProvider.GetRequiredService(); - var userId = httpAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); + var userId = httpAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); - return new ValueTask>(query.With(t => t.UserId == userId)); - }) - .AlwaysRun() + return new ValueTask>(query.With(t => t.UserId == userId)); + } + ) + .AlwaysRun() ); } } diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/DefaultNotificationsAdminListQueryService.cs b/src/OrchardCore/OrchardCore.Notifications.Core/DefaultNotificationsAdminListQueryService.cs index a480aa250bf..3a6d9133ce9 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/DefaultNotificationsAdminListQueryService.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/DefaultNotificationsAdminListQueryService.cs @@ -12,9 +12,7 @@ public class DefaultNotificationsAdminListQueryService : INotificationsAdminList private readonly ISession _session; private readonly IServiceProvider _serviceProvider; - public DefaultNotificationsAdminListQueryService( - ISession session, - IServiceProvider serviceProvider) + public DefaultNotificationsAdminListQueryService(ISession session, IServiceProvider serviceProvider) { _session = session; _serviceProvider = serviceProvider; @@ -39,10 +37,6 @@ public async Task QueryAsync(int page, int pageSize, Li query = query.Take(pageSize); } - return new NotificationQueryResult() - { - Notifications = await query.ListAsync(), - TotalCount = totalCount, - }; + return new NotificationQueryResult() { Notifications = await query.ListAsync(), TotalCount = totalCount, }; } } diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/INotificationAdminListFilterParser.cs b/src/OrchardCore/OrchardCore.Notifications.Core/INotificationAdminListFilterParser.cs index 5cd880f6081..59ec96fb0dc 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/INotificationAdminListFilterParser.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/INotificationAdminListFilterParser.cs @@ -2,6 +2,4 @@ namespace OrchardCore.Notifications; -public interface INotificationAdminListFilterParser : IQueryParser -{ -} +public interface INotificationAdminListFilterParser : IQueryParser { } diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs b/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs index 37d132dce40..c525ed178ee 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs @@ -33,7 +33,8 @@ public NotificationIndexProvider() public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(notification => { var content = notification.Summary ?? string.Empty; diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/NotificationPermissions.cs b/src/OrchardCore/OrchardCore.Notifications.Core/NotificationPermissions.cs index 15f1ae244b2..97c95fd6873 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/NotificationPermissions.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/NotificationPermissions.cs @@ -4,5 +4,5 @@ namespace OrchardCore.Notifications; public class NotificationPermissions { - public readonly static Permission ManageNotifications = new("ManageNotifications", "Manage notifications"); + public static readonly Permission ManageNotifications = new("ManageNotifications", "Manage notifications"); } diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/Services/DefaultNotificationAdminListFilterParser.cs b/src/OrchardCore/OrchardCore.Notifications.Core/Services/DefaultNotificationAdminListFilterParser.cs index b117b100790..2e475331a58 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/Services/DefaultNotificationAdminListFilterParser.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/Services/DefaultNotificationAdminListFilterParser.cs @@ -11,6 +11,5 @@ public DefaultNotificationAdminListFilterParser(IQueryParser parse _parser = parser; } - public QueryFilterResult Parse(string text) - => _parser.Parse(text); + public QueryFilterResult Parse(string text) => _parser.Parse(text); } diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/Services/EmailNotificationProvider.cs b/src/OrchardCore/OrchardCore.Notifications.Core/Services/EmailNotificationProvider.cs index 8a3b50e7e91..e32299054bf 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/Services/EmailNotificationProvider.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/Services/EmailNotificationProvider.cs @@ -10,9 +10,7 @@ public class EmailNotificationProvider : INotificationMethodProvider private readonly ISmtpService _smtpService; protected readonly IStringLocalizer S; - public EmailNotificationProvider( - ISmtpService smtpService, - IStringLocalizer stringLocalizer) + public EmailNotificationProvider(ISmtpService smtpService, IStringLocalizer stringLocalizer) { _smtpService = smtpService; S = stringLocalizer; @@ -31,11 +29,7 @@ public async Task TrySendAsync(object notify, INotificationMessage message return false; } - var mailMessage = new MailMessage() - { - To = user.Email, - Subject = message.Summary, - }; + var mailMessage = new MailMessage() { To = user.Email, Subject = message.Summary, }; if (message.IsHtmlPreferred && !string.IsNullOrWhiteSpace(message.HtmlBody)) { diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/Services/NotificationMethodProviderAccessor.cs b/src/OrchardCore/OrchardCore.Notifications.Core/Services/NotificationMethodProviderAccessor.cs index dc0e0f62e8d..ba3ae55a083 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/Services/NotificationMethodProviderAccessor.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/Services/NotificationMethodProviderAccessor.cs @@ -31,11 +31,13 @@ public Task> GetProvidersAsync(object n var methods = _notificationMethodProviders.Where(provider => !optout.Contains(provider.Method)); if (selectedMethods.Count > 0) { - return Task.FromResult>(methods - // Priority matters to honor user preferences. - .OrderBy(provider => selectedMethods.IndexOf(provider.Method)) - .ThenBy(provider => provider.Name.ToString()) - .ToList()); + return Task.FromResult>( + methods + // Priority matters to honor user preferences. + .OrderBy(provider => selectedMethods.IndexOf(provider.Method)) + .ThenBy(provider => provider.Name.ToString()) + .ToList() + ); } return Task.FromResult>(methods.OrderBy(provider => provider.Name.ToString()).ToList()); diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/Services/NotificationService.cs b/src/OrchardCore/OrchardCore.Notifications.Core/Services/NotificationService.cs index c1aa1dfee10..4e2ba59f1be 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/Services/NotificationService.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/Services/NotificationService.cs @@ -14,11 +14,13 @@ public class NotificationService : INotificationService private readonly ISession _session; private readonly IClock _clock; - public NotificationService(INotificationMethodProviderAccessor notificationMethodProviderAccessor, + public NotificationService( + INotificationMethodProviderAccessor notificationMethodProviderAccessor, IEnumerable notificationEvents, ILogger logger, ISession session, - IClock clock) + IClock clock + ) { _notificationMethodProviderAccessor = notificationMethodProviderAccessor; _notificationEvents = notificationEvents; diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdApplicationStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdApplicationStore.cs index 50ce9d5a108..4e50d817b6b 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdApplicationStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdApplicationStore.cs @@ -6,7 +6,8 @@ namespace OrchardCore.OpenId.Abstractions.Stores { - public interface IOpenIdApplicationStore : IOpenIddictApplicationStore where TApplication : class + public interface IOpenIdApplicationStore : IOpenIddictApplicationStore + where TApplication : class { ValueTask FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken); ValueTask GetPhysicalIdAsync(TApplication application, CancellationToken cancellationToken); diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdAuthorizationStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdAuthorizationStore.cs index 52216beb0e5..2c60d6c4751 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdAuthorizationStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdAuthorizationStore.cs @@ -4,7 +4,8 @@ namespace OrchardCore.OpenId.Abstractions.Stores { - public interface IOpenIdAuthorizationStore : IOpenIddictAuthorizationStore where TAuthorization : class + public interface IOpenIdAuthorizationStore : IOpenIddictAuthorizationStore + where TAuthorization : class { ValueTask FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken); ValueTask GetPhysicalIdAsync(TAuthorization authorization, CancellationToken cancellationToken); diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdScopeStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdScopeStore.cs index 0cce5089dd7..dc72f67dd59 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdScopeStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdScopeStore.cs @@ -4,7 +4,8 @@ namespace OrchardCore.OpenId.Abstractions.Stores { - public interface IOpenIdScopeStore : IOpenIddictScopeStore where TScope : class + public interface IOpenIdScopeStore : IOpenIddictScopeStore + where TScope : class { ValueTask FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken); ValueTask GetPhysicalIdAsync(TScope scope, CancellationToken cancellationToken); diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdTokenStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdTokenStore.cs index 292c9930265..a3bc646cd37 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdTokenStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/Abstractions/Stores/IOpenIdTokenStore.cs @@ -4,7 +4,8 @@ namespace OrchardCore.OpenId.Abstractions.Stores { - public interface IOpenIdTokenStore : IOpenIddictTokenStore where TToken : class + public interface IOpenIdTokenStore : IOpenIddictTokenStore + where TToken : class { ValueTask FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken); ValueTask GetPhysicalIdAsync(TToken token, CancellationToken cancellationToken); diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/OpenIdExtensions.cs b/src/OrchardCore/OrchardCore.OpenId.Core/OpenIdExtensions.cs index d42c7d0192d..7e77c42a7b2 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/OpenIdExtensions.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/OpenIdExtensions.cs @@ -20,8 +20,7 @@ public static OpenIddictCoreBuilder AddOrchardMigrations(this OpenIddictCoreBuil { ArgumentNullException.ThrowIfNull(builder); - builder.Services.TryAddEnumerable( - ServiceDescriptor.Scoped()); + builder.Services.TryAddEnumerable(ServiceDescriptor.Scoped()); // Configure support for an OpenId collection. builder.Services.Configure(o => o.Collections.Add("OpenId")); @@ -33,10 +32,11 @@ public static OpenIddictCoreBuilder UseOrchardManagers(this OpenIddictCoreBuilde { ArgumentNullException.ThrowIfNull(builder); - builder.ReplaceApplicationManager(typeof(OpenIdApplicationManager<>)) - .ReplaceAuthorizationManager(typeof(OpenIdAuthorizationManager<>)) - .ReplaceScopeManager(typeof(OpenIdScopeManager<>)) - .ReplaceTokenManager(typeof(OpenIdTokenManager<>)); + builder + .ReplaceApplicationManager(typeof(OpenIdApplicationManager<>)) + .ReplaceAuthorizationManager(typeof(OpenIdAuthorizationManager<>)) + .ReplaceScopeManager(typeof(OpenIdScopeManager<>)) + .ReplaceTokenManager(typeof(OpenIdTokenManager<>)); // Register proxy delegates so that the Orchard managers can be directly // resolved from the DI using the non-generic, Orchard-specific interfaces. @@ -57,15 +57,17 @@ public static OpenIddictCoreBuilder UseYesSql(this OpenIddictCoreBuilder builder // in case case-sensitive stores were registered before this extension was called. builder.Configure(options => options.DisableAdditionalFiltering = false); - builder.SetDefaultApplicationEntity() - .SetDefaultAuthorizationEntity() - .SetDefaultScopeEntity() - .SetDefaultTokenEntity(); + builder + .SetDefaultApplicationEntity() + .SetDefaultAuthorizationEntity() + .SetDefaultScopeEntity() + .SetDefaultTokenEntity(); - builder.ReplaceApplicationStoreResolver() - .ReplaceAuthorizationStoreResolver() - .ReplaceScopeStoreResolver() - .ReplaceTokenStoreResolver(); + builder + .ReplaceApplicationStoreResolver() + .ReplaceAuthorizationStoreResolver() + .ReplaceScopeStoreResolver() + .ReplaceTokenStoreResolver(); builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); @@ -77,13 +79,15 @@ public static OpenIddictCoreBuilder UseYesSql(this OpenIddictCoreBuilder builder builder.Services.TryAddScoped(typeof(OpenIdScopeStore<>)); builder.Services.TryAddScoped(typeof(OpenIdTokenStore<>)); - builder.Services.TryAddEnumerable(new[] - { - ServiceDescriptor.Singleton(), - ServiceDescriptor.Singleton(), - ServiceDescriptor.Singleton(), - ServiceDescriptor.Singleton() - }); + builder.Services.TryAddEnumerable( + new[] + { + ServiceDescriptor.Singleton(), + ServiceDescriptor.Singleton(), + ServiceDescriptor.Singleton(), + ServiceDescriptor.Singleton() + } + ); return builder; } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdApplicationManager.cs b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdApplicationManager.cs index 9d4e052c98f..e3e895fdd06 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdApplicationManager.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdApplicationManager.cs @@ -16,17 +16,16 @@ namespace OrchardCore.OpenId.Services.Managers { - public class OpenIdApplicationManager : OpenIddictApplicationManager, - IOpenIdApplicationManager where TApplication : class + public class OpenIdApplicationManager : OpenIddictApplicationManager, IOpenIdApplicationManager + where TApplication : class { public OpenIdApplicationManager( IOpenIddictApplicationCache cache, ILogger> logger, IOptionsMonitor options, - IOpenIddictApplicationStoreResolver resolver) - : base(cache, logger, options, resolver) - { - } + IOpenIddictApplicationStoreResolver resolver + ) + : base(cache, logger, options, resolver) { } /// /// Retrieves an application using its physical identifier. @@ -44,9 +43,9 @@ public virtual ValueTask FindByPhysicalIdAsync(string identifier, throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } - return Store is IOpenIdApplicationStore store ? - store.FindByPhysicalIdAsync(identifier, cancellationToken) : - Store.FindByIdAsync(identifier, cancellationToken); + return Store is IOpenIdApplicationStore store + ? store.FindByPhysicalIdAsync(identifier, cancellationToken) + : Store.FindByIdAsync(identifier, cancellationToken); } /// @@ -62,13 +61,12 @@ public virtual ValueTask GetPhysicalIdAsync(TApplication application, Ca { ArgumentNullException.ThrowIfNull(application); - return Store is IOpenIdApplicationStore store ? - store.GetPhysicalIdAsync(application, cancellationToken) : - Store.GetIdAsync(application, cancellationToken); + return Store is IOpenIdApplicationStore store + ? store.GetPhysicalIdAsync(application, cancellationToken) + : Store.GetIdAsync(application, cancellationToken); } - public virtual async ValueTask> GetRolesAsync( - TApplication application, CancellationToken cancellationToken = default) + public virtual async ValueTask> GetRolesAsync(TApplication application, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(application); @@ -95,8 +93,7 @@ public virtual async ValueTask> GetRolesAsync( } } - public virtual IAsyncEnumerable ListInRoleAsync( - string role, CancellationToken cancellationToken = default) + public virtual IAsyncEnumerable ListInRoleAsync(string role, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(role)) { @@ -126,8 +123,7 @@ async IAsyncEnumerable ExecuteAsync() } } - public virtual async ValueTask SetRolesAsync(TApplication application, - ImmutableArray roles, CancellationToken cancellationToken = default) + public virtual async ValueTask SetRolesAsync(TApplication application, ImmutableArray roles, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(application); @@ -143,8 +139,7 @@ public virtual async ValueTask SetRolesAsync(TApplication application, else { var properties = await Store.GetPropertiesAsync(application, cancellationToken); - properties = properties.SetItem(OpenIdConstants.Properties.Roles, - JsonSerializer.SerializeToElement(roles, JOptions.UnsafeRelaxedJsonEscaping)); + properties = properties.SetItem(OpenIdConstants.Properties.Roles, JsonSerializer.SerializeToElement(roles, JOptions.UnsafeRelaxedJsonEscaping)); await Store.SetPropertiesAsync(application, properties, cancellationToken); } @@ -152,8 +147,7 @@ public virtual async ValueTask SetRolesAsync(TApplication application, await UpdateAsync(application, cancellationToken); } - public override async ValueTask PopulateAsync(TApplication application, - OpenIddictApplicationDescriptor descriptor, CancellationToken cancellationToken = default) + public override async ValueTask PopulateAsync(TApplication application, OpenIddictApplicationDescriptor descriptor, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(application); @@ -174,16 +168,14 @@ public override async ValueTask PopulateAsync(TApplication application, else { var properties = await Store.GetPropertiesAsync(application, cancellationToken); - properties = properties.SetItem(OpenIdConstants.Properties.Roles, - JsonSerializer.SerializeToElement(model.Roles, JOptions.UnsafeRelaxedJsonEscaping)); + properties = properties.SetItem(OpenIdConstants.Properties.Roles, JsonSerializer.SerializeToElement(model.Roles, JOptions.UnsafeRelaxedJsonEscaping)); await Store.SetPropertiesAsync(application, properties, cancellationToken); } } } - public override async ValueTask PopulateAsync(OpenIddictApplicationDescriptor descriptor, - TApplication application, CancellationToken cancellationToken = default) + public override async ValueTask PopulateAsync(OpenIddictApplicationDescriptor descriptor, TApplication application, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(descriptor); @@ -197,8 +189,7 @@ public override async ValueTask PopulateAsync(OpenIddictApplicationDescriptor de } } - public override IAsyncEnumerable ValidateAsync( - TApplication application, CancellationToken cancellationToken = default) + public override IAsyncEnumerable ValidateAsync(TApplication application, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(application); @@ -223,19 +214,18 @@ async IAsyncEnumerable ExecuteAsync() } } - async ValueTask IOpenIdApplicationManager.FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) - => await FindByPhysicalIdAsync(identifier, cancellationToken); + async ValueTask IOpenIdApplicationManager.FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) => + await FindByPhysicalIdAsync(identifier, cancellationToken); - ValueTask IOpenIdApplicationManager.GetPhysicalIdAsync(object application, CancellationToken cancellationToken) - => GetPhysicalIdAsync((TApplication)application, cancellationToken); + ValueTask IOpenIdApplicationManager.GetPhysicalIdAsync(object application, CancellationToken cancellationToken) => + GetPhysicalIdAsync((TApplication)application, cancellationToken); - ValueTask> IOpenIdApplicationManager.GetRolesAsync(object application, CancellationToken cancellationToken) - => GetRolesAsync((TApplication)application, cancellationToken); + ValueTask> IOpenIdApplicationManager.GetRolesAsync(object application, CancellationToken cancellationToken) => + GetRolesAsync((TApplication)application, cancellationToken); - IAsyncEnumerable IOpenIdApplicationManager.ListInRoleAsync(string role, CancellationToken cancellationToken) - => ListInRoleAsync(role, cancellationToken); + IAsyncEnumerable IOpenIdApplicationManager.ListInRoleAsync(string role, CancellationToken cancellationToken) => ListInRoleAsync(role, cancellationToken); - ValueTask IOpenIdApplicationManager.SetRolesAsync(object application, ImmutableArray roles, CancellationToken cancellationToken) - => SetRolesAsync((TApplication)application, roles, cancellationToken); + ValueTask IOpenIdApplicationManager.SetRolesAsync(object application, ImmutableArray roles, CancellationToken cancellationToken) => + SetRolesAsync((TApplication)application, roles, cancellationToken); } } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdAuthorizationManager.cs b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdAuthorizationManager.cs index 6c6e567f289..2771528f791 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdAuthorizationManager.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdAuthorizationManager.cs @@ -10,17 +10,16 @@ namespace OrchardCore.OpenId.Services.Managers { - public class OpenIdAuthorizationManager : OpenIddictAuthorizationManager, - IOpenIdAuthorizationManager where TAuthorization : class + public class OpenIdAuthorizationManager : OpenIddictAuthorizationManager, IOpenIdAuthorizationManager + where TAuthorization : class { public OpenIdAuthorizationManager( IOpenIddictAuthorizationCache cache, ILogger> logger, IOptionsMonitor options, - IOpenIddictAuthorizationStoreResolver resolver) - : base(cache, logger, options, resolver) - { - } + IOpenIddictAuthorizationStoreResolver resolver + ) + : base(cache, logger, options, resolver) { } /// /// Retrieves an authorization using its physical identifier. @@ -38,9 +37,9 @@ public virtual ValueTask FindByPhysicalIdAsync(string identifier throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } - return Store is IOpenIdApplicationStore store ? - store.FindByPhysicalIdAsync(identifier, cancellationToken) : - Store.FindByIdAsync(identifier, cancellationToken); + return Store is IOpenIdApplicationStore store + ? store.FindByPhysicalIdAsync(identifier, cancellationToken) + : Store.FindByIdAsync(identifier, cancellationToken); } /// @@ -56,15 +55,15 @@ public virtual ValueTask GetPhysicalIdAsync(TAuthorization authorization { ArgumentNullException.ThrowIfNull(authorization); - return Store is IOpenIdAuthorizationStore store ? - store.GetPhysicalIdAsync(authorization, cancellationToken) : - Store.GetIdAsync(authorization, cancellationToken); + return Store is IOpenIdAuthorizationStore store + ? store.GetPhysicalIdAsync(authorization, cancellationToken) + : Store.GetIdAsync(authorization, cancellationToken); } - async ValueTask IOpenIdAuthorizationManager.FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) - => await FindByPhysicalIdAsync(identifier, cancellationToken); + async ValueTask IOpenIdAuthorizationManager.FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) => + await FindByPhysicalIdAsync(identifier, cancellationToken); - ValueTask IOpenIdAuthorizationManager.GetPhysicalIdAsync(object authorization, CancellationToken cancellationToken) - => GetPhysicalIdAsync((TAuthorization)authorization, cancellationToken); + ValueTask IOpenIdAuthorizationManager.GetPhysicalIdAsync(object authorization, CancellationToken cancellationToken) => + GetPhysicalIdAsync((TAuthorization)authorization, cancellationToken); } } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdScopeManager.cs b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdScopeManager.cs index eab3ec1b16c..5364219ad91 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdScopeManager.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdScopeManager.cs @@ -10,16 +10,16 @@ namespace OrchardCore.OpenId.Services.Managers { - public class OpenIdScopeManager : OpenIddictScopeManager, IOpenIdScopeManager where TScope : class + public class OpenIdScopeManager : OpenIddictScopeManager, IOpenIdScopeManager + where TScope : class { public OpenIdScopeManager( IOpenIddictScopeCache cache, ILogger> logger, IOptionsMonitor options, - IOpenIddictScopeStoreResolver resolver) - : base(cache, logger, options, resolver) - { - } + IOpenIddictScopeStoreResolver resolver + ) + : base(cache, logger, options, resolver) { } /// /// Retrieves a scope using its physical identifier. @@ -37,9 +37,7 @@ public virtual ValueTask FindByPhysicalIdAsync(string identifier, Cancel throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } - return Store is IOpenIdScopeStore store ? - store.FindByPhysicalIdAsync(identifier, cancellationToken) : - Store.FindByIdAsync(identifier, cancellationToken); + return Store is IOpenIdScopeStore store ? store.FindByPhysicalIdAsync(identifier, cancellationToken) : Store.FindByIdAsync(identifier, cancellationToken); } /// @@ -55,15 +53,12 @@ public virtual ValueTask GetPhysicalIdAsync(TScope scope, CancellationTo { ArgumentNullException.ThrowIfNull(scope); - return Store is IOpenIdScopeStore store ? - store.GetPhysicalIdAsync(scope, cancellationToken) : - Store.GetIdAsync(scope, cancellationToken); + return Store is IOpenIdScopeStore store ? store.GetPhysicalIdAsync(scope, cancellationToken) : Store.GetIdAsync(scope, cancellationToken); } - async ValueTask IOpenIdScopeManager.FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) - => await FindByPhysicalIdAsync(identifier, cancellationToken); + async ValueTask IOpenIdScopeManager.FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) => + await FindByPhysicalIdAsync(identifier, cancellationToken); - ValueTask IOpenIdScopeManager.GetPhysicalIdAsync(object scope, CancellationToken cancellationToken) - => GetPhysicalIdAsync((TScope)scope, cancellationToken); + ValueTask IOpenIdScopeManager.GetPhysicalIdAsync(object scope, CancellationToken cancellationToken) => GetPhysicalIdAsync((TScope)scope, cancellationToken); } } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdTokenManager.cs b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdTokenManager.cs index 57f60a3c396..cd95d99bef7 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdTokenManager.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdTokenManager.cs @@ -10,16 +10,16 @@ namespace OrchardCore.OpenId.Services.Managers { - public class OpenIdTokenManager : OpenIddictTokenManager, IOpenIdTokenManager where TToken : class + public class OpenIdTokenManager : OpenIddictTokenManager, IOpenIdTokenManager + where TToken : class { public OpenIdTokenManager( IOpenIddictTokenCache cache, ILogger> logger, IOptionsMonitor options, - IOpenIddictTokenStoreResolver resolver) - : base(cache, logger, options, resolver) - { - } + IOpenIddictTokenStoreResolver resolver + ) + : base(cache, logger, options, resolver) { } /// /// Retrieves a token using its physical identifier. @@ -37,9 +37,7 @@ public virtual ValueTask FindByPhysicalIdAsync(string identifier, Cancel throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } - return Store is IOpenIdTokenStore store ? - store.FindByPhysicalIdAsync(identifier, cancellationToken) : - Store.FindByIdAsync(identifier, cancellationToken); + return Store is IOpenIdTokenStore store ? store.FindByPhysicalIdAsync(identifier, cancellationToken) : Store.FindByIdAsync(identifier, cancellationToken); } /// @@ -55,15 +53,12 @@ public virtual ValueTask GetPhysicalIdAsync(TToken token, CancellationTo { ArgumentNullException.ThrowIfNull(token); - return Store is IOpenIdTokenStore store ? - store.GetPhysicalIdAsync(token, cancellationToken) : - Store.GetIdAsync(token, cancellationToken); + return Store is IOpenIdTokenStore store ? store.GetPhysicalIdAsync(token, cancellationToken) : Store.GetIdAsync(token, cancellationToken); } - async ValueTask IOpenIdTokenManager.FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) - => await FindByPhysicalIdAsync(identifier, cancellationToken); + async ValueTask IOpenIdTokenManager.FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) => + await FindByPhysicalIdAsync(identifier, cancellationToken); - ValueTask IOpenIdTokenManager.GetPhysicalIdAsync(object token, CancellationToken cancellationToken) - => GetPhysicalIdAsync((TToken)token, cancellationToken); + ValueTask IOpenIdTokenManager.GetPhysicalIdAsync(object token, CancellationToken cancellationToken) => GetPhysicalIdAsync((TToken)token, cancellationToken); } } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdApplicationIndex.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdApplicationIndex.cs index b09b973fa62..130947d9948 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdApplicationIndex.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdApplicationIndex.cs @@ -32,71 +32,50 @@ public class OpenIdApplicationIndexProvider : IndexProvider { private const string OpenIdCollection = OpenIdApplication.OpenIdCollection; - public OpenIdApplicationIndexProvider() - => CollectionName = OpenIdCollection; + public OpenIdApplicationIndexProvider() => CollectionName = OpenIdCollection; public override void Describe(DescribeContext context) { - context.For() - .Map(application => new OpenIdApplicationIndex - { - ApplicationId = application.ApplicationId, - ClientId = application.ClientId - }); + context.For().Map(application => new OpenIdApplicationIndex { ApplicationId = application.ApplicationId, ClientId = application.ClientId }); - context.For() - .Map(application => application.PostLogoutRedirectUris.Select(uri => new OpenIdAppByLogoutUriIndex - { - LogoutRedirectUri = uri, - Count = 1 - })) + context + .For() + .Map(application => application.PostLogoutRedirectUris.Select(uri => new OpenIdAppByLogoutUriIndex { LogoutRedirectUri = uri, Count = 1 })) .Group(index => index.LogoutRedirectUri) - .Reduce(group => new OpenIdAppByLogoutUriIndex - { - LogoutRedirectUri = group.Key, - Count = group.Sum(x => x.Count) - }) - .Delete((index, map) => - { - index.Count -= map.Sum(x => x.Count); - return index.Count > 0 ? index : null; - }); + .Reduce(group => new OpenIdAppByLogoutUriIndex { LogoutRedirectUri = group.Key, Count = group.Sum(x => x.Count) }) + .Delete( + (index, map) => + { + index.Count -= map.Sum(x => x.Count); + return index.Count > 0 ? index : null; + } + ); - context.For() - .Map(application => application.RedirectUris.Select(uri => new OpenIdAppByRedirectUriIndex - { - RedirectUri = uri, - Count = 1 - })) + context + .For() + .Map(application => application.RedirectUris.Select(uri => new OpenIdAppByRedirectUriIndex { RedirectUri = uri, Count = 1 })) .Group(index => index.RedirectUri) - .Reduce(group => new OpenIdAppByRedirectUriIndex - { - RedirectUri = group.Key, - Count = group.Sum(x => x.Count) - }) - .Delete((index, map) => - { - index.Count -= map.Sum(x => x.Count); - return index.Count > 0 ? index : null; - }); + .Reduce(group => new OpenIdAppByRedirectUriIndex { RedirectUri = group.Key, Count = group.Sum(x => x.Count) }) + .Delete( + (index, map) => + { + index.Count -= map.Sum(x => x.Count); + return index.Count > 0 ? index : null; + } + ); - context.For() - .Map(application => application.Roles.Select(role => new OpenIdAppByRoleNameIndex - { - RoleName = role, - Count = 1 - })) + context + .For() + .Map(application => application.Roles.Select(role => new OpenIdAppByRoleNameIndex { RoleName = role, Count = 1 })) .Group(index => index.RoleName) - .Reduce(group => new OpenIdAppByRoleNameIndex - { - RoleName = group.Key, - Count = group.Sum(x => x.Count) - }) - .Delete((index, map) => - { - index.Count -= map.Sum(x => x.Count); - return index.Count > 0 ? index : null; - }); + .Reduce(group => new OpenIdAppByRoleNameIndex { RoleName = group.Key, Count = group.Sum(x => x.Count) }) + .Delete( + (index, map) => + { + index.Count -= map.Sum(x => x.Count); + return index.Count > 0 ? index : null; + } + ); } } } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdAuthorizationIndex.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdAuthorizationIndex.cs index 3e587cee8cb..709908d2b0a 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdAuthorizationIndex.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdAuthorizationIndex.cs @@ -18,12 +18,12 @@ public class OpenIdAuthorizationIndexProvider : IndexProvider CollectionName = OpenIdCollection; + public OpenIdAuthorizationIndexProvider() => CollectionName = OpenIdCollection; public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(authorization => new OpenIdAuthorizationIndex { ApplicationId = authorization.ApplicationId, diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdScopeIndex.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdScopeIndex.cs index 8f47940b140..56389d815cd 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdScopeIndex.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdScopeIndex.cs @@ -20,35 +20,24 @@ public class OpenIdScopeIndexProvider : IndexProvider { private const string OpenIdCollection = OpenIdScope.OpenIdCollection; - public OpenIdScopeIndexProvider() - => CollectionName = OpenIdCollection; + public OpenIdScopeIndexProvider() => CollectionName = OpenIdCollection; public override void Describe(DescribeContext context) { - context.For() - .Map(scope => new OpenIdScopeIndex - { - Name = scope.Name, - ScopeId = scope.ScopeId - }); + context.For().Map(scope => new OpenIdScopeIndex { Name = scope.Name, ScopeId = scope.ScopeId }); - context.For() - .Map(scope => scope.Resources.Select(resource => new OpenIdScopeByResourceIndex - { - Resource = resource, - Count = 1 - })) + context + .For() + .Map(scope => scope.Resources.Select(resource => new OpenIdScopeByResourceIndex { Resource = resource, Count = 1 })) .Group(index => index.Resource) - .Reduce(group => new OpenIdScopeByResourceIndex - { - Resource = group.Key, - Count = group.Sum(x => x.Count) - }) - .Delete((index, map) => - { - index.Count -= map.Sum(x => x.Count); - return index.Count > 0 ? index : null; - }); + .Reduce(group => new OpenIdScopeByResourceIndex { Resource = group.Key, Count = group.Sum(x => x.Count) }) + .Delete( + (index, map) => + { + index.Count -= map.Sum(x => x.Count); + return index.Count > 0 ? index : null; + } + ); } } } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdTokenIndex.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdTokenIndex.cs index f768eefc92e..6d5cbe93dad 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdTokenIndex.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Indexes/OpenIdTokenIndex.cs @@ -21,12 +21,12 @@ public class OpenIdTokenIndexProvider : IndexProvider { private const string OpenIdCollection = OpenIdToken.OpenIdCollection; - public OpenIdTokenIndexProvider() - => CollectionName = OpenIdCollection; + public OpenIdTokenIndexProvider() => CollectionName = OpenIdCollection; public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(token => new OpenIdTokenIndex { TokenId = token.TokenId, diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Migrations/OpenIdMigrations.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Migrations/OpenIdMigrations.cs index afaf9d56254..419911049b0 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Migrations/OpenIdMigrations.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Migrations/OpenIdMigrations.cs @@ -24,138 +24,115 @@ public OpenIdMigrations(ISession session) public async Task CreateAsync() { - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ApplicationId", column => column.WithLength(48)) - .Column("ClientId", column => column.Unique()), - collection: OpenIdApplicationCollection); - - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdApplication", - "DocumentId", - "ApplicationId", - "ClientId"), + await SchemaBuilder.CreateMapIndexTableAsync( + table => table.Column("ApplicationId", column => column.WithLength(48)).Column("ClientId", column => column.Unique()), collection: OpenIdApplicationCollection ); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("LogoutRedirectUri") - .Column("Count"), - collection: OpenIdApplicationCollection); + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdApplication", "DocumentId", "ApplicationId", "ClientId"), + collection: OpenIdApplicationCollection + ); + + await SchemaBuilder.CreateReduceIndexTableAsync( + table => table.Column("LogoutRedirectUri").Column("Count"), + collection: OpenIdApplicationCollection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdAppByLogoutUri_LogoutRedirectUri", "LogoutRedirectUri"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdAppByLogoutUri_LogoutRedirectUri", "LogoutRedirectUri"), collection: OpenIdApplicationCollection ); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("RedirectUri") - .Column("Count"), - collection: OpenIdApplicationCollection); + await SchemaBuilder.CreateReduceIndexTableAsync( + table => table.Column("RedirectUri").Column("Count"), + collection: OpenIdApplicationCollection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdAppByRedirectUri_RedirectUri", "RedirectUri"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdAppByRedirectUri_RedirectUri", "RedirectUri"), collection: OpenIdApplicationCollection ); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("RoleName") - .Column("Count"), - collection: OpenIdApplicationCollection); + await SchemaBuilder.CreateReduceIndexTableAsync( + table => table.Column("RoleName").Column("Count"), + collection: OpenIdApplicationCollection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdAppByRoleName_RoleName", "RoleName"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdAppByRoleName_RoleName", "RoleName"), collection: OpenIdApplicationCollection ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("AuthorizationId", column => column.WithLength(48)) - .Column("ApplicationId", column => column.WithLength(48)) - .Column("Status") - .Column("Subject") - .Column("Type") - .Column("CreationDate"), - collection: OpenIdAuthorizationCollection); - - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdAuthorization_ApplicationId", - "DocumentId", - "ApplicationId", - "Status", - "Subject"), + await SchemaBuilder.CreateMapIndexTableAsync( + table => + table + .Column("AuthorizationId", column => column.WithLength(48)) + .Column("ApplicationId", column => column.WithLength(48)) + .Column("Status") + .Column("Subject") + .Column("Type") + .Column("CreationDate"), collection: OpenIdAuthorizationCollection ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdAuthorization_AuthorizationId", - "DocumentId", - "AuthorizationId", - "Status", - "Type", - "CreationDate"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdAuthorization_ApplicationId", "DocumentId", "ApplicationId", "Status", "Subject"), collection: OpenIdAuthorizationCollection ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("Name", column => column.Unique()) - .Column("ScopeId", column => column.WithLength(48)), - collection: OpenIdScopeCollection); + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdAuthorization_AuthorizationId", "DocumentId", "AuthorizationId", "Status", "Type", "CreationDate"), + collection: OpenIdAuthorizationCollection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdScope", - "DocumentId", - "Name", - "ScopeId"), + await SchemaBuilder.CreateMapIndexTableAsync( + table => table.Column("Name", column => column.Unique()).Column("ScopeId", column => column.WithLength(48)), collection: OpenIdScopeCollection ); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("Resource") - .Column("Count"), - collection: OpenIdScopeCollection); + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdScope", "DocumentId", "Name", "ScopeId"), + collection: OpenIdScopeCollection + ); + + await SchemaBuilder.CreateReduceIndexTableAsync( + table => table.Column("Resource").Column("Count"), + collection: OpenIdScopeCollection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdScopeByResource_Resource", - "Resource"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdScopeByResource_Resource", "Resource"), collection: OpenIdScopeCollection ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("TokenId", column => column.WithLength(48)) - .Column("ApplicationId", column => column.WithLength(48)) - .Column("AuthorizationId", column => column.WithLength(48)) - .Column("ExpirationDate") - .Column("ReferenceId") - .Column("Status") - .Column("Subject") - .Column("Type") - .Column("CreationDate"), - collection: OpenIdTokenCollection); - - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdToken_ApplicationId", - "DocumentId", - "ApplicationId", - "Status", - "Subject"), + await SchemaBuilder.CreateMapIndexTableAsync( + table => + table + .Column("TokenId", column => column.WithLength(48)) + .Column("ApplicationId", column => column.WithLength(48)) + .Column("AuthorizationId", column => column.WithLength(48)) + .Column("ExpirationDate") + .Column("ReferenceId") + .Column("Status") + .Column("Subject") + .Column("Type") + .Column("CreationDate"), collection: OpenIdTokenCollection ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdToken_AuthorizationId", - "DocumentId", - "AuthorizationId", - "Status", - "Type", - "CreationDate", - "ExpirationDate"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdToken_ApplicationId", "DocumentId", "ApplicationId", "Status", "Subject"), collection: OpenIdTokenCollection ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdToken_TokenId", - "DocumentId", - "TokenId", - "ReferenceId"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdToken_AuthorizationId", "DocumentId", "AuthorizationId", "Status", "Type", "CreationDate", "ExpirationDate"), + collection: OpenIdTokenCollection + ); + + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdToken_TokenId", "DocumentId", "TokenId", "ReferenceId"), collection: OpenIdTokenCollection ); @@ -166,14 +143,15 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom1Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("Type")); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("Type")); return 2; } private class OpenIdApplicationByPostLogoutRedirectUriIndex { } + private class OpenIdApplicationByRedirectUriIndex { } + private class OpenIdApplicationByRoleNameIndex { } // This code can be removed in a later version. @@ -183,17 +161,11 @@ public async Task UpdateFrom2Async() await SchemaBuilder.DropReduceIndexTableAsync(null); await SchemaBuilder.DropReduceIndexTableAsync(null); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("LogoutRedirectUri") - .Column("Count")); + await SchemaBuilder.CreateReduceIndexTableAsync(table => table.Column("LogoutRedirectUri").Column("Count")); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("RedirectUri") - .Column("Count")); + await SchemaBuilder.CreateReduceIndexTableAsync(table => table.Column("RedirectUri").Column("Count")); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("RoleName") - .Column("Count")); + await SchemaBuilder.CreateReduceIndexTableAsync(table => table.Column("RoleName").Column("Count")); return 3; } @@ -201,11 +173,9 @@ await SchemaBuilder.CreateReduceIndexTableAsync(table // This code can be removed in a later version. public async Task UpdateFrom3Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("CreationDate")); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("CreationDate")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .AddColumn("CreationDate")); + await SchemaBuilder.AlterIndexTableAsync(table => table.AddColumn("CreationDate")); return 4; } @@ -213,60 +183,30 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom4Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdApplicationIndex_DocumentId", - "DocumentId", - "ApplicationId", - "ClientId") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_OpenIdApplicationIndex_DocumentId", "DocumentId", "ApplicationId", "ClientId") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdAuthorizationIndex_DocumentId_ApplicationId", - "DocumentId", - "ApplicationId", - "Status", - "Subject") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_OpenIdAuthorizationIndex_DocumentId_ApplicationId", "DocumentId", "ApplicationId", "Status", "Subject") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdAuthorizationIndex_DocumentId_AuthorizationId", - "DocumentId", - "AuthorizationId", - "Status", - "Type", - "CreationDate") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_OpenIdAuthorizationIndex_DocumentId_AuthorizationId", "DocumentId", "AuthorizationId", "Status", "Type", "CreationDate") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdScopeIndex_DocumentId", - "DocumentId", - "Name", - "ScopeId") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_OpenIdScopeIndex_DocumentId", "DocumentId", "Name", "ScopeId")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdTokenIndex_DocumentId_ApplicationId", - "DocumentId", - "ApplicationId", - "Status", - "Subject") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_OpenIdTokenIndex_DocumentId_ApplicationId", "DocumentId", "ApplicationId", "Status", "Subject") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdTokenIndex_DocumentId_AuthorizationId", - "DocumentId", - "AuthorizationId", - "Status", - "Type", - "CreationDate", - "ExpirationDate") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_OpenIdTokenIndex_DocumentId_AuthorizationId", "DocumentId", "AuthorizationId", "Status", "Type", "CreationDate", "ExpirationDate") ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdTokenIndex_DocumentId_TokenId", - "DocumentId", - "TokenId", - "ReferenceId") + await SchemaBuilder.AlterIndexTableAsync(table => + table.CreateIndex("IDX_OpenIdTokenIndex_DocumentId_TokenId", "DocumentId", "TokenId", "ReferenceId") ); return 5; @@ -275,21 +215,13 @@ await SchemaBuilder.AlterIndexTableAsync(table => table // This code can be removed in a later version. public async Task UpdateFrom5Async() { - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdAppByLogoutUriIndex_LogoutRedirectUri", "LogoutRedirectUri") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_OpenIdAppByLogoutUriIndex_LogoutRedirectUri", "LogoutRedirectUri")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdAppByRedirectUriIndex_RedirectUri", "RedirectUri") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_OpenIdAppByRedirectUriIndex_RedirectUri", "RedirectUri")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdAppByRoleNameIndex_RoleName", "RoleName") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_OpenIdAppByRoleNameIndex_RoleName", "RoleName")); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_OpenIdScopeByResourceIndex_Resource", "Resource") - ); + await SchemaBuilder.AlterIndexTableAsync(table => table.CreateIndex("IDX_OpenIdScopeByResourceIndex_Resource", "Resource")); return 6; } @@ -298,71 +230,55 @@ await SchemaBuilder.AlterIndexTableAsync(table => ta public async Task UpdateFrom6Async() { // Create all index tables with the new collection value. - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("TokenId", column => column.WithLength(48)) - .Column("ApplicationId", column => column.WithLength(48)) - .Column("AuthorizationId", column => column.WithLength(48)) - .Column("ExpirationDate") - .Column("ReferenceId") - .Column("Status") - .Column("Subject") - .Column("Type") - .Column("CreationDate"), - collection: OpenIdTokenCollection); - - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdToken_ApplicationId", - "DocumentId", - "ApplicationId", - "Status", - "Subject"), + await SchemaBuilder.CreateMapIndexTableAsync( + table => + table + .Column("TokenId", column => column.WithLength(48)) + .Column("ApplicationId", column => column.WithLength(48)) + .Column("AuthorizationId", column => column.WithLength(48)) + .Column("ExpirationDate") + .Column("ReferenceId") + .Column("Status") + .Column("Subject") + .Column("Type") + .Column("CreationDate"), + collection: OpenIdTokenCollection + ); + + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdToken_ApplicationId", "DocumentId", "ApplicationId", "Status", "Subject"), collection: OpenIdTokenCollection ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdToken_AuthorizationId", - "DocumentId", - "AuthorizationId", - "Status", - "Type", - "CreationDate", - "ExpirationDate"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdToken_AuthorizationId", "DocumentId", "AuthorizationId", "Status", "Type", "CreationDate", "ExpirationDate"), collection: OpenIdTokenCollection ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdToken_TokenId", - "DocumentId", - "TokenId", - "ReferenceId"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdToken_TokenId", "DocumentId", "TokenId", "ReferenceId"), collection: OpenIdTokenCollection ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("AuthorizationId", column => column.WithLength(48)) - .Column("ApplicationId", column => column.WithLength(48)) - .Column("Status") - .Column("Subject") - .Column("Type") - .Column("CreationDate"), - collection: OpenIdAuthorizationCollection); - - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdAuthorization_ApplicationId", - "DocumentId", - "ApplicationId", - "Status", - "Subject"), + await SchemaBuilder.CreateMapIndexTableAsync( + table => + table + .Column("AuthorizationId", column => column.WithLength(48)) + .Column("ApplicationId", column => column.WithLength(48)) + .Column("Status") + .Column("Subject") + .Column("Type") + .Column("CreationDate"), collection: OpenIdAuthorizationCollection ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdAuthorization_AuthorizationId", - "DocumentId", - "AuthorizationId", - "Status", - "Type", - "CreationDate"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdAuthorization_ApplicationId", "DocumentId", "ApplicationId", "Status", "Subject"), + collection: OpenIdAuthorizationCollection + ); + + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdAuthorization_AuthorizationId", "DocumentId", "AuthorizationId", "Status", "Type", "CreationDate"), collection: OpenIdAuthorizationCollection ); @@ -402,70 +318,64 @@ await SchemaBuilder.AlterIndexTableAsync(table => tabl // This code can be removed in a later version. public async Task UpdateFrom7Async() { - // Create all index tables with the new collection value. - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("ApplicationId", column => column.WithLength(48)) - .Column("ClientId", column => column.Unique()), - collection: OpenIdApplicationCollection); - - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdApplication", - "DocumentId", - "ApplicationId", - "ClientId"), + // Create all index tables with the new collection value. + await SchemaBuilder.CreateMapIndexTableAsync( + table => table.Column("ApplicationId", column => column.WithLength(48)).Column("ClientId", column => column.Unique()), collection: OpenIdApplicationCollection ); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("LogoutRedirectUri") - .Column("Count"), - collection: OpenIdApplicationCollection); + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdApplication", "DocumentId", "ApplicationId", "ClientId"), + collection: OpenIdApplicationCollection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdAppByLogoutUri_LogoutRedirectUri", "LogoutRedirectUri"), + await SchemaBuilder.CreateReduceIndexTableAsync( + table => table.Column("LogoutRedirectUri").Column("Count"), collection: OpenIdApplicationCollection ); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("RedirectUri") - .Column("Count"), - collection: OpenIdApplicationCollection); + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdAppByLogoutUri_LogoutRedirectUri", "LogoutRedirectUri"), + collection: OpenIdApplicationCollection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdAppByRedirectUri_RedirectUri", "RedirectUri"), + await SchemaBuilder.CreateReduceIndexTableAsync( + table => table.Column("RedirectUri").Column("Count"), collection: OpenIdApplicationCollection ); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("RoleName") - .Column("Count"), - collection: OpenIdApplicationCollection); + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdAppByRedirectUri_RedirectUri", "RedirectUri"), + collection: OpenIdApplicationCollection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdAppByRoleName_RoleName", "RoleName"), + await SchemaBuilder.CreateReduceIndexTableAsync( + table => table.Column("RoleName").Column("Count"), collection: OpenIdApplicationCollection ); - await SchemaBuilder.CreateMapIndexTableAsync(table => table - .Column("Name", column => column.Unique()) - .Column("ScopeId", column => column.WithLength(48)), - collection: OpenIdScopeCollection); + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdAppByRoleName_RoleName", "RoleName"), + collection: OpenIdApplicationCollection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdScope", - "DocumentId", - "Name", - "ScopeId"), + await SchemaBuilder.CreateMapIndexTableAsync( + table => table.Column("Name", column => column.Unique()).Column("ScopeId", column => column.WithLength(48)), collection: OpenIdScopeCollection ); - await SchemaBuilder.CreateReduceIndexTableAsync(table => table - .Column("Resource") - .Column("Count"), - collection: OpenIdScopeCollection); + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdScope", "DocumentId", "Name", "ScopeId"), + collection: OpenIdScopeCollection + ); + + await SchemaBuilder.CreateReduceIndexTableAsync( + table => table.Column("Resource").Column("Count"), + collection: OpenIdScopeCollection + ); - await SchemaBuilder.AlterIndexTableAsync(table => table - .CreateIndex("IDX_COL_OpenIdScopeByResource_Resource", "Resource"), + await SchemaBuilder.AlterIndexTableAsync( + table => table.CreateIndex("IDX_COL_OpenIdScopeByResource_Resource", "Resource"), collection: OpenIdScopeCollection ); diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Models/OpenIdApplication.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Models/OpenIdApplication.cs index 178f51a5720..10c04fc2083 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Models/OpenIdApplication.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Models/OpenIdApplication.cs @@ -46,8 +46,7 @@ public class OpenIdApplication /// /// Gets or sets the localized display names associated with the application. /// - public ImmutableDictionary DisplayNames { get; set; } - = ImmutableDictionary.Create(); + public ImmutableDictionary DisplayNames { get; set; } = ImmutableDictionary.Create(); /// /// Gets or sets the physical identifier associated with the current application. @@ -93,8 +92,7 @@ public class OpenIdApplication /// /// Gets or sets the settings associated with the application. /// - public ImmutableDictionary Settings { get; set; } - = ImmutableDictionary.Create(); + public ImmutableDictionary Settings { get; set; } = ImmutableDictionary.Create(); /// /// Gets or sets the client type associated with the current application. diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Models/OpenIdScope.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Models/OpenIdScope.cs index 9d4396816bd..68971a94770 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Models/OpenIdScope.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Models/OpenIdScope.cs @@ -24,8 +24,7 @@ public class OpenIdScope /// /// Gets or sets the localized descriptions associated with the scope. /// - public ImmutableDictionary Descriptions { get; set; } - = ImmutableDictionary.Create(); + public ImmutableDictionary Descriptions { get; set; } = ImmutableDictionary.Create(); /// /// Gets or sets the display name associated with the current scope. @@ -35,8 +34,7 @@ public class OpenIdScope /// /// Gets or sets the localized display names associated with the scope. /// - public ImmutableDictionary DisplayNames { get; set; } - = ImmutableDictionary.Create(); + public ImmutableDictionary DisplayNames { get; set; } = ImmutableDictionary.Create(); /// /// Gets or sets the physical identifier associated with the current scope. diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdApplicationStoreResolver.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdApplicationStoreResolver.cs index 49362e000f4..4cadac3e981 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdApplicationStoreResolver.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdApplicationStoreResolver.cs @@ -21,7 +21,8 @@ public OpenIdApplicationStoreResolver(TypeResolutionCache cache, IServiceProvide } /// - public IOpenIddictApplicationStore Get() where TApplication : class + public IOpenIddictApplicationStore Get() + where TApplication : class { var store = _provider.GetService>(); if (store != null) @@ -29,20 +30,25 @@ public IOpenIddictApplicationStore Get() where TAppl return store; } - var type = _cache.GetOrAdd(typeof(TApplication), key => - { - if (!typeof(OpenIdApplication).IsAssignableFrom(key)) + var type = _cache.GetOrAdd( + typeof(TApplication), + key => { - throw new InvalidOperationException(new StringBuilder() - .AppendLine("The specified application type is not compatible with the YesSql stores.") - .Append("When enabling the YesSql stores, make sure you use the built-in 'OpenIdApplication' ") - .Append("entity (from the 'OrchardCore.OpenId.Core' package) or a custom entity ") - .Append("that inherits from the 'OpenIdApplication' entity.") - .ToString()); - } + if (!typeof(OpenIdApplication).IsAssignableFrom(key)) + { + throw new InvalidOperationException( + new StringBuilder() + .AppendLine("The specified application type is not compatible with the YesSql stores.") + .Append("When enabling the YesSql stores, make sure you use the built-in 'OpenIdApplication' ") + .Append("entity (from the 'OrchardCore.OpenId.Core' package) or a custom entity ") + .Append("that inherits from the 'OpenIdApplication' entity.") + .ToString() + ); + } - return typeof(OpenIdApplicationStore<>).MakeGenericType(key); - }); + return typeof(OpenIdApplicationStore<>).MakeGenericType(key); + } + ); return (IOpenIddictApplicationStore)_provider.GetRequiredService(type); } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdAuthorizationStoreResolver.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdAuthorizationStoreResolver.cs index 39868f9fafb..b0fcda6a7fa 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdAuthorizationStoreResolver.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdAuthorizationStoreResolver.cs @@ -21,7 +21,8 @@ public OpenIdAuthorizationStoreResolver(TypeResolutionCache cache, IServiceProvi } /// - public IOpenIddictAuthorizationStore Get() where TAuthorization : class + public IOpenIddictAuthorizationStore Get() + where TAuthorization : class { var store = _provider.GetService>(); if (store != null) @@ -29,20 +30,25 @@ public IOpenIddictAuthorizationStore Get() where return store; } - var type = _cache.GetOrAdd(typeof(TAuthorization), key => - { - if (!typeof(OpenIdAuthorization).IsAssignableFrom(key)) + var type = _cache.GetOrAdd( + typeof(TAuthorization), + key => { - throw new InvalidOperationException(new StringBuilder() - .AppendLine("The specified authorization type is not compatible with the YesSql stores.") - .Append("When enabling the YesSql stores, make sure you use the built-in 'OpenIdAuthorization' ") - .Append("entity (from the 'OrchardCore.OpenId.Core' package) or a custom entity ") - .Append("that inherits from the 'OpenIdAuthorization' entity.") - .ToString()); - } + if (!typeof(OpenIdAuthorization).IsAssignableFrom(key)) + { + throw new InvalidOperationException( + new StringBuilder() + .AppendLine("The specified authorization type is not compatible with the YesSql stores.") + .Append("When enabling the YesSql stores, make sure you use the built-in 'OpenIdAuthorization' ") + .Append("entity (from the 'OrchardCore.OpenId.Core' package) or a custom entity ") + .Append("that inherits from the 'OpenIdAuthorization' entity.") + .ToString() + ); + } - return typeof(OpenIdAuthorizationStore<>).MakeGenericType(key); - }); + return typeof(OpenIdAuthorizationStore<>).MakeGenericType(key); + } + ); return (IOpenIddictAuthorizationStore)_provider.GetRequiredService(type); } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdScopeStoreResolver.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdScopeStoreResolver.cs index 756d45308fc..6456679d410 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdScopeStoreResolver.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdScopeStoreResolver.cs @@ -21,7 +21,8 @@ public OpenIdScopeStoreResolver(TypeResolutionCache cache, IServiceProvider prov } /// - public IOpenIddictScopeStore Get() where TScope : class + public IOpenIddictScopeStore Get() + where TScope : class { var store = _provider.GetService>(); if (store != null) @@ -29,20 +30,25 @@ public IOpenIddictScopeStore Get() where TScope : class return store; } - var type = _cache.GetOrAdd(typeof(TScope), key => - { - if (!typeof(OpenIdScope).IsAssignableFrom(key)) + var type = _cache.GetOrAdd( + typeof(TScope), + key => { - throw new InvalidOperationException(new StringBuilder() - .AppendLine("The specified scope type is not compatible with the YesSql stores.") - .Append("When enabling the YesSql stores, make sure you use the built-in 'OpenIdScope' ") - .Append("entity (from the 'OrchardCore.OpenId.Core' package) or a custom entity ") - .Append("that inherits from the 'OpenIdScope' entity.") - .ToString()); - } + if (!typeof(OpenIdScope).IsAssignableFrom(key)) + { + throw new InvalidOperationException( + new StringBuilder() + .AppendLine("The specified scope type is not compatible with the YesSql stores.") + .Append("When enabling the YesSql stores, make sure you use the built-in 'OpenIdScope' ") + .Append("entity (from the 'OrchardCore.OpenId.Core' package) or a custom entity ") + .Append("that inherits from the 'OpenIdScope' entity.") + .ToString() + ); + } - return typeof(OpenIdScopeStore<>).MakeGenericType(key); - }); + return typeof(OpenIdScopeStore<>).MakeGenericType(key); + } + ); return (IOpenIddictScopeStore)_provider.GetRequiredService(type); } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdTokenStoreResolver.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdTokenStoreResolver.cs index 309d08a1e99..22676926b6d 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdTokenStoreResolver.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Resolvers/OpenIdTokenStoreResolver.cs @@ -21,7 +21,8 @@ public OpenIdTokenStoreResolver(TypeResolutionCache cache, IServiceProvider prov } /// - public IOpenIddictTokenStore Get() where TToken : class + public IOpenIddictTokenStore Get() + where TToken : class { var store = _provider.GetService>(); if (store != null) @@ -29,20 +30,25 @@ public IOpenIddictTokenStore Get() where TToken : class return store; } - var type = _cache.GetOrAdd(typeof(TToken), key => - { - if (!typeof(OpenIdToken).IsAssignableFrom(key)) + var type = _cache.GetOrAdd( + typeof(TToken), + key => { - throw new InvalidOperationException(new StringBuilder() - .AppendLine("The specified token type is not compatible with the YesSql stores.") - .Append("When enabling the YesSql stores, make sure you use the built-in 'OpenIdToken' ") - .Append("entity (from the 'OrchardCore.OpenId.Core' package) or a custom entity ") - .Append("that inherits from the 'OpenIdToken' entity.") - .ToString()); - } + if (!typeof(OpenIdToken).IsAssignableFrom(key)) + { + throw new InvalidOperationException( + new StringBuilder() + .AppendLine("The specified token type is not compatible with the YesSql stores.") + .Append("When enabling the YesSql stores, make sure you use the built-in 'OpenIdToken' ") + .Append("entity (from the 'OrchardCore.OpenId.Core' package) or a custom entity ") + .Append("that inherits from the 'OpenIdToken' entity.") + .ToString() + ); + } - return typeof(OpenIdTokenStore<>).MakeGenericType(key); - }); + return typeof(OpenIdTokenStore<>).MakeGenericType(key); + } + ); return (IOpenIddictTokenStore)_provider.GetRequiredService(type); } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdApplicationStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdApplicationStore.cs index 62b81c60ead..8bf93cc4cb6 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdApplicationStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdApplicationStore.cs @@ -21,11 +21,7 @@ namespace OrchardCore.OpenId.YesSql.Stores public class OpenIdApplicationStore : IOpenIdApplicationStore where TApplication : OpenIdApplication, new() { - private static readonly JsonSerializerOptions _serializerOptions = new() - { - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - WriteIndented = false - }; + private static readonly JsonSerializerOptions _serializerOptions = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, WriteIndented = false }; private const string OpenIdCollection = OpenIdAuthorization.OpenIdCollection; private readonly ISession _session; @@ -44,8 +40,8 @@ public virtual async ValueTask CountAsync(CancellationToken cancellationTo } /// - public virtual ValueTask CountAsync(Func, IQueryable> query, CancellationToken cancellationToken) - => throw new NotSupportedException(); + public virtual ValueTask CountAsync(Func, IQueryable> query, CancellationToken cancellationToken) => + throw new NotSupportedException(); /// public virtual async ValueTask CreateAsync(TApplication application, CancellationToken cancellationToken) @@ -106,9 +102,7 @@ public virtual IAsyncEnumerable FindByPostLogoutRedirectUriAsync(s cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.LogoutRedirectUri == uri, - collection: OpenIdCollection).ToAsyncEnumerable(); + return _session.Query(index => index.LogoutRedirectUri == uri, collection: OpenIdCollection).ToAsyncEnumerable(); } /// @@ -118,9 +112,7 @@ public virtual IAsyncEnumerable FindByRedirectUriAsync(string uri, cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.RedirectUri == uri, - collection: OpenIdCollection).ToAsyncEnumerable(); + return _session.Query(index => index.RedirectUri == uri, collection: OpenIdCollection).ToAsyncEnumerable(); } public virtual ValueTask GetApplicationTypeAsync(TApplication application, CancellationToken cancellationToken) @@ -133,8 +125,9 @@ public virtual ValueTask GetApplicationTypeAsync(TApplication applicatio /// public virtual ValueTask GetAsync( Func, TState, IQueryable> query, - TState state, CancellationToken cancellationToken) - => throw new NotSupportedException(); + TState state, + CancellationToken cancellationToken + ) => throw new NotSupportedException(); /// public virtual ValueTask GetClientIdAsync(TApplication application, CancellationToken cancellationToken) @@ -177,8 +170,7 @@ public virtual ValueTask GetDisplayNameAsync(TApplication application, C } /// - public virtual ValueTask> GetDisplayNamesAsync( - TApplication application, CancellationToken cancellationToken) + public virtual ValueTask> GetDisplayNamesAsync(TApplication application, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); @@ -244,8 +236,7 @@ public virtual ValueTask> GetProperties return new ValueTask>(ImmutableDictionary.Create()); } - return new ValueTask>( - JConvert.DeserializeObject>(application.Properties.ToString())); + return new ValueTask>(JConvert.DeserializeObject>(application.Properties.ToString())); } /// @@ -273,8 +264,7 @@ public virtual ValueTask> GetSettingsAsync(T } /// - public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) - => new(new TApplication { ApplicationId = Guid.NewGuid().ToString("n") }); + public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) => new(new TApplication { ApplicationId = Guid.NewGuid().ToString("n") }); /// public virtual IAsyncEnumerable ListAsync(int? count, int? offset, CancellationToken cancellationToken) @@ -297,8 +287,9 @@ public virtual IAsyncEnumerable ListAsync(int? count, int? offset, /// public virtual IAsyncEnumerable ListAsync( Func, TState, IQueryable> query, - TState state, CancellationToken cancellationToken) - => throw new NotSupportedException(); + TState state, + CancellationToken cancellationToken + ) => throw new NotSupportedException(); /// public virtual ValueTask SetApplicationTypeAsync(TApplication application, string type, CancellationToken cancellationToken) @@ -311,8 +302,7 @@ public virtual ValueTask SetApplicationTypeAsync(TApplication application, strin } /// - public virtual ValueTask SetClientIdAsync(TApplication application, - string identifier, CancellationToken cancellationToken) + public virtual ValueTask SetClientIdAsync(TApplication application, string identifier, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); @@ -399,8 +389,7 @@ public virtual ValueTask SetPermissionsAsync(TApplication application, Immutable } /// - public virtual ValueTask SetPostLogoutRedirectUrisAsync(TApplication application, - ImmutableArray uris, CancellationToken cancellationToken) + public virtual ValueTask SetPostLogoutRedirectUrisAsync(TApplication application, ImmutableArray uris, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); @@ -427,8 +416,7 @@ public virtual ValueTask SetPropertiesAsync(TApplication application, ImmutableD } /// - public virtual ValueTask SetRedirectUrisAsync(TApplication application, - ImmutableArray uris, CancellationToken cancellationToken) + public virtual ValueTask SetRedirectUrisAsync(TApplication application, ImmutableArray uris, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); @@ -438,8 +426,7 @@ public virtual ValueTask SetRedirectUrisAsync(TApplication application, } /// - public virtual ValueTask SetRequirementsAsync(TApplication application, - ImmutableArray requirements, CancellationToken cancellationToken) + public virtual ValueTask SetRequirementsAsync(TApplication application, ImmutableArray requirements, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); @@ -449,8 +436,7 @@ public virtual ValueTask SetRequirementsAsync(TApplication application, } /// - public virtual ValueTask SetSettingsAsync(TApplication application, - ImmutableDictionary settings, CancellationToken cancellationToken) + public virtual ValueTask SetSettingsAsync(TApplication application, ImmutableDictionary settings, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(application); @@ -474,10 +460,13 @@ public virtual async ValueTask UpdateAsync(TApplication application, Cancellatio } catch (ConcurrencyException exception) { - throw new OpenIddictExceptions.ConcurrencyException(new StringBuilder() - .AppendLine("The application was concurrently updated and cannot be persisted in its current state.") - .Append("Reload the application from the database and retry the operation.") - .ToString(), exception); + throw new OpenIddictExceptions.ConcurrencyException( + new StringBuilder() + .AppendLine("The application was concurrently updated and cannot be persisted in its current state.") + .Append("Reload the application from the database and retry the operation.") + .ToString(), + exception + ); } } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdAuthorizationStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdAuthorizationStore.cs index cfcd1810363..ef3351e5f3e 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdAuthorizationStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdAuthorizationStore.cs @@ -38,8 +38,8 @@ public virtual async ValueTask CountAsync(CancellationToken cancellationTo } /// - public virtual ValueTask CountAsync(Func, IQueryable> query, CancellationToken cancellationToken) - => throw new NotSupportedException(); + public virtual ValueTask CountAsync(Func, IQueryable> query, CancellationToken cancellationToken) => + throw new NotSupportedException(); /// public virtual async ValueTask CreateAsync(TAuthorization authorization, CancellationToken cancellationToken) @@ -64,22 +64,20 @@ public virtual async ValueTask DeleteAsync(TAuthorization authorization, Cancell } /// - public virtual IAsyncEnumerable FindAsync( - string subject, string client, CancellationToken cancellationToken) + public virtual IAsyncEnumerable FindAsync(string subject, string client, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(subject); ArgumentException.ThrowIfNullOrEmpty(client); cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.ApplicationId == client && index.Subject == subject, - collection: OpenIdCollection).ToAsyncEnumerable(); + return _session + .Query(index => index.ApplicationId == client && index.Subject == subject, collection: OpenIdCollection) + .ToAsyncEnumerable(); } /// - public virtual IAsyncEnumerable FindAsync( - string subject, string client, string status, CancellationToken cancellationToken) + public virtual IAsyncEnumerable FindAsync(string subject, string client, string status, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(subject); ArgumentException.ThrowIfNullOrEmpty(client); @@ -87,15 +85,16 @@ public virtual IAsyncEnumerable FindAsync( cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.ApplicationId == client && index.Subject == subject && index.Status == status, - collection: OpenIdCollection).ToAsyncEnumerable(); + return _session + .Query( + index => index.ApplicationId == client && index.Subject == subject && index.Status == status, + collection: OpenIdCollection + ) + .ToAsyncEnumerable(); } /// - public virtual IAsyncEnumerable FindAsync( - string subject, string client, - string status, string type, CancellationToken cancellationToken) + public virtual IAsyncEnumerable FindAsync(string subject, string client, string status, string type, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(subject); ArgumentException.ThrowIfNullOrEmpty(client); @@ -104,16 +103,23 @@ public virtual IAsyncEnumerable FindAsync( cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.ApplicationId == client && index.Subject == subject && - index.Status == status && index.Type == type, - collection: OpenIdCollection).ToAsyncEnumerable(); + return _session + .Query( + index => index.ApplicationId == client && index.Subject == subject && index.Status == status && index.Type == type, + collection: OpenIdCollection + ) + .ToAsyncEnumerable(); } /// public virtual async IAsyncEnumerable FindAsync( - string subject, string client, string status, string type, - ImmutableArray scopes, [EnumeratorCancellation] CancellationToken cancellationToken) + string subject, + string client, + string status, + string type, + ImmutableArray scopes, + [EnumeratorCancellation] CancellationToken cancellationToken + ) { await foreach (var authorization in FindAsync(subject, client, status, type, cancellationToken)) { @@ -125,16 +131,13 @@ public virtual async IAsyncEnumerable FindAsync( } /// - public virtual IAsyncEnumerable FindByApplicationIdAsync( - string identifier, CancellationToken cancellationToken) + public virtual IAsyncEnumerable FindByApplicationIdAsync(string identifier, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(identifier); cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.ApplicationId == identifier, - collection: OpenIdCollection).ToAsyncEnumerable(); + return _session.Query(index => index.ApplicationId == identifier, collection: OpenIdCollection).ToAsyncEnumerable(); } /// @@ -144,9 +147,7 @@ public virtual async ValueTask FindByIdAsync(string identifier, cancellationToken.ThrowIfCancellationRequested(); - return await _session.Query( - index => index.AuthorizationId == identifier, - collection: OpenIdCollection).FirstOrDefaultAsync(); + return await _session.Query(index => index.AuthorizationId == identifier, collection: OpenIdCollection).FirstOrDefaultAsync(); } /// @@ -160,16 +161,13 @@ public virtual async ValueTask FindByPhysicalIdAsync(string iden } /// - public virtual IAsyncEnumerable FindBySubjectAsync( - string subject, CancellationToken cancellationToken) + public virtual IAsyncEnumerable FindBySubjectAsync(string subject, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(subject); cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.Subject == subject, - collection: OpenIdCollection).ToAsyncEnumerable(); + return _session.Query(index => index.Subject == subject, collection: OpenIdCollection).ToAsyncEnumerable(); } /// @@ -183,8 +181,9 @@ public virtual ValueTask GetApplicationIdAsync(TAuthorization authorizat /// public virtual ValueTask GetAsync( Func, TState, IQueryable> query, - TState state, CancellationToken cancellationToken) - => throw new NotSupportedException(); + TState state, + CancellationToken cancellationToken + ) => throw new NotSupportedException(); /// public virtual ValueTask GetCreationDateAsync(TAuthorization authorization, CancellationToken cancellationToken) @@ -226,7 +225,8 @@ public virtual ValueTask> GetProperties } return new ValueTask>( - JConvert.DeserializeObject>(authorization.Properties.ToString())); + JConvert.DeserializeObject>(authorization.Properties.ToString()) + ); } /// @@ -262,8 +262,8 @@ public virtual ValueTask GetTypeAsync(TAuthorization authorization, Canc } /// - public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) - => new(new TAuthorization { AuthorizationId = Guid.NewGuid().ToString("n") }); + public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) => + new(new TAuthorization { AuthorizationId = Guid.NewGuid().ToString("n") }); /// public virtual IAsyncEnumerable ListAsync(int? count, int? offset, CancellationToken cancellationToken) @@ -286,8 +286,9 @@ public virtual IAsyncEnumerable ListAsync(int? count, int? offse /// public virtual IAsyncEnumerable ListAsync( Func, TState, IQueryable> query, - TState state, CancellationToken cancellationToken) - => throw new NotSupportedException(); + TState state, + CancellationToken cancellationToken + ) => throw new NotSupportedException(); /// public virtual async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken) @@ -304,14 +305,23 @@ public virtual async ValueTask PruneAsync(DateTimeOffset threshold, Cancel { cancellationToken.ThrowIfCancellationRequested(); - var authorizations = (await _session.Query( - authorization => authorization.CreationDate < threshold.UtcDateTime && - (authorization.Status != OpenIddictConstants.Statuses.Valid || - (authorization.Type == OpenIddictConstants.AuthorizationTypes.AdHoc && - authorization.AuthorizationId.IsNotIn( - token => token.AuthorizationId, - token => token.Id != 0))), - collection: OpenIdCollection).Take(100).ListAsync()).ToList(); + var authorizations = ( + await _session + .Query( + authorization => + authorization.CreationDate < threshold.UtcDateTime + && ( + authorization.Status != OpenIddictConstants.Statuses.Valid + || ( + authorization.Type == OpenIddictConstants.AuthorizationTypes.AdHoc + && authorization.AuthorizationId.IsNotIn(token => token.AuthorizationId, token => token.Id != 0) + ) + ), + collection: OpenIdCollection + ) + .Take(100) + .ListAsync() + ).ToList(); if (authorizations.Count is 0) { @@ -347,8 +357,7 @@ public virtual async ValueTask PruneAsync(DateTimeOffset threshold, Cancel } /// - public virtual ValueTask SetApplicationIdAsync(TAuthorization authorization, - string identifier, CancellationToken cancellationToken) + public virtual ValueTask SetApplicationIdAsync(TAuthorization authorization, string identifier, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); @@ -392,8 +401,7 @@ public virtual ValueTask SetPropertiesAsync(TAuthorization authorization, Immuta } /// - public virtual ValueTask SetScopesAsync(TAuthorization authorization, - ImmutableArray scopes, CancellationToken cancellationToken) + public virtual ValueTask SetScopesAsync(TAuthorization authorization, ImmutableArray scopes, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); @@ -403,8 +411,7 @@ public virtual ValueTask SetScopesAsync(TAuthorization authorization, } /// - public virtual ValueTask SetStatusAsync(TAuthorization authorization, - string status, CancellationToken cancellationToken) + public virtual ValueTask SetStatusAsync(TAuthorization authorization, string status, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); @@ -414,8 +421,7 @@ public virtual ValueTask SetStatusAsync(TAuthorization authorization, } /// - public virtual ValueTask SetSubjectAsync(TAuthorization authorization, - string subject, CancellationToken cancellationToken) + public virtual ValueTask SetSubjectAsync(TAuthorization authorization, string subject, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); @@ -425,8 +431,7 @@ public virtual ValueTask SetSubjectAsync(TAuthorization authorization, } /// - public virtual ValueTask SetTypeAsync(TAuthorization authorization, - string type, CancellationToken cancellationToken) + public virtual ValueTask SetTypeAsync(TAuthorization authorization, string type, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(authorization); @@ -450,10 +455,13 @@ public virtual async ValueTask UpdateAsync(TAuthorization authorization, Cancell } catch (ConcurrencyException exception) { - throw new OpenIddictExceptions.ConcurrencyException(new StringBuilder() - .AppendLine("The authorization was concurrently updated and cannot be persisted in its current state.") - .Append("Reload the authorization from the database and retry the operation.") - .ToString(), exception); + throw new OpenIddictExceptions.ConcurrencyException( + new StringBuilder() + .AppendLine("The authorization was concurrently updated and cannot be persisted in its current state.") + .Append("Reload the authorization from the database and retry the operation.") + .ToString(), + exception + ); } } } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdScopeStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdScopeStore.cs index 9415dca4446..f0f62c472e0 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdScopeStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdScopeStore.cs @@ -37,8 +37,8 @@ public virtual async ValueTask CountAsync(CancellationToken cancellationTo } /// - public virtual ValueTask CountAsync(Func, IQueryable> query, CancellationToken cancellationToken) - => throw new NotSupportedException(); + public virtual ValueTask CountAsync(Func, IQueryable> query, CancellationToken cancellationToken) => + throw new NotSupportedException(); /// public virtual async ValueTask CreateAsync(TScope scope, CancellationToken cancellationToken) @@ -83,8 +83,7 @@ public virtual async ValueTask FindByNameAsync(string name, Cancellation } /// - public virtual IAsyncEnumerable FindByNamesAsync( - ImmutableArray names, CancellationToken cancellationToken) + public virtual IAsyncEnumerable FindByNamesAsync(ImmutableArray names, CancellationToken cancellationToken) { if (names.Any(name => string.IsNullOrEmpty(name))) { @@ -113,16 +112,15 @@ public virtual IAsyncEnumerable FindByResourceAsync(string resource, Can cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.Resource == resource, - collection: OpenIdCollection).ToAsyncEnumerable(); + return _session.Query(index => index.Resource == resource, collection: OpenIdCollection).ToAsyncEnumerable(); } /// public virtual ValueTask GetAsync( Func, TState, IQueryable> query, - TState state, CancellationToken cancellationToken) - => throw new NotSupportedException(); + TState state, + CancellationToken cancellationToken + ) => throw new NotSupportedException(); /// public virtual ValueTask GetDescriptionAsync(TScope scope, CancellationToken cancellationToken) @@ -133,8 +131,7 @@ public virtual ValueTask GetDescriptionAsync(TScope scope, CancellationT } /// - public virtual ValueTask> GetDescriptionsAsync( - TScope scope, CancellationToken cancellationToken) + public virtual ValueTask> GetDescriptionsAsync(TScope scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); @@ -155,8 +152,7 @@ public virtual ValueTask GetDisplayNameAsync(TScope scope, CancellationT } /// - public virtual ValueTask> GetDisplayNamesAsync( - TScope scope, CancellationToken cancellationToken) + public virtual ValueTask> GetDisplayNamesAsync(TScope scope, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); @@ -202,8 +198,7 @@ public virtual ValueTask> GetProperties return new ValueTask>(ImmutableDictionary.Create()); } - return new ValueTask>( - JConvert.DeserializeObject>(scope.Properties.ToString())); + return new ValueTask>(JConvert.DeserializeObject>(scope.Properties.ToString())); } /// @@ -215,8 +210,7 @@ public virtual ValueTask> GetResourcesAsync(TScope scope, } /// - public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) - => new(new TScope { ScopeId = Guid.NewGuid().ToString("n") }); + public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) => new(new TScope { ScopeId = Guid.NewGuid().ToString("n") }); /// public virtual IAsyncEnumerable ListAsync(int? count, int? offset, CancellationToken cancellationToken) @@ -239,8 +233,9 @@ public virtual IAsyncEnumerable ListAsync(int? count, int? offset, Cance /// public virtual IAsyncEnumerable ListAsync( Func, TState, IQueryable> query, - TState state, CancellationToken cancellationToken) - => throw new NotSupportedException(); + TState state, + CancellationToken cancellationToken + ) => throw new NotSupportedException(); /// public virtual ValueTask SetDescriptionAsync(TScope scope, string description, CancellationToken cancellationToken) @@ -253,8 +248,7 @@ public virtual ValueTask SetDescriptionAsync(TScope scope, string description, C } /// - public virtual ValueTask SetDescriptionsAsync(TScope scope, - ImmutableDictionary descriptions, CancellationToken cancellationToken) + public virtual ValueTask SetDescriptionsAsync(TScope scope, ImmutableDictionary descriptions, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); @@ -274,8 +268,7 @@ public virtual ValueTask SetDisplayNameAsync(TScope scope, string name, Cancella } /// - public virtual ValueTask SetDisplayNamesAsync(TScope scope, - ImmutableDictionary names, CancellationToken cancellationToken) + public virtual ValueTask SetDisplayNamesAsync(TScope scope, ImmutableDictionary names, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scope); @@ -336,10 +329,13 @@ public virtual async ValueTask UpdateAsync(TScope scope, CancellationToken cance } catch (ConcurrencyException exception) { - throw new OpenIddictExceptions.ConcurrencyException(new StringBuilder() - .AppendLine("The scope was concurrently updated and cannot be persisted in its current state.") - .Append("Reload the scope from the database and retry the operation.") - .ToString(), exception); + throw new OpenIddictExceptions.ConcurrencyException( + new StringBuilder() + .AppendLine("The scope was concurrently updated and cannot be persisted in its current state.") + .Append("Reload the scope from the database and retry the operation.") + .ToString(), + exception + ); } } } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdTokenStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdTokenStore.cs index 855669fe72d..dfeae79c025 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdTokenStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdTokenStore.cs @@ -38,8 +38,8 @@ public virtual async ValueTask CountAsync(CancellationToken cancellationTo } /// - public virtual ValueTask CountAsync(Func, IQueryable> query, CancellationToken cancellationToken) - => throw new NotSupportedException(); + public virtual ValueTask CountAsync(Func, IQueryable> query, CancellationToken cancellationToken) => + throw new NotSupportedException(); /// public virtual async ValueTask CreateAsync(TToken token, CancellationToken cancellationToken) @@ -64,21 +64,18 @@ public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cance } /// - public virtual IAsyncEnumerable FindAsync( - string subject, string client, CancellationToken cancellationToken) + public virtual IAsyncEnumerable FindAsync(string subject, string client, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(subject); ArgumentException.ThrowIfNullOrEmpty(client); cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.ApplicationId == client && index.Subject == subject, collection: OpenIdCollection).ToAsyncEnumerable(); + return _session.Query(index => index.ApplicationId == client && index.Subject == subject, collection: OpenIdCollection).ToAsyncEnumerable(); } /// - public virtual IAsyncEnumerable FindAsync( - string subject, string client, string status, CancellationToken cancellationToken) + public virtual IAsyncEnumerable FindAsync(string subject, string client, string status, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(subject); ArgumentException.ThrowIfNullOrEmpty(client); @@ -86,13 +83,13 @@ public virtual IAsyncEnumerable FindAsync( cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.ApplicationId == client && index.Subject == subject && index.Status == status, collection: OpenIdCollection).ToAsyncEnumerable(); + return _session + .Query(index => index.ApplicationId == client && index.Subject == subject && index.Status == status, collection: OpenIdCollection) + .ToAsyncEnumerable(); } /// - public virtual IAsyncEnumerable FindAsync( - string subject, string client, string status, string type, CancellationToken cancellationToken) + public virtual IAsyncEnumerable FindAsync(string subject, string client, string status, string type, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(subject); ArgumentException.ThrowIfNullOrEmpty(client); @@ -101,9 +98,12 @@ public virtual IAsyncEnumerable FindAsync( cancellationToken.ThrowIfCancellationRequested(); - return _session.Query( - index => index.ApplicationId == client && index.Subject == subject && - index.Status == status && index.Type == type, collection: OpenIdCollection).ToAsyncEnumerable(); + return _session + .Query( + index => index.ApplicationId == client && index.Subject == subject && index.Status == status && index.Type == type, + collection: OpenIdCollection + ) + .ToAsyncEnumerable(); } /// @@ -169,8 +169,9 @@ public virtual IAsyncEnumerable FindBySubjectAsync(string subject, Cance /// public virtual ValueTask GetAsync( Func, TState, IQueryable> query, - TState state, CancellationToken cancellationToken) - => throw new NotSupportedException(); + TState state, + CancellationToken cancellationToken + ) => throw new NotSupportedException(); /// public virtual ValueTask GetApplicationIdAsync(TToken token, CancellationToken cancellationToken) @@ -248,8 +249,7 @@ public virtual ValueTask> GetProperties return new ValueTask>(ImmutableDictionary.Create()); } - return new ValueTask>( - JConvert.DeserializeObject>(token.Properties.ToString())); + return new ValueTask>(JConvert.DeserializeObject>(token.Properties.ToString())); } /// @@ -298,8 +298,7 @@ public virtual ValueTask GetTypeAsync(TToken token, CancellationToken ca } /// - public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) - => new(new TToken { TokenId = Guid.NewGuid().ToString("n") }); + public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) => new(new TToken { TokenId = Guid.NewGuid().ToString("n") }); /// public virtual IAsyncEnumerable ListAsync(int? count, int? offset, CancellationToken cancellationToken) @@ -322,8 +321,9 @@ public virtual IAsyncEnumerable ListAsync(int? count, int? offset, Cance /// public virtual IAsyncEnumerable ListAsync( Func, TState, IQueryable> query, - TState state, CancellationToken cancellationToken) - => throw new NotSupportedException(); + TState state, + CancellationToken cancellationToken + ) => throw new NotSupportedException(); /// public virtual async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken = default) @@ -340,13 +340,24 @@ public virtual async ValueTask PruneAsync(DateTimeOffset threshold, Cancel { cancellationToken.ThrowIfCancellationRequested(); - var tokens = (await _session.Query( - token => token.CreationDate < threshold.UtcDateTime && - ((token.Status != Statuses.Inactive && token.Status != Statuses.Valid) || - token.AuthorizationId.IsNotIn( - authorization => authorization.AuthorizationId, - authorization => authorization.Status == Statuses.Valid) || - token.ExpirationDate < DateTime.UtcNow), collection: OpenIdCollection).Take(100).ListAsync()).ToList(); + var tokens = ( + await _session + .Query( + token => + token.CreationDate < threshold.UtcDateTime + && ( + (token.Status != Statuses.Inactive && token.Status != Statuses.Valid) + || token.AuthorizationId.IsNotIn( + authorization => authorization.AuthorizationId, + authorization => authorization.Status == Statuses.Valid + ) + || token.ExpirationDate < DateTime.UtcNow + ), + collection: OpenIdCollection + ) + .Take(100) + .ListAsync() + ).ToList(); if (tokens.Count is 0) { @@ -390,8 +401,7 @@ public virtual async ValueTask RevokeByAuthorizationIdAsync(string identif cancellationToken.ThrowIfCancellationRequested(); - var tokens = (await _session.Query( - token => token.AuthorizationId == identifier, collection: OpenIdCollection).ListAsync()).ToList(); + var tokens = (await _session.Query(token => token.AuthorizationId == identifier, collection: OpenIdCollection).ListAsync()).ToList(); if (tokens.Count is 0) { @@ -556,10 +566,13 @@ public virtual async ValueTask UpdateAsync(TToken token, CancellationToken cance } catch (ConcurrencyException exception) { - throw new OpenIddictExceptions.ConcurrencyException(new StringBuilder() - .AppendLine("The token was concurrently updated and cannot be persisted in its current state.") - .Append("Reload the token from the database and retry the operation.") - .ToString(), exception); + throw new OpenIddictExceptions.ConcurrencyException( + new StringBuilder() + .AppendLine("The token was concurrently updated and cannot be persisted in its current state.") + .Append("Reload the token from the database and retry the operation.") + .ToString(), + exception + ); } } } diff --git a/src/OrchardCore/OrchardCore.Queries.Abstractions/Query.cs b/src/OrchardCore/OrchardCore.Queries.Abstractions/Query.cs index 0d3e59062be..0fe911a9496 100644 --- a/src/OrchardCore/OrchardCore.Queries.Abstractions/Query.cs +++ b/src/OrchardCore/OrchardCore.Queries.Abstractions/Query.cs @@ -8,7 +8,7 @@ public class Query /// /// Initializes a new instance of a . /// - /// + /// protected Query(string source) { Source = source; diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IPAddressRobotDetector.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IPAddressRobotDetector.cs index 98a50a0b442..2a324f2770d 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IPAddressRobotDetector.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IPAddressRobotDetector.cs @@ -12,10 +12,7 @@ public class IPAddressRobotDetector : IDetectRobots private readonly IClientIPAddressAccessor _clientIpAddressAccessor; private readonly ReCaptchaSettings _settings; - public IPAddressRobotDetector( - IClientIPAddressAccessor clientIpAddressAccessor, - IMemoryCache memoryCache, - IOptions settingsAccessor) + public IPAddressRobotDetector(IClientIPAddressAccessor clientIpAddressAccessor, IMemoryCache memoryCache, IOptions settingsAccessor) { _clientIpAddressAccessor = clientIpAddressAccessor; _memoryCache = memoryCache; @@ -40,10 +37,7 @@ public RobotDetectionResult DetectRobot() var ipAddressKey = GetIpAddressCacheKey(); var faultyRequestCount = _memoryCache.GetOrCreate(ipAddressKey, fact => 0); - return new RobotDetectionResult() - { - IsRobot = faultyRequestCount > _settings.DetectionThreshold - }; + return new RobotDetectionResult() { IsRobot = faultyRequestCount > _settings.DetectionThreshold }; } public void FlagAsRobot() diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettings.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettings.cs index 9ef25e413fb..51f2a49bbfb 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettings.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettings.cs @@ -17,9 +17,6 @@ public class ReCaptchaSettings private bool? _isValid; - public bool IsValid() - => _isValid ??= !string.IsNullOrWhiteSpace(SiteKey) - && !string.IsNullOrWhiteSpace(SecretKey) - && !string.IsNullOrWhiteSpace(ReCaptchaApiUri); + public bool IsValid() => _isValid ??= !string.IsNullOrWhiteSpace(SiteKey) && !string.IsNullOrWhiteSpace(SecretKey) && !string.IsNullOrWhiteSpace(ReCaptchaApiUri); } } diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettingsConfiguration.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettingsConfiguration.cs index 93a3a6e1a67..69a05b763fc 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettingsConfiguration.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettingsConfiguration.cs @@ -14,9 +14,7 @@ public ReCaptchaSettingsConfiguration(ISiteService site) public void Configure(ReCaptchaSettings options) { - var settings = _site.GetSiteSettingsAsync() - .GetAwaiter().GetResult() - .As(); + var settings = _site.GetSiteSettingsAsync().GetAwaiter().GetResult().As(); options.SiteKey = settings.SiteKey; options.SecretKey = settings.SecretKey; diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/ServiceCollectionExtensions.cs index b8a76288e02..b1f68da14eb 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/ServiceCollectionExtensions.cs @@ -20,18 +20,22 @@ public static IServiceCollection AddReCaptcha(this IServiceCollection services, services .AddHttpClient(nameof(ReCaptchaService)) - .AddResilienceHandler("oc-handler", builder => builder - .AddRetry(new HttpRetryStrategyOptions - { - Name = "oc-retry", - MaxRetryAttempts = 3, - OnRetry = attempt => - { - attempt.RetryDelay.Add(TimeSpan.FromSeconds(0.5 * attempt.AttemptNumber)); + .AddResilienceHandler( + "oc-handler", + builder => + builder.AddRetry( + new HttpRetryStrategyOptions + { + Name = "oc-retry", + MaxRetryAttempts = 3, + OnRetry = attempt => + { + attempt.RetryDelay.Add(TimeSpan.FromSeconds(0.5 * attempt.AttemptNumber)); - return ValueTask.CompletedTask; - } - }) + return ValueTask.CompletedTask; + } + } + ) ); services.AddSingleton(); diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaService.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaService.cs index c12142eeacf..b84828c1ff8 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaService.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaService.cs @@ -17,10 +17,7 @@ namespace OrchardCore.ReCaptcha.Services { public class ReCaptchaService { - private static readonly JsonSerializerOptions _jsonSerializerOptions = new() - { - PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance, - }; + private static readonly JsonSerializerOptions _jsonSerializerOptions = new() { PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance, }; private readonly ReCaptchaSettings _reCaptchaSettings; private readonly IHttpClientFactory _httpClientFactory; @@ -36,7 +33,8 @@ public ReCaptchaService( IEnumerable robotDetectors, IHttpContextAccessor httpContextAccessor, ILogger logger, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _httpClientFactory = httpClientFactory; _reCaptchaSettings = optionsAccessor.Value; @@ -50,34 +48,27 @@ public ReCaptchaService( /// /// Flags the behavior as that of a robot. /// - public void MaybeThisIsARobot() - => _robotDetectors.Invoke(i => i.FlagAsRobot(), _logger); + public void MaybeThisIsARobot() => _robotDetectors.Invoke(i => i.FlagAsRobot(), _logger); /// /// Determines if the request has been made by a robot. /// /// Yes (true) or no (false). - public bool IsThisARobot() - => _robotDetectors.Invoke(i => i.DetectRobot(), _logger) - .Any(a => a.IsRobot); + public bool IsThisARobot() => _robotDetectors.Invoke(i => i.DetectRobot(), _logger).Any(a => a.IsRobot); /// /// Clears all robot markers, we are dealing with a human. /// /// - public void ThisIsAHuman() - => _robotDetectors.Invoke(i => i.IsNotARobot(), _logger); + public void ThisIsAHuman() => _robotDetectors.Invoke(i => i.IsNotARobot(), _logger); /// /// Verifies the ReCaptcha response with the ReCaptcha webservice. /// /// /// - public async Task VerifyCaptchaResponseAsync(string reCaptchaResponse) - => !string.IsNullOrWhiteSpace(reCaptchaResponse) - && _reCaptchaSettings.IsValid() - && await VerifyAsync(reCaptchaResponse); - + public async Task VerifyCaptchaResponseAsync(string reCaptchaResponse) => + !string.IsNullOrWhiteSpace(reCaptchaResponse) && _reCaptchaSettings.IsValid() && await VerifyAsync(reCaptchaResponse); /// /// Validates the captcha that is in the Form of the current request. @@ -119,11 +110,7 @@ private async Task VerifyAsync(string responseToken) { try { - var content = new FormUrlEncodedContent(new Dictionary - { - { "secret", _reCaptchaSettings.SecretKey }, - { "response", responseToken } - }); + var content = new FormUrlEncodedContent(new Dictionary { { "secret", _reCaptchaSettings.SecretKey }, { "response", responseToken } }); var httpClient = _httpClientFactory.CreateClient(nameof(ReCaptchaService)); var response = await httpClient.PostAsync(_verifyHost, content); diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/TagHelpers/ReCaptchaTagHelper.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/TagHelpers/ReCaptchaTagHelper.cs index 6737e890a26..d21bb213124 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/TagHelpers/ReCaptchaTagHelper.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/TagHelpers/ReCaptchaTagHelper.cs @@ -32,7 +32,8 @@ public ReCaptchaTagHelper( IResourceManager resourceManager, ILocalizationService localizationService, IHttpContextAccessor httpContextAccessor, - ILogger logger) + ILogger logger + ) { _resourceManager = resourceManager; _httpContextAccessor = httpContextAccessor; @@ -102,10 +103,7 @@ private async Task GetReCaptchaScriptUrlAsync() query = query.Add("onload", OnLoad); } - var settingsUrl = new UriBuilder(_settings.ReCaptchaScriptUri) - { - Query = query.ToString() - }; + var settingsUrl = new UriBuilder(_settings.ReCaptchaScriptUri) { Query = query.ToString() }; return settingsUrl.ToString(); } diff --git a/src/OrchardCore/OrchardCore.Recipes.Abstractions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Recipes.Abstractions/ServiceCollectionExtensions.cs index c26aeef080b..6db363af089 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Abstractions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Abstractions/ServiceCollectionExtensions.cs @@ -5,8 +5,7 @@ namespace OrchardCore.Recipes { public static class ServiceCollectionExtensions { - public static IServiceCollection AddRecipeExecutionStep( - this IServiceCollection serviceCollection) + public static IServiceCollection AddRecipeExecutionStep(this IServiceCollection serviceCollection) where TImplementation : class, IRecipeStepHandler { serviceCollection.AddScoped(); diff --git a/src/OrchardCore/OrchardCore.Recipes.Abstractions/Services/IRecipeReader.cs b/src/OrchardCore/OrchardCore.Recipes.Abstractions/Services/IRecipeReader.cs index 1d2b462b467..3556a32a80e 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Abstractions/Services/IRecipeReader.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Abstractions/Services/IRecipeReader.cs @@ -8,8 +8,8 @@ namespace OrchardCore.Recipes.Services public interface IRecipeReader { [Obsolete("This method has been deprecated, please use GetRecipeDescriptorAsync(string, IFileInfo, IFileProvider).")] - Task GetRecipeDescriptor(string recipeBasePath, IFileInfo recipeFileInfo, IFileProvider fileProvider) - => GetRecipeDescriptorAsync(recipeBasePath, recipeFileInfo, fileProvider); + Task GetRecipeDescriptor(string recipeBasePath, IFileInfo recipeFileInfo, IFileProvider fileProvider) => + GetRecipeDescriptorAsync(recipeBasePath, recipeFileInfo, fileProvider); Task GetRecipeDescriptorAsync(string recipeBasePath, IFileInfo recipeFileInfo, IFileProvider fileProvider); } diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/ParametersMethodProvider.cs b/src/OrchardCore/OrchardCore.Recipes.Core/ParametersMethodProvider.cs index 503db793984..e49f30ebc35 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/ParametersMethodProvider.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/ParametersMethodProvider.cs @@ -16,10 +16,13 @@ public ParametersMethodProvider(object environment) _globalMethod = new GlobalMethod { Name = "parameters", - Method = serviceprovider => (Func)(name => - { - return environmentObject.SelectNode(name)?.Value(); - }), + Method = serviceprovider => + (Func)( + name => + { + return environmentObject.SelectNode(name)?.Value(); + } + ), }; } diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/Services/ApplicationRecipeHarvester.cs b/src/OrchardCore/OrchardCore.Recipes.Core/Services/ApplicationRecipeHarvester.cs index 3c32f148328..6b1a926db15 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/Services/ApplicationRecipeHarvester.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/Services/ApplicationRecipeHarvester.cs @@ -12,14 +12,8 @@ namespace OrchardCore.Recipes.Services /// public class ApplicationRecipeHarvester : RecipeHarvester { - public ApplicationRecipeHarvester( - IRecipeReader recipeReader, - IExtensionManager extensionManager, - IHostEnvironment hostingEnvironment, - ILogger logger) - : base(recipeReader, extensionManager, hostingEnvironment, logger) - { - } + public ApplicationRecipeHarvester(IRecipeReader recipeReader, IExtensionManager extensionManager, IHostEnvironment hostingEnvironment, ILogger logger) + : base(recipeReader, extensionManager, hostingEnvironment, logger) { } public override Task> HarvestRecipesAsync() { diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeExecutor.cs b/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeExecutor.cs index 78ffe0bf579..01242d2935d 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeExecutor.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeExecutor.cs @@ -26,11 +26,7 @@ public class RecipeExecutor : IRecipeExecutor private readonly Dictionary> _methodProviders = []; - public RecipeExecutor( - IShellHost shellHost, - ShellSettings shellSettings, - IEnumerable recipeEventHandlers, - ILogger logger) + public RecipeExecutor(IShellHost shellHost, ShellSettings shellSettings, IEnumerable recipeEventHandlers, ILogger logger) { _shellHost = shellHost; _shellSettings = shellSettings; @@ -40,7 +36,12 @@ public RecipeExecutor( public async Task ExecuteAsync(string executionId, RecipeDescriptor recipeDescriptor, IDictionary environment, CancellationToken cancellationToken) { - await _recipeEventHandlers.InvokeAsync((handler, executionId, recipeDescriptor) => handler.RecipeExecutingAsync(executionId, recipeDescriptor), executionId, recipeDescriptor, _logger); + await _recipeEventHandlers.InvokeAsync( + (handler, executionId, recipeDescriptor) => handler.RecipeExecutingAsync(executionId, recipeDescriptor), + executionId, + recipeDescriptor, + _logger + ); try { @@ -131,13 +132,23 @@ public async Task ExecuteAsync(string executionId, RecipeDescriptor reci } } - await _recipeEventHandlers.InvokeAsync((handler, executionId, recipeDescriptor) => handler.RecipeExecutedAsync(executionId, recipeDescriptor), executionId, recipeDescriptor, _logger); + await _recipeEventHandlers.InvokeAsync( + (handler, executionId, recipeDescriptor) => handler.RecipeExecutedAsync(executionId, recipeDescriptor), + executionId, + recipeDescriptor, + _logger + ); return executionId; } catch (Exception) { - await _recipeEventHandlers.InvokeAsync((handler, executionId, recipeDescriptor) => handler.ExecutionFailedAsync(executionId, recipeDescriptor), executionId, recipeDescriptor, _logger); + await _recipeEventHandlers.InvokeAsync( + (handler, executionId, recipeDescriptor) => handler.ExecutionFailedAsync(executionId, recipeDescriptor), + executionId, + recipeDescriptor, + _logger + ); throw; } @@ -149,9 +160,7 @@ public async Task ExecuteAsync(string executionId, RecipeDescriptor reci private async Task ExecuteStepAsync(RecipeExecutionContext recipeStep) { - var shellScope = recipeStep.RecipeDescriptor.RequireNewScope - ? await _shellHost.GetScopeAsync(_shellSettings) - : ShellScope.Current; + var shellScope = recipeStep.RecipeDescriptor.RequireNewScope ? await _shellHost.GetScopeAsync(_shellSettings) : ShellScope.Current; await shellScope.UsingAsync(async scope => { @@ -237,12 +246,9 @@ private JsonNode EvaluateJsonTree(IScriptingManager scriptingManager, RecipeExec value = value.Trim('[', ']'); - value = (scriptingManager.Evaluate( - value, - context.RecipeDescriptor.FileProvider, - context.RecipeDescriptor.BasePath, - _methodProviders[context.ExecutionId]) - ?? "").ToString(); + value = ( + scriptingManager.Evaluate(value, context.RecipeDescriptor.FileProvider, context.RecipeDescriptor.BasePath, _methodProviders[context.ExecutionId]) ?? "" + ).ToString(); } node = JsonValue.Create(value); diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeHarvester.cs b/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeHarvester.cs index f418ff2b5d6..cecd278b76b 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeHarvester.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeHarvester.cs @@ -18,11 +18,7 @@ public class RecipeHarvester : IRecipeHarvester private readonly IHostEnvironment _hostingEnvironment; private readonly ILogger _logger; - public RecipeHarvester( - IRecipeReader recipeReader, - IExtensionManager extensionManager, - IHostEnvironment hostingEnvironment, - ILogger logger) + public RecipeHarvester(IRecipeReader recipeReader, IExtensionManager extensionManager, IHostEnvironment hostingEnvironment, ILogger logger) { _recipeReader = recipeReader; _extensionManager = extensionManager; @@ -31,8 +27,7 @@ public RecipeHarvester( } /// - public virtual Task> HarvestRecipesAsync() - => _extensionManager.GetExtensions().InvokeAsync(HarvestRecipes, _logger); + public virtual Task> HarvestRecipesAsync() => _extensionManager.GetExtensions().InvokeAsync(HarvestRecipes, _logger); /// /// Returns a list of recipes for a content path. @@ -43,7 +38,8 @@ protected async Task> HarvestRecipesAsync(string p { var recipeDescriptors = new List(); - var recipeFiles = _hostingEnvironment.ContentRootFileProvider.GetDirectoryContents(path) + var recipeFiles = _hostingEnvironment + .ContentRootFileProvider.GetDirectoryContents(path) .Where(f => !f.IsDirectory && f.Name.EndsWith(RecipesConstants.RecipeExtension, StringComparison.Ordinal)); foreach (var recipeFile in recipeFiles) diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeMigrator.cs b/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeMigrator.cs index ce453ef4086..1feedba8fec 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeMigrator.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeMigrator.cs @@ -27,7 +27,8 @@ public RecipeMigrator( IHostEnvironment hostingEnvironment, ITypeFeatureProvider typeFeatureProvider, IEnumerable environmentProviders, - ILogger logger) + ILogger logger + ) { _recipeReader = recipeReader; _recipeExecutor = recipeExecutor; diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/VariablesMethodProvider.cs b/src/OrchardCore/OrchardCore.Recipes.Core/VariablesMethodProvider.cs index 8a054cc975d..cf4b3d4b1ce 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/VariablesMethodProvider.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/VariablesMethodProvider.cs @@ -19,29 +19,38 @@ public VariablesMethodProvider(JsonObject variables, List _globalMethod = new GlobalMethod { Name = GlobalMethodName, - Method = serviceProvider => (Func)(name => - { - var variable = variables[name]; + Method = serviceProvider => + (Func)( + name => + { + var variable = variables[name]; - if (variable == null) - { - var S = serviceProvider.GetService>(); + if (variable == null) + { + var S = serviceProvider.GetService>(); - throw new ValidationException(S["The variable '{0}' was used in the recipe but not defined. Make sure you add the '{0}' variable in the '{1}' section of the recipe.", name, GlobalMethodName]); - } + throw new ValidationException( + S[ + "The variable '{0}' was used in the recipe but not defined. Make sure you add the '{0}' variable in the '{1}' section of the recipe.", + name, + GlobalMethodName + ] + ); + } - var value = variable.Value(); + var value = variable.Value(); - // Replace variable value while the result returns another script. - while (value.StartsWith('[') && value.EndsWith(']')) - { - value = value.Trim('[', ']'); - value = (ScriptingManager.Evaluate(value, null, null, scopedMethodProviders) ?? "").ToString(); - variables[name] = value; - } + // Replace variable value while the result returns another script. + while (value.StartsWith('[') && value.EndsWith(']')) + { + value = value.Trim('[', ']'); + value = (ScriptingManager.Evaluate(value, null, null, scopedMethodProviders) ?? "").ToString(); + variables[name] = value; + } - return value; - }), + return value; + } + ), }; } diff --git a/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/MetaEntry.cs b/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/MetaEntry.cs index 4b2b1937214..da8c2b07d3a 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/MetaEntry.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/MetaEntry.cs @@ -13,7 +13,8 @@ public MetaEntry() _builder.TagRenderMode = TagRenderMode.SelfClosing; } - public MetaEntry(string name = null, string property = null, string content = null, string httpEquiv = null, string charset = null) : this() + public MetaEntry(string name = null, string property = null, string content = null, string httpEquiv = null, string charset = null) + : this() { if (!string.IsNullOrEmpty(name)) { diff --git a/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/RequireSettings.cs b/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/RequireSettings.cs index b8332a2c846..d77c190180f 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/RequireSettings.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/RequireSettings.cs @@ -30,9 +30,7 @@ public Dictionary Attributes private set { _attributes = value; } } - public RequireSettings() - { - } + public RequireSettings() { } public RequireSettings(ResourceManagementOptions options) { @@ -215,7 +213,9 @@ public RequireSettings UpdatePositionFromDependent(RequireSettings dependent) { if (dependent.Position == ResourcePosition.First && Position == ResourcePosition.Last) { - throw new InvalidOperationException($"Invalid dependency position of type '{dependent.Type}' for resource '{dependent.Name}' positioned at '{dependent.Position}' depending on '{Name}' positioned at '{Position}'"); + throw new InvalidOperationException( + $"Invalid dependency position of type '{dependent.Type}' for resource '{dependent.Name}' positioned at '{dependent.Position}' depending on '{Name}' positioned at '{Position}'" + ); } // If a 'First' resource depends on a 'ByDependency' resource, position the dependency 'First'. @@ -254,24 +254,31 @@ public RequireSettings NewAndCombine(RequireSettings other) Type = Type, Location = Location, Position = Position - } - .Combine(other) - ; + }.Combine(other); } public RequireSettings Combine(RequireSettings other) { - AtLocation(Location).AtLocation(other.Location) - .WithBasePath(BasePath).WithBasePath(other.BasePath) - .UseCdn(CdnMode).UseCdn(other.CdnMode) - .UseCdnBaseUrl(CdnBaseUrl).UseCdnBaseUrl(other.CdnBaseUrl) - .UseDebugMode(DebugMode).UseDebugMode(other.DebugMode) - .UseCulture(Culture).UseCulture(other.Culture) - .UseCondition(Condition).UseCondition(other.Condition) - .UseVersion(Version).UseVersion(other.Version) - .ShouldAppendVersion(AppendVersion).ShouldAppendVersion(other.AppendVersion) - .Define(InlineDefinition).Define(other.InlineDefinition) - ; + AtLocation(Location) + .AtLocation(other.Location) + .WithBasePath(BasePath) + .WithBasePath(other.BasePath) + .UseCdn(CdnMode) + .UseCdn(other.CdnMode) + .UseCdnBaseUrl(CdnBaseUrl) + .UseCdnBaseUrl(other.CdnBaseUrl) + .UseDebugMode(DebugMode) + .UseDebugMode(other.DebugMode) + .UseCulture(Culture) + .UseCulture(other.Culture) + .UseCondition(Condition) + .UseCondition(other.Condition) + .UseVersion(Version) + .UseVersion(other.Version) + .ShouldAppendVersion(AppendVersion) + .ShouldAppendVersion(other.AppendVersion) + .Define(InlineDefinition) + .Define(other.InlineDefinition); _attributes = MergeAttributes(other); return this; diff --git a/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/ResourceDefinition.cs b/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/ResourceDefinition.cs index 62a442119d2..c054a115052 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/ResourceDefinition.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/ResourceDefinition.cs @@ -170,6 +170,7 @@ public ResourceDefinition SetInnerContent(string innerContent) return this; } + /// /// Position a resource first, last or by dependency. /// @@ -181,24 +182,19 @@ public ResourceDefinition SetPosition(ResourcePosition position) return this; } - public TagBuilder GetTagBuilder(RequireSettings settings, - string applicationPath, - IFileVersionProvider fileVersionProvider) + public TagBuilder GetTagBuilder(RequireSettings settings, string applicationPath, IFileVersionProvider fileVersionProvider) { - string url, filePathAttributeName = null; + string url, + filePathAttributeName = null; // Url priority. if (settings.DebugMode) { - url = settings.CdnMode - ? Coalesce(UrlCdnDebug, UrlDebug, UrlCdn, Url) - : Coalesce(UrlDebug, Url, UrlCdnDebug, UrlCdn); + url = settings.CdnMode ? Coalesce(UrlCdnDebug, UrlDebug, UrlCdn, Url) : Coalesce(UrlDebug, Url, UrlCdnDebug, UrlCdn); } else { - url = settings.CdnMode - ? Coalesce(UrlCdn, Url, UrlCdnDebug, UrlDebug) - : Coalesce(Url, UrlDebug, UrlCdn, UrlCdnDebug); + url = settings.CdnMode ? Coalesce(UrlCdn, Url, UrlCdnDebug, UrlDebug) : Coalesce(Url, UrlDebug, UrlCdn, UrlCdnDebug); } if (string.IsNullOrEmpty(url)) @@ -227,20 +223,23 @@ public TagBuilder GetTagBuilder(RequireSettings settings, } // If settings has value, it can override resource definition, otherwise use resource definition. - if (url != null && ((settings.AppendVersion.HasValue && settings.AppendVersion == true) || - (!settings.AppendVersion.HasValue && AppendVersion == true))) + if (url != null && ((settings.AppendVersion.HasValue && settings.AppendVersion == true) || (!settings.AppendVersion.HasValue && AppendVersion == true))) { url = fileVersionProvider.AddFileVersionToPath(applicationPath, url); } // Don't prefix cdn if the path includes a protocol, i.e. is an external url, or is in debug mode. - if (url != null && !settings.DebugMode && !string.IsNullOrEmpty(settings.CdnBaseUrl) && - + if ( + url != null + && !settings.DebugMode + && !string.IsNullOrEmpty(settings.CdnBaseUrl) + && // Don't evaluate with Uri.TryCreate as it produces incorrect results on Linux. - !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && - !url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && - !url.StartsWith("//", StringComparison.OrdinalIgnoreCase) && - !url.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) + !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) + && !url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) + && !url.StartsWith("//", StringComparison.OrdinalIgnoreCase) + && !url.StartsWith("file://", StringComparison.OrdinalIgnoreCase) + ) { url = settings.CdnBaseUrl + url; } @@ -263,24 +262,12 @@ public TagBuilder GetTagBuilder(RequireSettings settings, if (url == null && InnerContent != null) { // Inline style declaration. - tagBuilder = new TagBuilder("style") - { - Attributes = { - { "type", "text/css" } - } - }; + tagBuilder = new TagBuilder("style") { Attributes = { { "type", "text/css" } } }; } else { // Stylesheet resource. - tagBuilder = new TagBuilder("link") - { - TagRenderMode = TagRenderMode.SelfClosing, - Attributes = { - { "type", "text/css" }, - { "rel", "stylesheet" } - } - }; + tagBuilder = new TagBuilder("link") { TagRenderMode = TagRenderMode.SelfClosing, Attributes = { { "type", "text/css" }, { "rel", "stylesheet" } } }; filePathAttributeName = "href"; } break; @@ -359,9 +346,7 @@ public override bool Equals(object obj) } var that = (ResourceDefinition)obj; - return string.Equals(that.Name, Name) && - string.Equals(that.Type, Type) && - string.Equals(that.Version, Version); + return string.Equals(that.Name, Name) && string.Equals(that.Type, Type) && string.Equals(that.Version, Version); } public override int GetHashCode() diff --git a/src/OrchardCore/OrchardCore.ResourceManagement.Core/Razor/ResourceCdnHelperExtensions.cs b/src/OrchardCore/OrchardCore.ResourceManagement.Core/Razor/ResourceCdnHelperExtensions.cs index 3801055802c..d6e1c823e37 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement.Core/Razor/ResourceCdnHelperExtensions.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement.Core/Razor/ResourceCdnHelperExtensions.cs @@ -23,19 +23,22 @@ public static string ResourceUrl(this IOrchardHelper orchardHelper, string resou } // If append version is set, allow it to override the site setting. - if (resourcePath != null && ((appendVersion.HasValue && appendVersion == true) || - (!appendVersion.HasValue && options.AppendVersion == true))) + if (resourcePath != null && ((appendVersion.HasValue && appendVersion == true) || (!appendVersion.HasValue && options.AppendVersion == true))) { resourcePath = fileVersionProvider.AddFileVersionToPath(orchardHelper.HttpContext.Request.PathBase, resourcePath); } // Don't prefix cdn if the path includes a protocol, i.e. is an external url, or is in debug mode. - if (!options.DebugMode && !string.IsNullOrEmpty(options.CdnBaseUrl) && + if ( + !options.DebugMode + && !string.IsNullOrEmpty(options.CdnBaseUrl) + && // Don't evaluate with Uri.TryCreate as it produces incorrect results on Linux. - !resourcePath.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && - !resourcePath.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && - !resourcePath.StartsWith("//", StringComparison.OrdinalIgnoreCase) && - !resourcePath.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) + !resourcePath.StartsWith("https://", StringComparison.OrdinalIgnoreCase) + && !resourcePath.StartsWith("http://", StringComparison.OrdinalIgnoreCase) + && !resourcePath.StartsWith("//", StringComparison.OrdinalIgnoreCase) + && !resourcePath.StartsWith("file://", StringComparison.OrdinalIgnoreCase) + ) { resourcePath = options.CdnBaseUrl + resourcePath; } diff --git a/src/OrchardCore/OrchardCore.ResourceManagement/ResourceManager.cs b/src/OrchardCore/OrchardCore.ResourceManagement/ResourceManager.cs index 3543b3aabef..9bf286390cf 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement/ResourceManager.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement/ResourceManager.cs @@ -26,9 +26,7 @@ public class ResourceManager : IResourceManager private HashSet _localStyles; private readonly ResourceManagementOptions _options; - public ResourceManager( - IOptions options, - IFileVersionProvider fileVersionProvider) + public ResourceManager(IOptions options, IFileVersionProvider fileVersionProvider) { _options = options.Value; _fileVersionProvider = fileVersionProvider; @@ -36,7 +34,6 @@ public ResourceManager( _builtResources = new Dictionary(StringComparer.OrdinalIgnoreCase); } - public ResourceManifest InlineManifest => _dynamicManifest ??= new ResourceManifest(); public RequireSettings RegisterResource(string resourceType, string resourceName) @@ -47,11 +44,7 @@ public RequireSettings RegisterResource(string resourceType, string resourceName var key = new ResourceTypeName(resourceType, resourceName); if (!_required.TryGetValue(key, out var settings)) { - settings = new RequireSettings(_options) - { - Type = resourceType, - Name = resourceName - }; + settings = new RequireSettings(_options) { Type = resourceType, Name = resourceName }; _required[key] = settings; } _builtResources[resourceType] = null; @@ -75,9 +68,7 @@ public RequireSettings RegisterUrl(string resourceType, string resourcePath, str resourceDebugPath = string.Concat(_options.ContentBasePath, resourceDebugPath.AsSpan(1)); } - return RegisterResource( - resourceType, - GetResourceKey(resourcePath, resourceDebugPath)).Define(d => d.SetUrl(resourcePath, resourceDebugPath)); + return RegisterResource(resourceType, GetResourceKey(resourcePath, resourceDebugPath)).Define(d => d.SetUrl(resourcePath, resourceDebugPath)); } public void RegisterHeadScript(IHtmlContent script) @@ -149,10 +140,7 @@ private ResourceDefinition FindResource(RequireSettings settings, bool resolveIn return resource; } - private static ResourceDefinition FindMatchingResource( - IEnumerable>> stream, - RequireSettings settings, - string name) + private static ResourceDefinition FindMatchingResource(IEnumerable>> stream, RequireSettings settings, string name) { Version lower = null; Version upper = null; @@ -170,9 +158,7 @@ private static ResourceDefinition FindMatchingResource( { foreach (var resourceDefinition in r.Value) { - var version = resourceDefinition.Version != null - ? new Version(resourceDefinition.Version) - : null; + var version = resourceDefinition.Version != null ? new Version(resourceDefinition.Version) : null; if (lower != null) { @@ -310,8 +296,7 @@ public List DoGetRegisteredStyles() return _styles ?? EmptyList.Instance; } - public IEnumerable GetRequiredResources(string resourceType) - => DoGetRequiredResources(resourceType); + public IEnumerable GetRequiredResources(string resourceType) => DoGetRequiredResources(resourceType); private ResourceRequiredContext[] DoGetRequiredResources(string resourceType) { @@ -323,14 +308,20 @@ private ResourceRequiredContext[] DoGetRequiredResources(string resourceType) var allResources = new ResourceDictionary(); foreach (var settings in ResolveRequiredResources(resourceType)) { - var resource = FindResource(settings) - ?? throw new InvalidOperationException($"Could not find a resource of type '{settings.Type}' named '{settings.Name}' with version '{settings.Version ?? "any"}'."); + var resource = + FindResource(settings) + ?? throw new InvalidOperationException( + $"Could not find a resource of type '{settings.Type}' named '{settings.Name}' with version '{settings.Version ?? "any"}'." + ); ExpandDependencies(resource, settings, allResources); } requiredResources = new ResourceRequiredContext[allResources.Count]; - int i, first = 0, byDependency = allResources.FirstCount, last = allResources.Count - allResources.LastCount; + int i, + first = 0, + byDependency = allResources.FirstCount, + last = allResources.Count - allResources.LastCount; foreach (DictionaryEntry entry in allResources) { var settings = (RequireSettings)entry.Value; @@ -358,10 +349,7 @@ private ResourceRequiredContext[] DoGetRequiredResources(string resourceType) return _builtResources[resourceType] = requiredResources; } - protected virtual void ExpandDependencies( - ResourceDefinition resource, - RequireSettings settings, - ResourceDictionary allResources) + protected virtual void ExpandDependencies(ResourceDefinition resource, RequireSettings settings, ResourceDictionary allResources) { if (resource == null) { @@ -392,17 +380,15 @@ protected virtual void ExpandDependencies( // (1) If a require exists for the resource, combine with it. Last settings in gets preference for its specified values. // (2) If no require already exists, form a new settings object based on the given one but with its own type/name. - var dependencySettings = (((RequireSettings)allResources[resource]) - ?.NewAndCombine(settings) + var dependencySettings = ( + ((RequireSettings)allResources[resource])?.NewAndCombine(settings) ?? new RequireSettings(_options) { Name = resource.Name, Type = resource.Type, Position = resource.Position - } - .Combine(settings)) - .CombinePosition(settings) - ; + }.Combine(settings) + ).CombinePosition(settings); if (dependencies != null) { @@ -654,8 +640,10 @@ public void RenderLocalScript(RequireSettings settings, TextWriter writer) foreach (var context in localScripts) { - if ((context.Settings.Location == ResourceLocation.Unspecified || context.Settings.Location == ResourceLocation.Inline) && - (_localScripts.Add(context.Settings.Name) || context.Settings.Name == settings.Name)) + if ( + (context.Settings.Location == ResourceLocation.Unspecified || context.Settings.Location == ResourceLocation.Inline) + && (_localScripts.Add(context.Settings.Name) || context.Settings.Name == settings.Name) + ) { if (!first) { @@ -678,8 +666,7 @@ public void RenderLocalStyle(RequireSettings settings, TextWriter writer) foreach (var context in localStyles) { - if (context.Settings.Location == ResourceLocation.Inline && - (_localStyles.Add(context.Settings.Name) || context.Settings.Name == settings.Name)) + if (context.Settings.Location == ResourceLocation.Inline && (_localStyles.Add(context.Settings.Name) || context.Settings.Name == settings.Name)) { if (!first) { diff --git a/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ResourcesTagHelper.cs b/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ResourcesTagHelper.cs index 54d4e608987..9c3051256ed 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ResourcesTagHelper.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ResourcesTagHelper.cs @@ -24,9 +24,7 @@ public class ResourcesTagHelper : TagHelper private readonly IResourceManager _resourceManager; private readonly ILogger _logger; - public ResourcesTagHelper( - IResourceManager resourceManager, - ILogger logger) + public ResourcesTagHelper(IResourceManager resourceManager, ILogger logger) { _resourceManager = resourceManager; _logger = logger; diff --git a/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ScriptTagHelper.cs b/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ScriptTagHelper.cs index acedeec426f..84832de8a54 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ScriptTagHelper.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ScriptTagHelper.cs @@ -203,8 +203,7 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu if (!childContent.IsEmptyOrWhiteSpace) { // Inline content definition - _resourceManager.InlineManifest.DefineScript(Name) - .SetInnerContent(childContent.GetContent()); + _resourceManager.InlineManifest.DefineScript(Name).SetInnerContent(childContent.GetContent()); } if (At == ResourceLocation.Inline) diff --git a/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/StyleTagHelper.cs b/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/StyleTagHelper.cs index 486128229ef..e99695b5778 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/StyleTagHelper.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/StyleTagHelper.cs @@ -162,8 +162,7 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu if (!childContent.IsEmptyOrWhiteSpace) { // Inline named style definition - _resourceManager.InlineManifest.DefineStyle(Name) - .SetInnerContent(childContent.GetContent()); + _resourceManager.InlineManifest.DefineStyle(Name).SetInnerContent(childContent.GetContent()); } if (At == ResourceLocation.Inline) diff --git a/src/OrchardCore/OrchardCore.Roles.Core/CommonPermissions.cs b/src/OrchardCore/OrchardCore.Roles.Core/CommonPermissions.cs index 1c6f57487c3..897adb7b971 100644 --- a/src/OrchardCore/OrchardCore.Roles.Core/CommonPermissions.cs +++ b/src/OrchardCore/OrchardCore.Roles.Core/CommonPermissions.cs @@ -13,10 +13,6 @@ public class CommonPermissions private static readonly Permission _assignRole = new("AssignRole_{0}", "Assign Role - {0}", new[] { AssignRoles, ManageRoles }); public static Permission CreatePermissionForAssignRole(string name) => - new( - string.Format(_assignRole.Name, name), - string.Format(_assignRole.Description, name), - _assignRole.ImpliedBy - ); + new(string.Format(_assignRole.Name, name), string.Format(_assignRole.Description, name), _assignRole.ImpliedBy); } } diff --git a/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionEvaluator.cs b/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionEvaluator.cs index f1cff188592..e9e01f33aaf 100644 --- a/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionEvaluator.cs +++ b/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionEvaluator.cs @@ -2,13 +2,13 @@ namespace OrchardCore.Rules { - public abstract class ConditionEvaluator : IConditionEvaluator where T : Condition + public abstract class ConditionEvaluator : IConditionEvaluator + where T : Condition { protected static ValueTask False => new(false); protected static ValueTask True => new(true); - ValueTask IConditionEvaluator.EvaluateAsync(Condition condition) - => EvaluateAsync(condition as T); + ValueTask IConditionEvaluator.EvaluateAsync(Condition condition) => EvaluateAsync(condition as T); public abstract ValueTask EvaluateAsync(T condition); } diff --git a/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionOperator.cs b/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionOperator.cs index 4c02e0238a3..78d2bd4ce5b 100644 --- a/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionOperator.cs +++ b/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionOperator.cs @@ -1,7 +1,4 @@ namespace OrchardCore.Rules { - public abstract class ConditionOperator - { - - } + public abstract class ConditionOperator { } } diff --git a/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionOperatorOptions.cs b/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionOperatorOptions.cs index 4a07bfa23b0..743990989ee 100644 --- a/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionOperatorOptions.cs +++ b/src/OrchardCore/OrchardCore.Rules.Abstractions/ConditionOperatorOptions.cs @@ -10,37 +10,24 @@ public class ConditionOperatorOptions private FrozenDictionary _factories; private FrozenDictionary _conditionOperatorOptionByType; - public IReadOnlyDictionary Factories - => _factories ??= Operators.ToFrozenDictionary(x => x.Factory.Name, x => x.Factory); + public IReadOnlyDictionary Factories => _factories ??= Operators.ToFrozenDictionary(x => x.Factory.Name, x => x.Factory); - public IReadOnlyDictionary ConditionOperatorOptionByType - => _conditionOperatorOptionByType ??= Operators.ToFrozenDictionary(x => x.Operator, x => x); + public IReadOnlyDictionary ConditionOperatorOptionByType => + _conditionOperatorOptionByType ??= Operators.ToFrozenDictionary(x => x.Operator, x => x); public List Operators { get; set; } = []; } - public class ConditionOperatorOption : ConditionOperatorOption where TLocalizer : class + public class ConditionOperatorOption : ConditionOperatorOption + where TLocalizer : class { - public ConditionOperatorOption( - Func displayText, - IOperatorComparer comparer, - Type operatorType, - IConditionOperatorFactory factory) : base( - (sp) => displayText((IStringLocalizer)sp.GetService(typeof(IStringLocalizer<>).MakeGenericType(typeof(TLocalizer)))), - comparer, - operatorType, - factory) - { - } + public ConditionOperatorOption(Func displayText, IOperatorComparer comparer, Type operatorType, IConditionOperatorFactory factory) + : base((sp) => displayText((IStringLocalizer)sp.GetService(typeof(IStringLocalizer<>).MakeGenericType(typeof(TLocalizer)))), comparer, operatorType, factory) { } } public class ConditionOperatorOption { - public ConditionOperatorOption( - Func displayText, - IOperatorComparer comparer, - Type operatorType, - IConditionOperatorFactory factory) + public ConditionOperatorOption(Func displayText, IOperatorComparer comparer, Type operatorType, IConditionOperatorFactory factory) { DisplayText = displayText; Comparer = comparer; diff --git a/src/OrchardCore/OrchardCore.Rules.Abstractions/IConditionFactory.cs b/src/OrchardCore/OrchardCore.Rules.Abstractions/IConditionFactory.cs index ee776bdbb8b..51b9d8f968a 100644 --- a/src/OrchardCore/OrchardCore.Rules.Abstractions/IConditionFactory.cs +++ b/src/OrchardCore/OrchardCore.Rules.Abstractions/IConditionFactory.cs @@ -6,15 +6,12 @@ public interface IConditionFactory Condition Create(); } - public class ConditionFactory : IConditionFactory where TCondition : Condition, new() + public class ConditionFactory : IConditionFactory + where TCondition : Condition, new() { private static readonly string _typeName = typeof(TCondition).Name; public string Name => _typeName; - public Condition Create() - => new TCondition() - { - Name = Name, - }; + public Condition Create() => new TCondition() { Name = Name, }; } } diff --git a/src/OrchardCore/OrchardCore.Rules.Abstractions/IConditionOperatorFactory.cs b/src/OrchardCore/OrchardCore.Rules.Abstractions/IConditionOperatorFactory.cs index 9fb9c1b7364..ce518a8a96e 100644 --- a/src/OrchardCore/OrchardCore.Rules.Abstractions/IConditionOperatorFactory.cs +++ b/src/OrchardCore/OrchardCore.Rules.Abstractions/IConditionOperatorFactory.cs @@ -6,12 +6,12 @@ public interface IConditionOperatorFactory ConditionOperator Create(); } - public class ConditionOperatorFactory : IConditionOperatorFactory where TConditionOperator : ConditionOperator, new() + public class ConditionOperatorFactory : IConditionOperatorFactory + where TConditionOperator : ConditionOperator, new() { private static readonly string _typeName = typeof(TConditionOperator).Name; public string Name => _typeName; - public ConditionOperator Create() - => new TConditionOperator(); + public ConditionOperator Create() => new TConditionOperator(); } } diff --git a/src/OrchardCore/OrchardCore.Rules.Abstractions/INegateOperator.cs b/src/OrchardCore/OrchardCore.Rules.Abstractions/INegateOperator.cs index 19f06975943..c29fdbeeedb 100644 --- a/src/OrchardCore/OrchardCore.Rules.Abstractions/INegateOperator.cs +++ b/src/OrchardCore/OrchardCore.Rules.Abstractions/INegateOperator.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Rules { - public interface INegateOperator - { - } + public interface INegateOperator { } } diff --git a/src/OrchardCore/OrchardCore.Rules.Abstractions/OperatorComparer.cs b/src/OrchardCore/OrchardCore.Rules.Abstractions/OperatorComparer.cs index a227b35b8ca..668c4e54e2e 100644 --- a/src/OrchardCore/OrchardCore.Rules.Abstractions/OperatorComparer.cs +++ b/src/OrchardCore/OrchardCore.Rules.Abstractions/OperatorComparer.cs @@ -1,9 +1,10 @@ namespace OrchardCore.Rules { - public abstract class OperatorComparer : IOperatorComparer where TConditionOperator : ConditionOperator + public abstract class OperatorComparer : IOperatorComparer + where TConditionOperator : ConditionOperator { - bool IOperatorComparer.Compare(ConditionOperator conditionOperator, object a, object b) - => Compare((TConditionOperator)conditionOperator, (TCompare)a, (TCompare)b); + bool IOperatorComparer.Compare(ConditionOperator conditionOperator, object a, object b) => Compare((TConditionOperator)conditionOperator, (TCompare)a, (TCompare)b); + public abstract bool Compare(TConditionOperator conditionOperator, TCompare a, TCompare b); } } diff --git a/src/OrchardCore/OrchardCore.Rules.Abstractions/Rule.cs b/src/OrchardCore/OrchardCore.Rules.Abstractions/Rule.cs index b4a8c88c3e2..caf892a421e 100644 --- a/src/OrchardCore/OrchardCore.Rules.Abstractions/Rule.cs +++ b/src/OrchardCore/OrchardCore.Rules.Abstractions/Rule.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Rules { - public class Rule : ConditionGroup - { - } + public class Rule : ConditionGroup { } } diff --git a/src/OrchardCore/OrchardCore.Rules.Abstractions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Rules.Abstractions/ServiceCollectionExtensions.cs index 4f81b66d490..6948a8920a0 100644 --- a/src/OrchardCore/OrchardCore.Rules.Abstractions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Rules.Abstractions/ServiceCollectionExtensions.cs @@ -24,7 +24,6 @@ public static IServiceCollection AddCondition(this IServiceCollection services, public static IServiceCollection AddCondition(this IServiceCollection services) where TCondition : Condition where TConditionEvaluator : IConditionEvaluator - where TConditionFactory : IConditionFactory - => services.AddCondition(typeof(TCondition), typeof(TConditionEvaluator), typeof(TConditionFactory)); + where TConditionFactory : IConditionFactory => services.AddCondition(typeof(TCondition), typeof(TConditionEvaluator), typeof(TConditionFactory)); } } diff --git a/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchFormViewModel.cs b/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchFormViewModel.cs index 56f042b567b..78ad2dee449 100644 --- a/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchFormViewModel.cs +++ b/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchFormViewModel.cs @@ -6,14 +6,10 @@ namespace OrchardCore.Search.ViewModels public class SearchFormViewModel : ShapeViewModel { public SearchFormViewModel() - : base("Search__Form") - { - } + : base("Search__Form") { } public SearchFormViewModel(string shapeType) - : base(shapeType) - { - } + : base(shapeType) { } public string Terms { get; set; } diff --git a/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchIndexViewModel.cs b/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchIndexViewModel.cs index 5c1578ad340..eeab5967ed4 100644 --- a/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchIndexViewModel.cs +++ b/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchIndexViewModel.cs @@ -8,14 +8,10 @@ namespace OrchardCore.Search.ViewModels public class SearchIndexViewModel : ShapeViewModel { public SearchIndexViewModel() - : base("Search__List") - { - } + : base("Search__List") { } public SearchIndexViewModel(string shapeType) - : base(shapeType) - { - } + : base(shapeType) { } public string Terms { get; set; } diff --git a/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchResultsViewModel.cs b/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchResultsViewModel.cs index 3c67016640d..d428b0a2639 100644 --- a/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchResultsViewModel.cs +++ b/src/OrchardCore/OrchardCore.Search.Abstractions/ViewModels/SearchResultsViewModel.cs @@ -8,14 +8,10 @@ namespace OrchardCore.Search.ViewModels public class SearchResultsViewModel : ShapeViewModel { public SearchResultsViewModel() - : base("Search__Results") - { - } + : base("Search__Results") { } public SearchResultsViewModel(string shapeType) - : base(shapeType) - { - } + : base(shapeType) { } [BindNever] public IEnumerable ContentItems { get; set; } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexDeploymentSource.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexDeploymentSource.cs index 0882725715b..1645f82c1db 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexDeploymentSource.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexDeploymentSource.cs @@ -28,19 +28,12 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan { if (indicesToAdd.Contains(index.IndexName)) { - var indexSettingsDict = new Dictionary - { - { index.IndexName, index }, - }; + var indexSettingsDict = new Dictionary { { index.IndexName, index }, }; data.Add(JObject.FromObject(indexSettingsDict)); } } - result.Steps.Add(new JsonObject - { - ["name"] = nameof(AzureAISearchIndexSettings), - ["Indices"] = data, - }); + result.Steps.Add(new JsonObject { ["name"] = nameof(AzureAISearchIndexSettings), ["Indices"] = data, }); } } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexRebuildDeploymentSource.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexRebuildDeploymentSource.cs index f334d6e6e26..667b33f1fb7 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexRebuildDeploymentSource.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexRebuildDeploymentSource.cs @@ -17,12 +17,14 @@ public Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult var indicesToRebuild = rebuildStep.IncludeAll ? [] : rebuildStep.Indices; - result.Steps.Add(new JsonObject - { - ["name"] = Name, - ["includeAll"] = rebuildStep.IncludeAll, - ["Indices"] = JArray.FromObject(indicesToRebuild), - }); + result.Steps.Add( + new JsonObject + { + ["name"] = Name, + ["includeAll"] = rebuildStep.IncludeAll, + ["Indices"] = JArray.FromObject(indicesToRebuild), + } + ); return Task.CompletedTask; } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexResetDeploymentSource.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexResetDeploymentSource.cs index 15cb2413052..6260e4e8603 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexResetDeploymentSource.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchIndexResetDeploymentSource.cs @@ -17,12 +17,14 @@ public Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult var indicesToReset = resetStep.IncludeAll ? [] : resetStep.Indices; - result.Steps.Add(new JsonObject - { - ["name"] = Name, - ["includeAll"] = resetStep.IncludeAll, - ["Indices"] = JArray.FromObject(indicesToReset), - }); + result.Steps.Add( + new JsonObject + { + ["name"] = Name, + ["includeAll"] = resetStep.IncludeAll, + ["Indices"] = JArray.FromObject(indicesToReset), + } + ); return Task.CompletedTask; } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchSettingsDeploymentSource.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchSettingsDeploymentSource.cs index 14f24ef9ccc..41dd72dc2b0 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchSettingsDeploymentSource.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Deployment/AzureAISearchSettingsDeploymentSource.cs @@ -23,10 +23,6 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan var settings = site.As(); - result.Steps.Add(new JsonObject - { - ["name"] = "Settings", - [nameof(AzureAISearchSettings)] = JObject.FromObject(settings), - }); + result.Steps.Add(new JsonObject { ["name"] = "Settings", [nameof(AzureAISearchSettings)] = JObject.FromObject(settings), }); } } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Handlers/AzureAISearchIndexingContentHandler.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Handlers/AzureAISearchIndexingContentHandler.cs index 519bad65a26..30d257aeec9 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Handlers/AzureAISearchIndexingContentHandler.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Handlers/AzureAISearchIndexingContentHandler.cs @@ -23,9 +23,13 @@ public class AzureAISearchIndexingContentHandler(IHttpContextAccessor httpContex private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; public override Task PublishedAsync(PublishContentContext context) => AddContextAsync(context); + public override Task CreatedAsync(CreateContentContext context) => AddContextAsync(context); + public override Task UpdatedAsync(UpdateContentContext context) => AddContextAsync(context); + public override Task RemovedAsync(RemoveContentContext context) => AddContextAsync(context); + public override Task UnpublishedAsync(PublishContentContext context) => AddContextAsync(context); private Task AddContextAsync(ContentContextBase context) @@ -74,8 +78,10 @@ private static async Task IndexingAsync(ShellScope scope, IEnumerable - /// This event is invoked before removing an existing that already exists. + /// This event is invoked before removing an existing that already exists. /// /// /// diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchDefaultOptions.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchDefaultOptions.cs index 46d8ccecf81..693ceddd94e 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchDefaultOptions.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchDefaultOptions.cs @@ -7,7 +7,7 @@ public class AzureAISearchDefaultOptions { public const string DefaultAnalyzer = LexicalAnalyzerName.Values.StandardLucene; - public readonly static string[] DefaultAnalyzers = + public static readonly string[] DefaultAnalyzers = [ LexicalAnalyzerName.Values.ArMicrosoft, LexicalAnalyzerName.Values.ArLucene, @@ -120,17 +120,13 @@ public class AzureAISearchDefaultOptions private bool _configurationExists; - public void SetConfigurationExists(bool configurationExists) - => _configurationExists = configurationExists; + public void SetConfigurationExists(bool configurationExists) => _configurationExists = configurationExists; - public bool ConfigurationExists() - => _configurationExists; + public bool ConfigurationExists() => _configurationExists; private bool _fileConfigurationExists; - public void SetFileConfigurationExists(bool fileConfigurationExists) - => _fileConfigurationExists = fileConfigurationExists; + public void SetFileConfigurationExists(bool fileConfigurationExists) => _fileConfigurationExists = fileConfigurationExists; - public bool FileConfigurationExists() - => _fileConfigurationExists; + public bool FileConfigurationExists() => _fileConfigurationExists; } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchIndexMap.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchIndexMap.cs index d62dc39e881..449f1970289 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchIndexMap.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchIndexMap.cs @@ -14,10 +14,7 @@ public class AzureAISearchIndexMap public DocumentIndexOptions Options { get; set; } - public AzureAISearchIndexMap() - { - - } + public AzureAISearchIndexMap() { } public AzureAISearchIndexMap(string azureFieldKey, Types type) { diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchIndexSettings.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchIndexSettings.cs index fcfa680a7aa..d213c765ac2 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchIndexSettings.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Models/AzureAISearchIndexSettings.cs @@ -26,14 +26,11 @@ public class AzureAISearchIndexSettings private long _lastTaskId = 0; - public long GetLastTaskId() - => _lastTaskId; + public long GetLastTaskId() => _lastTaskId; - public void SetLastTaskId(long lastTaskId) - => _lastTaskId = lastTaskId; + public void SetLastTaskId(long lastTaskId) => _lastTaskId = lastTaskId; // The dictionary key should be indexingKey Not AzureFieldKey. - public Dictionary> GetMaps() - => IndexMappings.GroupBy(group => group.IndexingKey) - .ToDictionary(group => group.Key, group => group.Select(map => map)); + public Dictionary> GetMaps() => + IndexMappings.GroupBy(group => group.IndexingKey).ToDictionary(group => group.Key, group => group.Select(map => map)); } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Permissions.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Permissions.cs index 38e9d5db8ad..f57c777c708 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Permissions.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Permissions.cs @@ -11,10 +11,7 @@ public class Permissions(AzureAISearchIndexSettingsService indexSettingsService) public async Task> GetPermissionsAsync() { - var permissions = new List() - { - AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes, - }; + var permissions = new List() { AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes, }; var indexSettings = await _indexSettingsService.GetSettingsAsync(); @@ -27,14 +24,5 @@ public async Task> GetPermissionsAsync() } public IEnumerable GetDefaultStereotypes() => - [ - new PermissionStereotype - { - Name = "Administrator", - Permissions = - [ - AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes, - ], - }, - ]; + [new PermissionStereotype { Name = "Administrator", Permissions = [AzureAISearchIndexPermissionHelper.ManageAzureAISearchIndexes,], },]; } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexRebuildStep.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexRebuildStep.cs index af69fba5840..a8520b6f243 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexRebuildStep.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexRebuildStep.cs @@ -32,27 +32,30 @@ public async Task ExecuteAsync(RecipeExecutionContext context) return; } - await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync(AzureAISearchIndexRebuildDeploymentSource.Name, async scope => - { - var searchIndexingService = scope.ServiceProvider.GetService(); - var indexSettingsService = scope.ServiceProvider.GetService(); - var indexDocumentManager = scope.ServiceProvider.GetRequiredService(); - var indexManager = scope.ServiceProvider.GetRequiredService(); + await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync( + AzureAISearchIndexRebuildDeploymentSource.Name, + async scope => + { + var searchIndexingService = scope.ServiceProvider.GetService(); + var indexSettingsService = scope.ServiceProvider.GetService(); + var indexDocumentManager = scope.ServiceProvider.GetRequiredService(); + var indexManager = scope.ServiceProvider.GetRequiredService(); - var indexSettings = model.IncludeAll - ? await indexSettingsService.GetSettingsAsync() - : (await indexSettingsService.GetSettingsAsync()).Where(x => model.Indices.Contains(x.IndexName, StringComparer.OrdinalIgnoreCase)); + var indexSettings = model.IncludeAll + ? await indexSettingsService.GetSettingsAsync() + : (await indexSettingsService.GetSettingsAsync()).Where(x => model.Indices.Contains(x.IndexName, StringComparer.OrdinalIgnoreCase)); - foreach (var settings in indexSettings) - { - settings.SetLastTaskId(0); - settings.IndexMappings = await indexDocumentManager.GetMappingsAsync(settings.IndexedContentTypes); - await indexSettingsService.UpdateAsync(settings); + foreach (var settings in indexSettings) + { + settings.SetLastTaskId(0); + settings.IndexMappings = await indexDocumentManager.GetMappingsAsync(settings.IndexedContentTypes); + await indexSettingsService.UpdateAsync(settings); - await indexManager.RebuildAsync(settings); - } + await indexManager.RebuildAsync(settings); + } - await searchIndexingService.ProcessContentItemsAsync(indexSettings.Select(settings => settings.IndexName).ToArray()); - }); + await searchIndexingService.ProcessContentItemsAsync(indexSettings.Select(settings => settings.IndexName).ToArray()); + } + ); } } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexResetStep.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexResetStep.cs index c61263dd321..68226887bee 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexResetStep.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexResetStep.cs @@ -32,33 +32,36 @@ public async Task ExecuteAsync(RecipeExecutionContext context) return; } - await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync(AzureAISearchIndexRebuildDeploymentSource.Name, async scope => - { - var searchIndexingService = scope.ServiceProvider.GetService(); - var indexSettingsService = scope.ServiceProvider.GetService(); - var indexManager = scope.ServiceProvider.GetRequiredService(); - var indexDocumentManager = scope.ServiceProvider.GetRequiredService(); - - var indexSettings = model.IncludeAll - ? await indexSettingsService.GetSettingsAsync() - : (await indexSettingsService.GetSettingsAsync()).Where(x => model.Indices.Contains(x.IndexName, StringComparer.OrdinalIgnoreCase)); - - foreach (var settings in indexSettings) + await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync( + AzureAISearchIndexRebuildDeploymentSource.Name, + async scope => { - settings.SetLastTaskId(0); - settings.IndexMappings = await indexDocumentManager.GetMappingsAsync(settings.IndexedContentTypes); + var searchIndexingService = scope.ServiceProvider.GetService(); + var indexSettingsService = scope.ServiceProvider.GetService(); + var indexManager = scope.ServiceProvider.GetRequiredService(); + var indexDocumentManager = scope.ServiceProvider.GetRequiredService(); + + var indexSettings = model.IncludeAll + ? await indexSettingsService.GetSettingsAsync() + : (await indexSettingsService.GetSettingsAsync()).Where(x => model.Indices.Contains(x.IndexName, StringComparer.OrdinalIgnoreCase)); - if (!await indexManager.ExistsAsync(settings.IndexName)) + foreach (var settings in indexSettings) { - settings.IndexFullName = indexManager.GetFullIndexName(settings.IndexName); + settings.SetLastTaskId(0); + settings.IndexMappings = await indexDocumentManager.GetMappingsAsync(settings.IndexedContentTypes); - await indexManager.CreateAsync(settings); + if (!await indexManager.ExistsAsync(settings.IndexName)) + { + settings.IndexFullName = indexManager.GetFullIndexName(settings.IndexName); + + await indexManager.CreateAsync(settings); + } + + await indexSettingsService.UpdateAsync(settings); } - await indexSettingsService.UpdateAsync(settings); + await searchIndexingService.ProcessContentItemsAsync(indexSettings.Select(settings => settings.IndexName).ToArray()); } - - await searchIndexingService.ProcessContentItemsAsync(indexSettings.Select(settings => settings.IndexName).ToArray()); - }); + ); } } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexSettingsStep.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexSettingsStep.cs index d48f4159295..c51c82bc453 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexSettingsStep.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Recipes/AzureAISearchIndexSettingsStep.cs @@ -18,7 +18,7 @@ public class AzureAISearchIndexSettingsStep( AzureAIIndexDocumentManager azureAIIndexDocumentManager, AzureAISearchIndexSettingsService azureAISearchIndexSettingsService, ILogger logger - ) : IRecipeStepHandler +) : IRecipeStepHandler { public const string Name = "azureai-index-create"; @@ -68,7 +68,11 @@ public async Task ExecuteAsync(RecipeExecutionContext context) if (indexSettings.IndexedContentTypes == null || indexSettings.IndexedContentTypes.Length == 0) { - _logger.LogError("No {fieldName} were provided in the recipe step. IndexName: {indexName}.", nameof(indexSettings.IndexedContentTypes), indexSettings.IndexName); + _logger.LogError( + "No {fieldName} were provided in the recipe step. IndexName: {indexName}.", + nameof(indexSettings.IndexedContentTypes), + indexSettings.IndexName + ); continue; } @@ -86,11 +90,14 @@ public async Task ExecuteAsync(RecipeExecutionContext context) } } - await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync(AzureAISearchIndexRebuildDeploymentSource.Name, async scope => - { - var searchIndexingService = scope.ServiceProvider.GetService(); + await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync( + AzureAISearchIndexRebuildDeploymentSource.Name, + async scope => + { + var searchIndexingService = scope.ServiceProvider.GetService(); - await searchIndexingService.ProcessContentItemsAsync(indexNames.ToArray()); - }); + await searchIndexingService.ProcessContentItemsAsync(indexNames.ToArray()); + } + ); } } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAIClientFactory.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAIClientFactory.cs index 0aafa7da263..aa5b5510d76 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAIClientFactory.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAIClientFactory.cs @@ -81,6 +81,5 @@ public SearchIndexClient CreateSearchIndexClient() return _searchIndexClient; } - private ManagedIdentityCredential GetManagedIdentityCredential() - => new(_defaultOptions.IdentityClientId); + private ManagedIdentityCredential GetManagedIdentityCredential() => new(_defaultOptions.IdentityClientId); } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchDefaultOptionsConfigurations.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchDefaultOptionsConfigurations.cs index 51b799e4e70..5532366773f 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchDefaultOptionsConfigurations.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchDefaultOptionsConfigurations.cs @@ -16,10 +16,7 @@ public class AzureAISearchDefaultOptionsConfigurations : IConfigureOptions() - ?? new AzureAISearchDefaultOptions(); + var fileOptions = _shellConfiguration.GetSection("OrchardCore_AzureAISearch").Get() ?? new AzureAISearchDefaultOptions(); // This should be called first to set whether or not the file configs are set or not. options.SetFileConfigurationExists(HasConnectionInfo(fileOptions)); @@ -37,9 +33,7 @@ public async void Configure(AzureAISearchDefaultOptions options) // The DisableUIConfiguration should always be set using the file options only. options.DisableUIConfiguration = fileOptions.DisableUIConfiguration; - options.Analyzers = fileOptions.Analyzers == null || fileOptions.Analyzers.Length == 0 - ? AzureAISearchDefaultOptions.DefaultAnalyzers - : fileOptions.Analyzers; + options.Analyzers = fileOptions.Analyzers == null || fileOptions.Analyzers.Length == 0 ? AzureAISearchDefaultOptions.DefaultAnalyzers : fileOptions.Analyzers; if (fileOptions.DisableUIConfiguration) { diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexDocumentManager.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexDocumentManager.cs index 77027c013cd..1e6d9f7b3a0 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexDocumentManager.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexDocumentManager.cs @@ -20,7 +20,8 @@ public class AzureAIIndexDocumentManager( IContentManager contentManager, IEnumerable documentEvents, IEnumerable contentItemIndexHandlers, - ILogger logger) + ILogger logger +) { private readonly AzureAIClientFactory _clientFactory = clientFactory; private readonly AzureAISearchIndexManager _indexManager = indexManager; @@ -96,13 +97,18 @@ public async Task DeleteAllDocumentsAsync(string indexName) searchOptions.Select.Add(IndexingConstants.ContentItemIdKey); // Match-all documents. - var totalRecords = SearchAsync(indexName, "*", (doc) => - { - if (doc.TryGetValue(IndexingConstants.ContentItemIdKey, out var contentItemId)) + var totalRecords = SearchAsync( + indexName, + "*", + (doc) => { - contentItemIds.Add(contentItemId.ToString()); - } - }, searchOptions); + if (doc.TryGetValue(IndexingConstants.ContentItemIdKey, out var contentItemId)) + { + contentItemIds.Add(contentItemId.ToString()); + } + }, + searchOptions + ); } catch (Exception ex) { @@ -205,10 +211,7 @@ public async Task> GetMappingsAsync(string[] indexe continue; } - mapping.Add(new AzureAISearchIndexMap(fieldKey, entry.Type, entry.Options) - { - IndexingKey = entry.Name, - }); + mapping.Add(new AzureAISearchIndexMap(fieldKey, entry.Type, entry.Options) { IndexingKey = entry.Name, }); } } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexManager.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexManager.cs index c55d01a31d5..673b5a2ea78 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexManager.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexManager.cs @@ -21,7 +21,8 @@ public class AzureAISearchIndexManager( IOptions azureAIOptions, IEnumerable indexEvents, IMemoryCache memoryCache, - ShellSettings shellSettings) + ShellSettings shellSettings +) { public const string OwnerKey = "Content__ContentItem__Owner"; public const string AuthorKey = "Content__ContentItem__Author"; @@ -68,8 +69,7 @@ public async Task CreateAsync(AzureAISearchIndexSettings settings) return false; } - public async Task ExistsAsync(string indexName) - => await GetAsync(indexName) != null; + public async Task ExistsAsync(string indexName) => await GetAsync(indexName) != null; public async Task GetAsync(string indexName) { @@ -195,24 +195,10 @@ private static SearchIndex GetSearchIndex(string fullIndexName, AzureAISearchInd IsFilterable = true, IsSortable = true, }, - new SimpleField(IndexingConstants.ContentItemVersionIdKey, SearchFieldDataType.String) - { - IsFilterable = true, - IsSortable = true, - }, - new SimpleField(OwnerKey, SearchFieldDataType.String) - { - IsFilterable = true, - IsSortable = true, - }, - new SearchableField(DisplayTextAnalyzedKey) - { - AnalyzerName = settings.AnalyzerName, - }, - new SearchableField(FullTextKey) - { - AnalyzerName = settings.AnalyzerName, - }, + new SimpleField(IndexingConstants.ContentItemVersionIdKey, SearchFieldDataType.String) { IsFilterable = true, IsSortable = true, }, + new SimpleField(OwnerKey, SearchFieldDataType.String) { IsFilterable = true, IsSortable = true, }, + new SearchableField(DisplayTextAnalyzedKey) { AnalyzerName = settings.AnalyzerName, }, + new SearchableField(FullTextKey) { AnalyzerName = settings.AnalyzerName, }, }; foreach (var indexMap in settings.IndexMappings) @@ -229,35 +215,21 @@ private static SearchIndex GetSearchIndex(string fullIndexName, AzureAISearchInd if (indexMap.Options.HasFlag(Indexing.DocumentIndexOptions.Keyword)) { - searchFields.Add(new SimpleField(safeFieldName, GetFieldType(indexMap.Type)) - { - IsFilterable = true, - IsSortable = true, - }); + searchFields.Add(new SimpleField(safeFieldName, GetFieldType(indexMap.Type)) { IsFilterable = true, IsSortable = true, }); continue; } - searchFields.Add(new SearchableField(safeFieldName, true) - { - AnalyzerName = settings.AnalyzerName, - }); + searchFields.Add(new SearchableField(safeFieldName, true) { AnalyzerName = settings.AnalyzerName, }); } - var searchIndex = new SearchIndex(fullIndexName) - { - Fields = searchFields, - Suggesters = - { - new SearchSuggester("sg", FullTextKey), - }, - }; + var searchIndex = new SearchIndex(fullIndexName) { Fields = searchFields, Suggesters = { new SearchSuggester("sg", FullTextKey), }, }; return searchIndex; } - private static SearchFieldDataType GetFieldType(Types type) - => type switch + private static SearchFieldDataType GetFieldType(Types type) => + type switch { Types.Boolean => SearchFieldDataType.Boolean, Types.DateTime => SearchFieldDataType.DateTimeOffset, diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexSettingsService.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexSettingsService.cs index dcaa3ba470d..683f194d491 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexSettingsService.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexSettingsService.cs @@ -34,8 +34,7 @@ public async Task GetDocumentAsync() return document; } - public async Task> GetSettingsAsync() - => (await GetDocumentAsync()).IndexSettings.Values; + public async Task> GetSettingsAsync() => (await GetDocumentAsync()).IndexSettings.Values; public async Task GetAsync(string indexName) { @@ -63,6 +62,6 @@ public async Task DeleteAsync(string indexName) await DocumentManager.UpdateAsync(document); } - private static IDocumentManager DocumentManager - => ShellScope.Services.GetRequiredService>(); + private static IDocumentManager DocumentManager => + ShellScope.Services.GetRequiredService>(); } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexingService.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexingService.cs index 34d4b2c18ec..cac0bf2ad67 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexingService.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchIndexingService.cs @@ -33,7 +33,8 @@ public AzureAISearchIndexingService( IStore store, IContentManager contentManager, IEnumerable contentItemIndexHandlers, - ILogger logger) + ILogger logger + ) { _indexingTaskManager = indexingTaskManager; _azureAISearchIndexSettingsService = azureAISearchIndexSettingsService; @@ -56,9 +57,7 @@ public async Task ProcessContentItemsAsync(params string[] indexNames) } else { - indexSettings = indexesDocument.IndexSettings.Where(x => indexNames.Contains(x.Key, StringComparer.OrdinalIgnoreCase)) - .Select(x => x.Value) - .ToList(); + indexSettings = indexesDocument.IndexSettings.Where(x => indexNames.Contains(x.Key, StringComparer.OrdinalIgnoreCase)).Select(x => x.Value).ToList(); } if (indexSettings.Count == 0) @@ -93,10 +92,7 @@ public async Task ProcessContentItemsAsync(params string[] indexNames) break; } - var updatedContentItemIds = tasks - .Where(x => x.Type == IndexingTaskTypes.Update) - .Select(x => x.ContentItemId) - .ToArray(); + var updatedContentItemIds = tasks.Where(x => x.Type == IndexingTaskTypes.Update).Select(x => x.ContentItemId).ToArray(); Dictionary allPublished = null; Dictionary allLatest = null; @@ -108,14 +104,17 @@ public async Task ProcessContentItemsAsync(params string[] indexNames) if (indexSettings.Any(x => !x.IndexLatest)) { - var publishedContentItems = await readOnlySession.Query(index => index.Published && index.ContentType.IsIn(allContentTypes) && index.ContentItemId.IsIn(updatedContentItemIds)).ListAsync(); - allPublished = publishedContentItems.DistinctBy(x => x.ContentItemId) - .ToDictionary(k => k.ContentItemId); + var publishedContentItems = await readOnlySession + .Query(index => index.Published && index.ContentType.IsIn(allContentTypes) && index.ContentItemId.IsIn(updatedContentItemIds)) + .ListAsync(); + allPublished = publishedContentItems.DistinctBy(x => x.ContentItemId).ToDictionary(k => k.ContentItemId); } if (indexSettings.Any(x => x.IndexLatest)) { - var latestContentItems = await readOnlySession.Query(index => index.Latest && index.ContentType.IsIn(allContentTypes) && index.ContentItemId.IsIn(updatedContentItemIds)).ListAsync(); + var latestContentItems = await readOnlySession + .Query(index => index.Latest && index.ContentType.IsIn(allContentTypes) && index.ContentItemId.IsIn(updatedContentItemIds)) + .ListAsync(); allLatest = latestContentItems.DistinctBy(x => x.ContentItemId).ToDictionary(k => k.ContentItemId); } @@ -123,17 +122,28 @@ public async Task ProcessContentItemsAsync(params string[] indexNames) { if (task.Type == IndexingTaskTypes.Update) { - BuildIndexContext publishedIndexContext = null, latestIndexContext = null; + BuildIndexContext publishedIndexContext = null, + latestIndexContext = null; if (allPublished != null && allPublished.TryGetValue(task.ContentItemId, out var publishedContentItem)) { - publishedIndexContext = new BuildIndexContext(new DocumentIndex(task.ContentItemId, publishedContentItem.ContentItemVersionId), publishedContentItem, [publishedContentItem.ContentType], new AzureAISearchContentIndexSettings()); + publishedIndexContext = new BuildIndexContext( + new DocumentIndex(task.ContentItemId, publishedContentItem.ContentItemVersionId), + publishedContentItem, + [publishedContentItem.ContentType], + new AzureAISearchContentIndexSettings() + ); await _contentItemIndexHandlers.InvokeAsync(x => x.BuildIndexAsync(publishedIndexContext), _logger); } if (allLatest != null && allLatest.TryGetValue(task.ContentItemId, out var latestContentItem)) { - latestIndexContext = new BuildIndexContext(new DocumentIndex(task.ContentItemId, latestContentItem.ContentItemVersionId), latestContentItem, [latestContentItem.ContentType], new AzureAISearchContentIndexSettings()); + latestIndexContext = new BuildIndexContext( + new DocumentIndex(task.ContentItemId, latestContentItem.ContentItemVersionId), + latestContentItem, + [latestContentItem.ContentType], + new AzureAISearchContentIndexSettings() + ); await _contentItemIndexHandlers.InvokeAsync(x => x.BuildIndexAsync(latestIndexContext), _logger); } diff --git a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchService.cs b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchService.cs index f672b316f6f..1ced734c3fc 100644 --- a/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchService.cs +++ b/src/OrchardCore/OrchardCore.Search.AzureAI.Core/Services/AzureAISearchService.cs @@ -16,7 +16,7 @@ public class AzureAISearchService( AzureAISearchIndexSettingsService indexSettingsService, ILogger logger, IOptions azureAIOptions - ) : ISearchService +) : ISearchService { public const string Key = "Azure AI Search"; @@ -66,11 +66,7 @@ public async Task SearchAsync(string indexName, string term, int s { result.ContentItemIds = []; - var searchOptions = new SearchOptions() - { - Skip = start, - Size = size, - }; + var searchOptions = new SearchOptions() { Skip = start, Size = size, }; searchOptions.Select.Add(IndexingConstants.ContentItemIdKey); @@ -82,13 +78,18 @@ public async Task SearchAsync(string indexName, string term, int s } } - await _indexDocumentManager.SearchAsync(index, term, (doc) => - { - if (doc.TryGetValue(IndexingConstants.ContentItemIdKey, out var contentItemId)) + await _indexDocumentManager.SearchAsync( + index, + term, + (doc) => { - result.ContentItemIds.Add(contentItemId.ToString()); - } - }, searchOptions); + if (doc.TryGetValue(IndexingConstants.ContentItemIdKey, out var contentItemId)) + { + result.ContentItemIds.Add(contentItemId.ToString()); + } + }, + searchOptions + ); result.Success = true; } @@ -100,4 +101,3 @@ await _indexDocumentManager.SearchAsync(index, term, (doc) => return result; } } - diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Abstractions/IElasticsearchQueryService.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Abstractions/IElasticsearchQueryService.cs index 5f4dcf3c936..e6853d356a8 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Abstractions/IElasticsearchQueryService.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Abstractions/IElasticsearchQueryService.cs @@ -7,7 +7,7 @@ namespace OrchardCore.Search.Elasticsearch public interface IElasticSearchQueryService { /// - /// Provides a way to execute a search request in Elasticsearch based on a . + /// Provides a way to execute a search request in Elasticsearch based on a . /// /// IList<string>. Task> ExecuteQueryAsync(string indexName, QueryContainer query, List sort, int start = 0, int end = 20); diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexDeploymentSource.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexDeploymentSource.cs index 44e5493c995..60f3f3403f9 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexDeploymentSource.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexDeploymentSource.cs @@ -35,21 +35,14 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan { if (indicesToAdd.Contains(index.IndexName)) { - var indexSettingsDict = new Dictionary - { - { index.IndexName, index }, - }; + var indexSettingsDict = new Dictionary { { index.IndexName, index }, }; data.Add(JObject.FromObject(indexSettingsDict)); } } // Adding Elasticsearch settings. - result.Steps.Add(new JsonObject - { - ["name"] = "ElasticIndexSettings", - ["Indices"] = data, - }); + result.Steps.Add(new JsonObject { ["name"] = "ElasticIndexSettings", ["Indices"] = data, }); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexRebuildDeploymentSource.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexRebuildDeploymentSource.cs index ef573459423..3362efe3663 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexRebuildDeploymentSource.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexRebuildDeploymentSource.cs @@ -6,9 +6,7 @@ namespace OrchardCore.Search.Elasticsearch.Core.Deployment { public class ElasticIndexRebuildDeploymentSource : IDeploymentSource { - public ElasticIndexRebuildDeploymentSource() - { - } + public ElasticIndexRebuildDeploymentSource() { } public Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult result) { @@ -20,12 +18,14 @@ public Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult var indicesToRebuild = elasticIndexRebuildStep.IncludeAll ? [] : elasticIndexRebuildStep.Indices; - result.Steps.Add(new JsonObject - { - ["name"] = "elastic-index-rebuild", - ["includeAll"] = elasticIndexRebuildStep.IncludeAll, - ["Indices"] = JArray.FromObject(indicesToRebuild), - }); + result.Steps.Add( + new JsonObject + { + ["name"] = "elastic-index-rebuild", + ["includeAll"] = elasticIndexRebuildStep.IncludeAll, + ["Indices"] = JArray.FromObject(indicesToRebuild), + } + ); return Task.CompletedTask; } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexResetDeploymentSource.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexResetDeploymentSource.cs index 8df988254e5..42bb37e8eef 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexResetDeploymentSource.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticIndexResetDeploymentSource.cs @@ -6,9 +6,7 @@ namespace OrchardCore.Search.Elasticsearch.Core.Deployment { public class ElasticIndexResetDeploymentSource : IDeploymentSource { - public ElasticIndexResetDeploymentSource() - { - } + public ElasticIndexResetDeploymentSource() { } public Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult result) { @@ -21,12 +19,14 @@ public Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult var indicesToReset = elasticIndexResetStep.IncludeAll ? [] : elasticIndexResetStep.Indices; - result.Steps.Add(new JsonObject - { - ["name"] = "lucene-index-reset", - ["includeAll"] = elasticIndexResetStep.IncludeAll, - ["Indices"] = JArray.FromObject(indicesToReset), - }); + result.Steps.Add( + new JsonObject + { + ["name"] = "lucene-index-reset", + ["includeAll"] = elasticIndexResetStep.IncludeAll, + ["Indices"] = JArray.FromObject(indicesToReset), + } + ); return Task.CompletedTask; } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticSettingsDeploymentSource.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticSettingsDeploymentSource.cs index ecbe1d9e763..f933ddb226d 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticSettingsDeploymentSource.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Deployment/ElasticSettingsDeploymentSource.cs @@ -26,11 +26,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan var elasticSettings = await _elasticIndexingService.GetElasticSettingsAsync(); // Adding Elasticsearch settings - result.Steps.Add(new JsonObject - { - ["name"] = "Settings", - ["ElasticSettings"] = JObject.FromObject(elasticSettings), - }); + result.Steps.Add(new JsonObject { ["name"] = "Settings", ["ElasticSettings"] = JObject.FromObject(elasticSettings), }); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Handlers/ElasticIndexingContentHandler.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Handlers/ElasticIndexingContentHandler.cs index 73988833b3f..6c766ad6221 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Handlers/ElasticIndexingContentHandler.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Handlers/ElasticIndexingContentHandler.cs @@ -22,20 +22,15 @@ public class ElasticIndexingContentHandler(IHttpContextAccessor httpContextAcces private readonly List _contexts = []; private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; - public override Task PublishedAsync(PublishContentContext context) - => AddContextAsync(context); + public override Task PublishedAsync(PublishContentContext context) => AddContextAsync(context); - public override Task CreatedAsync(CreateContentContext context) - => AddContextAsync(context); + public override Task CreatedAsync(CreateContentContext context) => AddContextAsync(context); - public override Task UpdatedAsync(UpdateContentContext context) - => AddContextAsync(context); + public override Task UpdatedAsync(UpdateContentContext context) => AddContextAsync(context); - public override Task RemovedAsync(RemoveContentContext context) - => AddContextAsync(context); + public override Task RemovedAsync(RemoveContentContext context) => AddContextAsync(context); - public override Task UnpublishedAsync(PublishContentContext context) - => AddContextAsync(context); + public override Task UnpublishedAsync(PublishContentContext context) => AddContextAsync(context); private Task AddContextAsync(ContentContextBase context) { @@ -82,8 +77,10 @@ private static async Task IndexingAsync(ShellScope scope, IEnumerable x.BuildIndexAsync(buildIndexContext), logger); await elasticIndexManager.DeleteDocumentsAsync(indexSettings.IndexName, [contentItem.ContentItemId]); diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Models/ElasticConnectionOptions.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Models/ElasticConnectionOptions.cs index 7f6b25f601c..aadd832b300 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Models/ElasticConnectionOptions.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Models/ElasticConnectionOptions.cs @@ -51,16 +51,12 @@ public class ElasticConnectionOptions private IConnectionSettingsValues _conntectionSettings; - public void SetFileConfigurationExists(bool fileConfigurationExists) - => _fileConfigurationExists = fileConfigurationExists; + public void SetFileConfigurationExists(bool fileConfigurationExists) => _fileConfigurationExists = fileConfigurationExists; - public bool FileConfigurationExists() - => _fileConfigurationExists; + public bool FileConfigurationExists() => _fileConfigurationExists; - public void SetConnectionSettings(IConnectionSettingsValues settings) - => _conntectionSettings = settings; + public void SetConnectionSettings(IConnectionSettingsValues settings) => _conntectionSettings = settings; - public IConnectionSettingsValues GetConnectionSettings() - => _conntectionSettings; + public IConnectionSettingsValues GetConnectionSettings() => _conntectionSettings; } } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Models/ElasticQuery.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Models/ElasticQuery.cs index cc8f900fb0f..33623bdeaa6 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Models/ElasticQuery.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Models/ElasticQuery.cs @@ -5,7 +5,8 @@ namespace OrchardCore.Search.Elasticsearch.Core.Models { public class ElasticQuery : Query { - public ElasticQuery() : base("Elasticsearch") { } + public ElasticQuery() + : base("Elasticsearch") { } public string Index { get; set; } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Providers/ElasticContentPickerResultProvider.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Providers/ElasticContentPickerResultProvider.cs index 0369070a359..8a06099a479 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Providers/ElasticContentPickerResultProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Providers/ElasticContentPickerResultProvider.cs @@ -16,10 +16,7 @@ public class ElasticContentPickerResultProvider : IContentPickerResultProvider private readonly string _indexPrefix; private readonly ElasticConnectionOptions _elasticConnectionOptions; - public ElasticContentPickerResultProvider( - ShellSettings shellSettings, - IOptions elasticConnectionOptions, - ElasticIndexManager elasticIndexManager) + public ElasticContentPickerResultProvider(ShellSettings shellSettings, IOptions elasticConnectionOptions, ElasticIndexManager elasticIndexManager) { _indexPrefix = shellSettings.Name.ToLowerInvariant() + "_"; _elasticConnectionOptions = elasticConnectionOptions.Value; @@ -51,68 +48,56 @@ public async Task> Search(ContentPickerSearchCo var results = new List(); - await _elasticIndexManager.SearchAsync(indexName, async elasticClient => - { - ISearchResponse> searchResponse = null; - var elasticTopDocs = new ElasticTopDocs(); - - if (string.IsNullOrWhiteSpace(searchContext.Query)) - { - searchResponse = await elasticClient.SearchAsync>(s => s - .Index(_indexPrefix + indexName) - .Query(q => q - .Bool(b => b - .Filter(f => f - .Terms(t => t - .Field("Content.ContentItem.ContentType") - .Terms(searchContext.ContentTypes.ToArray()) - ) - ) - ) - ) - ); - } - else + await _elasticIndexManager.SearchAsync( + indexName, + async elasticClient => { - searchResponse = await elasticClient.SearchAsync>(s => s - .Index(_indexPrefix + indexName) - .Query(q => q - .Bool(b => b - .Filter(f => f - .Terms(t => t - .Field("Content.ContentItem.ContentType") - .Terms(searchContext.ContentTypes.ToArray()) - ) - ) - .Should(s => s - .Wildcard(w => w - .Field("Content.ContentItem.DisplayText.Normalized") - .Wildcard(searchContext.Query.ToLowerInvariant() + "*") + ISearchResponse> searchResponse = null; + var elasticTopDocs = new ElasticTopDocs(); + + if (string.IsNullOrWhiteSpace(searchContext.Query)) + { + searchResponse = await elasticClient.SearchAsync>(s => + s.Index(_indexPrefix + indexName) + .Query(q => q.Bool(b => b.Filter(f => f.Terms(t => t.Field("Content.ContentItem.ContentType").Terms(searchContext.ContentTypes.ToArray()))))) + ); + } + else + { + searchResponse = await elasticClient.SearchAsync>(s => + s.Index(_indexPrefix + indexName) + .Query(q => + q.Bool(b => + b.Filter(f => f.Terms(t => t.Field("Content.ContentItem.ContentType").Terms(searchContext.ContentTypes.ToArray()))) + .Should(s => + s.Wildcard(w => w.Field("Content.ContentItem.DisplayText.Normalized").Wildcard(searchContext.Query.ToLowerInvariant() + "*")) + ) ) ) - ) - ) - ); - } + ); + } - if (searchResponse.IsValid) - { - elasticTopDocs.TopDocs = searchResponse.Documents.ToList(); - } + if (searchResponse.IsValid) + { + elasticTopDocs.TopDocs = searchResponse.Documents.ToList(); + } - if (elasticTopDocs.TopDocs != null) - { - foreach (var doc in elasticTopDocs.TopDocs) + if (elasticTopDocs.TopDocs != null) { - results.Add(new ContentPickerResult + foreach (var doc in elasticTopDocs.TopDocs) { - ContentItemId = doc["ContentItemId"].ToString(), - DisplayText = doc["Content.ContentItem.DisplayText.keyword"].ToString(), - HasPublished = doc["Content.ContentItem.Published"].ToString().ToLowerInvariant().Equals("true") - }); + results.Add( + new ContentPickerResult + { + ContentItemId = doc["ContentItemId"].ToString(), + DisplayText = doc["Content.ContentItem.DisplayText.keyword"].ToString(), + HasPublished = doc["Content.ContentItem.Published"].ToString().ToLowerInvariant().Equals("true") + } + ); + } } } - }); + ); return results.OrderBy(x => x.DisplayText); } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexRebuildStep.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexRebuildStep.cs index 2dc3571eee9..17ae55eb140 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexRebuildStep.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexRebuildStep.cs @@ -27,35 +27,38 @@ public async Task ExecuteAsync(RecipeExecutionContext context) if (model != null && (model.IncludeAll || model.Indices.Length > 0)) { - await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync("elastic-index-rebuild", async scope => - { - var elasticIndexingService = scope.ServiceProvider.GetService(); - var elasticIndexSettingsService = scope.ServiceProvider.GetService(); - var elasticIndexManager = scope.ServiceProvider.GetRequiredService(); - - var indexNames = model.IncludeAll ? (await elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray() : model.Indices; - - foreach (var indexName in indexNames) + await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync( + "elastic-index-rebuild", + async scope => { - var elasticIndexSettings = await elasticIndexSettingsService.GetSettingsAsync(indexName); + var elasticIndexingService = scope.ServiceProvider.GetService(); + var elasticIndexSettingsService = scope.ServiceProvider.GetService(); + var elasticIndexManager = scope.ServiceProvider.GetRequiredService(); - if (elasticIndexSettings == null) - { - continue; - } + var indexNames = model.IncludeAll ? (await elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray() : model.Indices; - if (!await elasticIndexManager.ExistsAsync(indexName)) - { - await elasticIndexingService.CreateIndexAsync(elasticIndexSettings); - } - else + foreach (var indexName in indexNames) { - await elasticIndexingService.RebuildIndexAsync(elasticIndexSettings); + var elasticIndexSettings = await elasticIndexSettingsService.GetSettingsAsync(indexName); + + if (elasticIndexSettings == null) + { + continue; + } + + if (!await elasticIndexManager.ExistsAsync(indexName)) + { + await elasticIndexingService.CreateIndexAsync(elasticIndexSettings); + } + else + { + await elasticIndexingService.RebuildIndexAsync(elasticIndexSettings); + } } - } - await elasticIndexingService.ProcessContentItemsAsync(indexNames); - }); + await elasticIndexingService.ProcessContentItemsAsync(indexNames); + } + ); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexResetStep.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexResetStep.cs index 0501bdce407..eadbaf14664 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexResetStep.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexResetStep.cs @@ -27,35 +27,38 @@ public async Task ExecuteAsync(RecipeExecutionContext context) if (model != null && (model.IncludeAll || model.Indices.Length > 0)) { - await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync("elastic-index-reset", async scope => - { - var elasticIndexingService = scope.ServiceProvider.GetService(); - var elasticIndexSettingsService = scope.ServiceProvider.GetService(); - var elasticIndexManager = scope.ServiceProvider.GetRequiredService(); - - var indexNames = model.IncludeAll ? (await elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray() : model.Indices; - - foreach (var indexName in indexNames) + await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync( + "elastic-index-reset", + async scope => { - var elasticIndexSettings = await elasticIndexSettingsService.GetSettingsAsync(indexName); + var elasticIndexingService = scope.ServiceProvider.GetService(); + var elasticIndexSettingsService = scope.ServiceProvider.GetService(); + var elasticIndexManager = scope.ServiceProvider.GetRequiredService(); - if (elasticIndexSettings == null) - { - continue; - } + var indexNames = model.IncludeAll ? (await elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray() : model.Indices; - if (!await elasticIndexManager.ExistsAsync(indexName)) - { - await elasticIndexingService.CreateIndexAsync(elasticIndexSettings); - } - else + foreach (var indexName in indexNames) { - await elasticIndexingService.ResetIndexAsync(elasticIndexSettings.IndexName); + var elasticIndexSettings = await elasticIndexSettingsService.GetSettingsAsync(indexName); + + if (elasticIndexSettings == null) + { + continue; + } + + if (!await elasticIndexManager.ExistsAsync(indexName)) + { + await elasticIndexingService.CreateIndexAsync(elasticIndexSettings); + } + else + { + await elasticIndexingService.ResetIndexAsync(elasticIndexSettings.IndexName); + } } - } - await elasticIndexingService.ProcessContentItemsAsync(indexNames); - }); + await elasticIndexingService.ProcessContentItemsAsync(indexNames); + } + ); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexStep.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexStep.cs index fecfc4c96ce..190b8b02391 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexStep.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Recipes/ElasticIndexStep.cs @@ -18,10 +18,7 @@ public class ElasticIndexStep : IRecipeStepHandler private readonly ElasticIndexingService _elasticIndexingService; private readonly ElasticIndexManager _elasticIndexManager; - public ElasticIndexStep( - ElasticIndexingService elasticIndexingService, - ElasticIndexManager elasticIndexManager - ) + public ElasticIndexStep(ElasticIndexingService elasticIndexingService, ElasticIndexManager elasticIndexManager) { _elasticIndexManager = elasticIndexManager; _elasticIndexingService = elasticIndexingService; diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticAnalyzer.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticAnalyzer.cs index 0b20c621f64..e94084c9239 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticAnalyzer.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticAnalyzer.cs @@ -13,9 +13,8 @@ public ElasticAnalyzer(string name, Func factory) Name = name; } - public ElasticAnalyzer(string name, IAnalyzer instance) : this(name, () => instance) - { - } + public ElasticAnalyzer(string name, IAnalyzer instance) + : this(name, () => instance) { } public string Name { get; } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticConnectionOptionsConfigurations.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticConnectionOptionsConfigurations.cs index 0f1d0ebf884..753f4f8d1c8 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticConnectionOptionsConfigurations.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticConnectionOptionsConfigurations.cs @@ -17,9 +17,7 @@ public class ElasticConnectionOptionsConfigurations : IConfigureOptions logger) + public ElasticConnectionOptionsConfigurations(IShellConfiguration shellConfiguration, ILogger logger) { _shellConfiguration = shellConfiguration; _logger = logger; @@ -27,8 +25,7 @@ public ElasticConnectionOptionsConfigurations( public void Configure(ElasticConnectionOptions options) { - var fileOptions = _shellConfiguration.GetSection(ConfigSectionName).Get() - ?? new ElasticConnectionOptions(); + var fileOptions = _shellConfiguration.GetSection(ConfigSectionName).Get() ?? new ElasticConnectionOptions(); options.Url = fileOptions.Url; options.Ports = fileOptions.Ports; @@ -77,7 +74,11 @@ private static ConnectionSettings GetConnectionSettings(ElasticConnectionOptions var settings = new ConnectionSettings(pool); - if (elasticConfiguration.ConnectionType != "CloudConnectionPool" && !string.IsNullOrWhiteSpace(elasticConfiguration.Username) && !string.IsNullOrWhiteSpace(elasticConfiguration.Password)) + if ( + elasticConfiguration.ConnectionType != "CloudConnectionPool" + && !string.IsNullOrWhiteSpace(elasticConfiguration.Username) + && !string.IsNullOrWhiteSpace(elasticConfiguration.Password) + ) { settings.BasicAuthentication(elasticConfiguration.Username, elasticConfiguration.Password); } @@ -106,7 +107,11 @@ private static IConnectionPool GetConnectionPool(ElasticConnectionOptions elasti break; case "CloudConnectionPool": - if (!string.IsNullOrWhiteSpace(elasticConfiguration.Username) && !string.IsNullOrWhiteSpace(elasticConfiguration.Password) && !string.IsNullOrWhiteSpace(elasticConfiguration.CloudId)) + if ( + !string.IsNullOrWhiteSpace(elasticConfiguration.Username) + && !string.IsNullOrWhiteSpace(elasticConfiguration.Password) + && !string.IsNullOrWhiteSpace(elasticConfiguration.CloudId) + ) { var credentials = new BasicAuthenticationCredentials(elasticConfiguration.Username, elasticConfiguration.Password); pool = new CloudConnectionPool(elasticConfiguration.CloudId, credentials); diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexInitializerService.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexInitializerService.cs index 6428cd27c48..4c7049007b8 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexInitializerService.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexInitializerService.cs @@ -29,7 +29,8 @@ public ElasticIndexInitializerService( ElasticIndexManager elasticIndexManager, ElasticIndexSettingsService elasticIndexSettingsService, IStringLocalizer localizer, - ILogger logger) + ILogger logger + ) { _shellSettings = shellSettings; _elasticIndexManager = elasticIndexManager; @@ -45,29 +46,32 @@ public override async Task ActivatedAsync() return; } - await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync("elastic-initialize", async scope => - { - var elasticIndexSettingsService = scope.ServiceProvider.GetRequiredService(); - var elasticIndexingService = scope.ServiceProvider.GetRequiredService(); - var indexManager = scope.ServiceProvider.GetRequiredService(); + await HttpBackgroundJob.ExecuteAfterEndOfRequestAsync( + "elastic-initialize", + async scope => + { + var elasticIndexSettingsService = scope.ServiceProvider.GetRequiredService(); + var elasticIndexingService = scope.ServiceProvider.GetRequiredService(); + var indexManager = scope.ServiceProvider.GetRequiredService(); - var elasticIndexSettings = await elasticIndexSettingsService.GetSettingsAsync(); - var createdIndexes = new List(); + var elasticIndexSettings = await elasticIndexSettingsService.GetSettingsAsync(); + var createdIndexes = new List(); - foreach (var settings in elasticIndexSettings) - { - if (!await indexManager.ExistsAsync(settings.IndexName)) + foreach (var settings in elasticIndexSettings) { - await elasticIndexingService.CreateIndexAsync(settings); - createdIndexes.Add(settings.IndexName); + if (!await indexManager.ExistsAsync(settings.IndexName)) + { + await elasticIndexingService.CreateIndexAsync(settings); + createdIndexes.Add(settings.IndexName); + } } - } - if (createdIndexes.Count > 0) - { - await elasticIndexingService.ProcessContentItemsAsync(createdIndexes.ToArray()); + if (createdIndexes.Count > 0) + { + await elasticIndexingService.ProcessContentItemsAsync(createdIndexes.ToArray()); + } } - }); + ); } public override async Task RemovingAsync(ShellRemovingContext context) diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexManager.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexManager.cs index e81b187efa4..a2155a5c850 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexManager.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexManager.cs @@ -1,4 +1,3 @@ - using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -34,34 +33,20 @@ public sealed class ElasticIndexManager private readonly ElasticsearchOptions _elasticsearchOptions; private readonly ConcurrentDictionary _timestamps = new(StringComparer.OrdinalIgnoreCase); private readonly string _lastTaskId = "last_task_id"; - private readonly Dictionary> _analyzerGetter = new(StringComparer.OrdinalIgnoreCase) - { - { "standard", () => new StandardAnalyzer() }, - { "simple", () => new SimpleAnalyzer() }, - { "keyword", () => new KeywordAnalyzer() }, - { "whitespace", () => new WhitespaceAnalyzer() }, - { "pattern", () => new PatternAnalyzer() }, - { "language", () => new LanguageAnalyzer() }, - { "fingerprint", () => new FingerprintAnalyzer() }, - { "custom", () => new CustomAnalyzer() }, - { "stop", () => new StopAnalyzer() }, - }; - private static readonly List _charsToRemove = - [ - '\\', - '/', - '*', - '\"', - '|', - '<', - '>', - '`', - '\'', - ' ', - '#', - ':', - '.', - ]; + private readonly Dictionary> _analyzerGetter = + new(StringComparer.OrdinalIgnoreCase) + { + { "standard", () => new StandardAnalyzer() }, + { "simple", () => new SimpleAnalyzer() }, + { "keyword", () => new KeywordAnalyzer() }, + { "whitespace", () => new WhitespaceAnalyzer() }, + { "pattern", () => new PatternAnalyzer() }, + { "language", () => new LanguageAnalyzer() }, + { "fingerprint", () => new FingerprintAnalyzer() }, + { "custom", () => new CustomAnalyzer() }, + { "stop", () => new StopAnalyzer() }, + }; + private static readonly List _charsToRemove = ['\\', '/', '*', '\"', '|', '<', '>', '`', '\'', ' ', '#', ':', '.',]; private string _indexPrefix; @@ -71,7 +56,7 @@ public ElasticIndexManager( IOptions elasticsearchOptions, IClock clock, ILogger logger - ) + ) { _elasticClient = elasticClient; _shellSettings = shellSettings; @@ -115,88 +100,52 @@ public async Task CreateIndexAsync(ElasticIndexSettings elasticIndexSettin } // Custom metadata to store the last indexing task id. - var IndexingState = new FluentDictionary() { - { _lastTaskId, 0 } - }; + var IndexingState = new FluentDictionary() { { _lastTaskId, 0 } }; var fullIndexName = GetFullIndexName(elasticIndexSettings.IndexName); var createIndexDescriptor = new CreateIndexDescriptor(fullIndexName) .Settings(s => indexSettingsDescriptor) - .Map(m => m - .SourceField(s => s - .Enabled(elasticIndexSettings.StoreSourceData) - .Excludes(new string[] { IndexingConstants.DisplayTextAnalyzedKey })) - .Meta(me => IndexingState)); + .Map(m => + m.SourceField(s => s.Enabled(elasticIndexSettings.StoreSourceData).Excludes(new string[] { IndexingConstants.DisplayTextAnalyzedKey })) + .Meta(me => IndexingState) + ); var response = await _elasticClient.Indices.CreateAsync(createIndexDescriptor); // We force some mappings for common fields. - await _elasticClient.MapAsync(p => p - .Index(fullIndexName) - .Properties(p => p - .Keyword(obj => obj - .Name(IndexingConstants.ContentItemIdKey) - ) - .Keyword(obj => obj - .Name(IndexingConstants.ContentItemVersionIdKey) + await _elasticClient.MapAsync(p => + p.Index(fullIndexName) + .Properties(p => + p.Keyword(obj => obj.Name(IndexingConstants.ContentItemIdKey)) + .Keyword(obj => obj.Name(IndexingConstants.ContentItemVersionIdKey)) + .Keyword(obj => obj.Name(IndexingConstants.OwnerKey)) + .Text(obj => obj.Name(IndexingConstants.FullTextKey)) ) - .Keyword(obj => obj - .Name(IndexingConstants.OwnerKey) - ) - .Text(obj => obj - .Name(IndexingConstants.FullTextKey) - ) - )); + ); // ContainedPart mappings. - await _elasticClient.MapAsync(p => p - .Index(fullIndexName) - .Properties(p => p - .Object(obj => obj - .Name(IndexingConstants.ContainedPartKey) - .AutoMap() - ) - )); + await _elasticClient.MapAsync(p => + p.Index(fullIndexName).Properties(p => p.Object(obj => obj.Name(IndexingConstants.ContainedPartKey).AutoMap())) + ); // We map DisplayText here because we have 3 different fields with it. // We can't have Content.ContentItem.DisplayText as it is mapped as an Object in Elasticsearch. - await _elasticClient.MapAsync(p => p - .Index(fullIndexName) - .Properties(p => p - .Object(obj => obj - .Name(IndexingConstants.DisplayTextKey) - .AutoMap() - ) - )); + await _elasticClient.MapAsync(p => + p.Index(fullIndexName).Properties(p => p.Object(obj => obj.Name(IndexingConstants.DisplayTextKey).AutoMap())) + ); // We map ContentType as a keyword because else the automatic mapping will break the queries. // We need to access it with Content.ContentItem.ContentType as a keyword // for the ContentPickerResultProvider(s). - await _elasticClient.MapAsync(p => p - .Index(fullIndexName) - .Properties(p => p - .Keyword(obj => obj - .Name(IndexingConstants.ContentTypeKey) - ) - )); + await _elasticClient.MapAsync(p => p.Index(fullIndexName).Properties(p => p.Keyword(obj => obj.Name(IndexingConstants.ContentTypeKey)))); // DynamicTemplates mapping for Taxonomy indexing mostly. - await _elasticClient.MapAsync(p => p - .Index(fullIndexName) - .DynamicTemplates(d => d - .DynamicTemplate("*.Inherited", dyn => dyn - .MatchMappingType("string") - .PathMatch("*" + IndexingConstants.InheritedKey) - .Mapping(m => m - .Keyword(k => k)) + await _elasticClient.MapAsync(p => + p.Index(fullIndexName) + .DynamicTemplates(d => + d.DynamicTemplate("*.Inherited", dyn => dyn.MatchMappingType("string").PathMatch("*" + IndexingConstants.InheritedKey).Mapping(m => m.Keyword(k => k))) + .DynamicTemplate("*.Ids", dyn => dyn.MatchMappingType("string").PathMatch("*" + IndexingConstants.IdsKey).Mapping(m => m.Keyword(k => k))) ) - .DynamicTemplate("*.Ids", dyn => dyn - .MatchMappingType("string") - .PathMatch("*" + IndexingConstants.IdsKey) - .Mapping(m => m - .Keyword(k => k)) - ) - ) - ); + ); return response.Acknowledged; } @@ -205,8 +154,7 @@ private IAnalyzer CreateAnalyzer(JsonObject analyzerProperties) { IAnalyzer analyzer = null; - if (analyzerProperties.TryGetPropertyValue("type", out var typeObject) - && _analyzerGetter.TryGetValue(typeObject.ToString(), out var getter)) + if (analyzerProperties.TryGetPropertyValue("type", out var typeObject) && _analyzerGetter.TryGetValue(typeObject.ToString(), out var getter)) { analyzer = getter.Invoke(); @@ -288,14 +236,9 @@ public async Task GetIndexMappings(string indexName) /// public async Task SetLastTaskId(string indexName, long lastTaskId) { - var IndexingState = new FluentDictionary() { - { _lastTaskId, lastTaskId } - }; + var IndexingState = new FluentDictionary() { { _lastTaskId, lastTaskId } }; - var putMappingRequest = new PutMappingRequest(GetFullIndexName(indexName)) - { - Meta = IndexingState - }; + var putMappingRequest = new PutMappingRequest(GetFullIndexName(indexName)) { Meta = IndexingState }; await _elasticClient.Indices.PutMappingAsync(putMappingRequest); } @@ -325,10 +268,7 @@ public async Task DeleteDocumentsAsync(string indexName, IEnumerable>(d => d - .Index(GetFullIndexName(indexName)) - .Id(id) - ); + descriptor.Delete>(d => d.Index(GetFullIndexName(indexName)).Id(id)); var response = await _elasticClient.BulkAsync(descriptor); @@ -349,10 +289,7 @@ public async Task DeleteDocumentsAsync(string indexName, IEnumerable public async Task DeleteAllDocumentsAsync(string indexName) { - var response = await _elasticClient.DeleteByQueryAsync>(del => del - .Index(GetFullIndexName(indexName)) - .Query(q => q.MatchAll()) - ); + var response = await _elasticClient.DeleteByQueryAsync>(del => del.Index(GetFullIndexName(indexName)).Query(q => q.MatchAll())); return response.IsValid; } @@ -417,10 +354,8 @@ public async Task StoreDocumentsAsync(string indexName, IEnumerable>(op => op - .Id(document.GetValueOrDefault("ContentItemId").ToString()) - .Document(document) - .Index(GetFullIndexName(indexName)) + descriptor.Index>(op => + op.Id(document.GetValueOrDefault("ContentItemId").ToString()).Document(document).Index(GetFullIndexName(indexName)) ); } @@ -482,10 +417,7 @@ public async Task SearchAsync(string indexName, QueryContainer q var hit = hits.Current; - var topDoc = new Dictionary - { - { "ContentItemId", hit.Id } - }; + var topDoc = new Dictionary { { "ContentItemId", hit.Id } }; topDocs.Add(topDoc); } @@ -601,11 +533,7 @@ private static void AddValue(Dictionary entries, string key, obj } // Convert the existing value to a list of values. - var values = new List() - { - entries[key], - value, - }; + var values = new List() { entries[key], value, }; entries[key] = values; } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexSettingsService.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexSettingsService.cs index 66d8e30309f..b3216e476e6 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexSettingsService.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexSettingsService.cs @@ -100,8 +100,7 @@ public async Task DeleteIndexAsync(string indexName) await DocumentManager.UpdateAsync(document); } - private static IDocumentManager DocumentManager => - ShellScope.Services.GetRequiredService>(); + private static IDocumentManager DocumentManager => ShellScope.Services.GetRequiredService>(); // Returns the name of the analyzer configured for the given index name. private static string GetAnalyzerName(ElasticIndexSettingsDocument document, string indexName) diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexingService.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexingService.cs index a463bd11635..9cc63d95971 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexingService.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexingService.cs @@ -52,7 +52,8 @@ public ElasticIndexingService( IEnumerable contentItemIndexHandlers, IStore store, IContentDefinitionManager contentDefinitionManager, - ILogger logger) + ILogger logger + ) { _shellHost = shellHost; _shellSettings = shellSettings; @@ -79,8 +80,7 @@ public async Task ProcessContentItemsAsync(params string[] indexNames) if (indexNames != null && indexNames.Length > 0) { - indexSettingsList = indexSettingsList - .Where(x => indexNames.Contains(x.IndexName, StringComparer.OrdinalIgnoreCase)); + indexSettingsList = indexSettingsList.Where(x => indexNames.Contains(x.IndexName, StringComparer.OrdinalIgnoreCase)); } if (!indexSettingsList.Any()) @@ -113,10 +113,7 @@ public async Task ProcessContentItemsAsync(params string[] indexNames) break; } - var updatedContentItemIds = tasks - .Where(x => x.Type == IndexingTaskTypes.Update) - .Select(x => x.ContentItemId) - .ToList(); + var updatedContentItemIds = tasks.Where(x => x.Type == IndexingTaskTypes.Update).Select(x => x.ContentItemId).ToList(); Dictionary allPublished = null; Dictionary allLatest = null; @@ -125,14 +122,19 @@ public async Task ProcessContentItemsAsync(params string[] indexNames) if (indexSettingsList.Any(x => !x.IndexLatest)) { - var publishedContentItems = await readOnlySession.Query(index => index.Published && index.ContentType.IsIn(allContentTypes) && index.ContentItemId.IsIn(updatedContentItemIds)).ListAsync(); - allPublished = publishedContentItems.DistinctBy(x => x.ContentItemId) - .ToDictionary(k => k.ContentItemId); + var publishedContentItems = await readOnlySession + .Query(index => + index.Published && index.ContentType.IsIn(allContentTypes) && index.ContentItemId.IsIn(updatedContentItemIds) + ) + .ListAsync(); + allPublished = publishedContentItems.DistinctBy(x => x.ContentItemId).ToDictionary(k => k.ContentItemId); } if (indexSettingsList.Any(x => x.IndexLatest)) { - var latestContentItems = await readOnlySession.Query(index => index.Latest && index.ContentType.IsIn(allContentTypes) && index.ContentItemId.IsIn(updatedContentItemIds)).ListAsync(); + var latestContentItems = await readOnlySession + .Query(index => index.Latest && index.ContentType.IsIn(allContentTypes) && index.ContentItemId.IsIn(updatedContentItemIds)) + .ListAsync(); allLatest = latestContentItems.DistinctBy(x => x.ContentItemId).ToDictionary(k => k.ContentItemId); } @@ -153,17 +155,28 @@ public async Task ProcessContentItemsAsync(params string[] indexNames) continue; } - BuildIndexContext publishedIndexContext = null, latestIndexContext = null; + BuildIndexContext publishedIndexContext = null, + latestIndexContext = null; if (allPublished != null && allPublished.TryGetValue(task.ContentItemId, out var publishedContentItem)) { - publishedIndexContext = new BuildIndexContext(new DocumentIndex(task.ContentItemId, publishedContentItem.ContentItemVersionId), publishedContentItem, [publishedContentItem.ContentType], new ElasticContentIndexSettings()); + publishedIndexContext = new BuildIndexContext( + new DocumentIndex(task.ContentItemId, publishedContentItem.ContentItemVersionId), + publishedContentItem, + [publishedContentItem.ContentType], + new ElasticContentIndexSettings() + ); await _contentItemIndexHandlers.InvokeAsync(x => x.BuildIndexAsync(publishedIndexContext), _logger); } if (allLatest != null && allLatest.TryGetValue(task.ContentItemId, out var latestContentItem)) { - latestIndexContext = new BuildIndexContext(new DocumentIndex(task.ContentItemId, latestContentItem.ContentItemVersionId), latestContentItem, [latestContentItem.ContentType], new ElasticContentIndexSettings()); + latestIndexContext = new BuildIndexContext( + new DocumentIndex(task.ContentItemId, latestContentItem.ContentItemVersionId), + latestContentItem, + [latestContentItem.ContentType], + new ElasticContentIndexSettings() + ); await _contentItemIndexHandlers.InvokeAsync(x => x.BuildIndexAsync(latestIndexContext), _logger); } @@ -241,8 +254,7 @@ public async Task CreateIndexAsync(ElasticIndexSettings elasticIndexSettings) /// /// Update an existing index. /// - public Task UpdateIndexAsync(ElasticIndexSettings elasticIndexSettings) - => _elasticIndexSettingsService.UpdateIndexAsync(elasticIndexSettings); + public Task UpdateIndexAsync(ElasticIndexSettings elasticIndexSettings) => _elasticIndexSettingsService.UpdateIndexAsync(elasticIndexSettings); /// /// Deletes permanently an index. @@ -303,18 +315,24 @@ public async Task SyncSettings() { foreach (var partDefinition in contentTypeDefinition.Parts) { - await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, partBuilder => - { - if (partDefinition.Settings.TryGetPropertyValue("LuceneContentIndexSettings", out var existingPartSettings)) + await _contentDefinitionManager.AlterPartDefinitionAsync( + partDefinition.Name, + partBuilder => { - var included = existingPartSettings["Included"]; - - if (included is not null && (bool)included) + if (partDefinition.Settings.TryGetPropertyValue("LuceneContentIndexSettings", out var existingPartSettings)) { - partDefinition.Settings.Add(nameof(ElasticContentIndexSettings), JNode.FromObject(existingPartSettings.ToObject())); + var included = existingPartSettings["Included"]; + + if (included is not null && (bool)included) + { + partDefinition.Settings.Add( + nameof(ElasticContentIndexSettings), + JNode.FromObject(existingPartSettings.ToObject()) + ); + } } } - }); + ); } } @@ -322,31 +340,37 @@ await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, pa foreach (var partDefinition in partDefinitions) { - await _contentDefinitionManager.AlterPartDefinitionAsync(partDefinition.Name, partBuilder => - { - if (partDefinition.Settings.TryGetPropertyValue("LuceneContentIndexSettings", out var existingPartSettings)) + await _contentDefinitionManager.AlterPartDefinitionAsync( + partDefinition.Name, + partBuilder => { - var included = existingPartSettings["Included"]; - - if (included != null && (bool)included) + if (partDefinition.Settings.TryGetPropertyValue("LuceneContentIndexSettings", out var existingPartSettings)) { - partDefinition.Settings.Add(nameof(ElasticContentIndexSettings), JNode.FromObject(existingPartSettings.ToObject())); + var included = existingPartSettings["Included"]; + + if (included != null && (bool)included) + { + partDefinition.Settings.Add(nameof(ElasticContentIndexSettings), JNode.FromObject(existingPartSettings.ToObject())); + } } - } - foreach (var fieldDefinition in partDefinition.Fields) - { - if (fieldDefinition.Settings.TryGetPropertyValue("LuceneContentIndexSettings", out var existingFieldSettings)) + foreach (var fieldDefinition in partDefinition.Fields) { - var included = existingFieldSettings["Included"]; - - if (included != null && (bool)included) + if (fieldDefinition.Settings.TryGetPropertyValue("LuceneContentIndexSettings", out var existingFieldSettings)) { - fieldDefinition.Settings.Add(nameof(ElasticContentIndexSettings), JNode.FromObject(existingFieldSettings.ToObject())); + var included = existingFieldSettings["Included"]; + + if (included != null && (bool)included) + { + fieldDefinition.Settings.Add( + nameof(ElasticContentIndexSettings), + JNode.FromObject(existingFieldSettings.ToObject()) + ); + } } } } - }); + ); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQueryService.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQueryService.cs index adfc2bf23bf..8274636778f 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQueryService.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQueryService.cs @@ -15,11 +15,7 @@ public class ElasticQueryService : IElasticQueryService private readonly IElasticClient _elasticClient; private readonly ILogger _logger; - public ElasticQueryService( - IElasticClient elasticClient, - ShellSettings shellSettings, - ILogger logger - ) + public ElasticQueryService(IElasticClient elasticClient, ShellSettings shellSettings, ILogger logger) { _indexPrefix = shellSettings.Name.ToLowerInvariant() + "_"; _elasticClient = elasticClient; diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQuerySource.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQuerySource.cs index 72ef9057373..dfc36f099ac 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQuerySource.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQuerySource.cs @@ -29,7 +29,8 @@ public ElasticQuerySource( ILiquidTemplateManager liquidTemplateManager, ISession session, JavaScriptEncoder javaScriptEncoder, - IOptions templateOptions) + IOptions templateOptions + ) { _queryService = queryService; _liquidTemplateManager = liquidTemplateManager; @@ -50,7 +51,11 @@ public async Task ExecuteQueryAsync(Query query, IDictionary new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions)))); + var tokenizedContent = await _liquidTemplateManager.RenderStringAsync( + elasticQuery.Template, + _javaScriptEncoder, + parameters.Select(x => new KeyValuePair(x.Key, FluidValue.Create(x.Value, _templateOptions))) + ); var docs = await _queryService.SearchAsync(elasticQuery.Index, tokenizedContent); elasticQueryResults.Count = docs.Count; @@ -84,8 +89,7 @@ public async Task ExecuteQueryAsync(Query query, IDictionary - KeyValuePair.Create(x.Key, (JsonNode)JsonValue.Create(x.Value.ToString()))))); + results.Add(new JsonObject(document.Select(x => KeyValuePair.Create(x.Key, (JsonNode)JsonValue.Create(x.Value.ToString()))))); } elasticQueryResults.Items = results; diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/IndexingBackgroundTask.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/IndexingBackgroundTask.cs index 7cdff32aac8..69bbd58c927 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/IndexingBackgroundTask.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/IndexingBackgroundTask.cs @@ -12,12 +12,7 @@ namespace OrchardCore.Search.Elasticsearch.Core.Services; /// /// This services is only registered from OrchardCore.Search.Elasticsearch.Worker feature. /// -[BackgroundTask( - Title = "Elasticsearch Indexes Updater", - Schedule = "* * * * *", - Description = "Updates Elasticsearch indexes.", - LockTimeout = 1000, - LockExpiration = 300000)] +[BackgroundTask(Title = "Elasticsearch Indexes Updater", Schedule = "* * * * *", Description = "Updates Elasticsearch indexes.", LockTimeout = 1000, LockExpiration = 300000)] public class IndexingBackgroundTask : IBackgroundTask { public Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken) diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/LuceneQueryService.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/LuceneQueryService.cs index 64c489ac1b0..0af89587393 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/LuceneQueryService.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/LuceneQueryService.cs @@ -21,8 +21,7 @@ public LuceneQueryService(IEnumerable queryProviders) public Task SearchAsync(LuceneQueryContext context, JsonObject queryObj) { - var queryProp = queryObj["query"].AsObject() - ?? throw new ArgumentException("Query DSL requires a [query] property"); + var queryProp = queryObj["query"].AsObject() ?? throw new ArgumentException("Query DSL requires a [query] property"); var query = CreateQueryFragment(context, queryProp); @@ -84,11 +83,7 @@ public Task SearchAsync(LuceneQueryContext context, JsonObject qu if (size > 0) { - TopDocs topDocs = context.IndexSearcher.Search( - query, - size + from, - sortField == null ? Sort.RELEVANCE : new Sort(sortFields.ToArray()) - ); + TopDocs topDocs = context.IndexSearcher.Search(query, size + from, sortField == null ? Sort.RELEVANCE : new Sort(sortFields.ToArray())); if (from > 0) { diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/BooleanQueryProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/BooleanQueryProvider.cs index c18c74173b1..81dfcf72833 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/BooleanQueryProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/BooleanQueryProvider.cs @@ -53,7 +53,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context break; case "filter": return CreateFilteredQuery(builder, context, boolQuery, property.Value); - default: throw new ArgumentException($"Invalid property '{property.Key}' in boolean query"); + default: + throw new ArgumentException($"Invalid property '{property.Key}' in boolean query"); } if (!isProps) @@ -73,7 +74,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context boolQuery.Add(builder.CreateQueryFragment(context, item.AsObject()), occur); } break; - default: throw new ArgumentException($"Invalid value in boolean query"); + default: + throw new ArgumentException($"Invalid value in boolean query"); } } } @@ -117,7 +119,8 @@ private Query CreateFilteredQuery(ILuceneQueryService builder, LuceneQueryContex } } break; - default: throw new ArgumentException($"Invalid value in boolean query"); + default: + throw new ArgumentException($"Invalid value in boolean query"); } return filteredQuery; diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/FuzzyFilterProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/FuzzyFilterProvider.cs index 066a5dfe668..758d53eeb62 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/FuzzyFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/FuzzyFilterProvider.cs @@ -49,7 +49,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer fuzziness?.Value() ?? LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE, prefixLength?.Value() ?? 0, maxExpansions?.Value() ?? 50, - true); + true + ); if (obj.TryGetPropertyValue("boost", out var boost)) { @@ -57,7 +58,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer } break; - default: throw new ArgumentException("Invalid fuzzy query"); + default: + throw new ArgumentException("Invalid fuzzy query"); } booleanQuery.Add(fuzzyQuery, Occur.MUST); diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/GeoDistanceFilterProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/GeoDistanceFilterProvider.cs index 982b78bc77a..11e2ba226d6 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/GeoDistanceFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/GeoDistanceFilterProvider.cs @@ -202,7 +202,8 @@ private static bool TryGetPointFromJToken(JsonNode geoToken, out IPoint point) point = new Point(geoArrayValue[0].Value(), geoArrayValue[1].Value(), ctx); return true; - default: throw new ArgumentException("Invalid geo point representation"); + default: + throw new ArgumentException("Invalid geo point representation"); } } diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/MatchFilterProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/MatchFilterProvider.cs index 9685f67d198..be6f7c3f7d1 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/MatchFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/MatchFilterProvider.cs @@ -71,7 +71,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer } break; - default: throw new ArgumentException("Invalid query"); + default: + throw new ArgumentException("Invalid query"); } booleanQuery.Add(boolQuery, Occur.MUST); diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/MatchPhraseFilterProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/MatchPhraseFilterProvider.cs index ca4bbb5ede3..96096cdc956 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/MatchPhraseFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/MatchPhraseFilterProvider.cs @@ -48,7 +48,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer } break; - default: throw new ArgumentException("Invalid wildcard query"); + default: + throw new ArgumentException("Invalid wildcard query"); } foreach (var term in LuceneQueryService.Tokenize(first.Key, value.Value(), context.DefaultAnalyzer)) diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/PrefixFilterProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/PrefixFilterProvider.cs index da292af306b..307d3788bc3 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/PrefixFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/PrefixFilterProvider.cs @@ -54,7 +54,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer } break; - default: throw new ArgumentException("Invalid prefix query"); + default: + throw new ArgumentException("Invalid prefix query"); } booleanQuery.Add(prefixQuery, Occur.MUST); diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/RangeFilterProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/RangeFilterProvider.cs index 98bf687e8d5..8ca70cc3d78 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/RangeFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/RangeFilterProvider.cs @@ -35,7 +35,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer var nodeKind = JsonValueKind.Null; float? boost = null; - bool includeLower = false, includeUpper = false; + bool includeLower = false, + includeUpper = false; foreach (var element in range.Value.AsObject()) { @@ -73,13 +74,11 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer switch (nodeKind) { case JsonValueKind.Number: - if (gt.AsValue().TryGetValue(out var minInt) && - lt.AsValue().TryGetValue(out var maxInt)) + if (gt.AsValue().TryGetValue(out var minInt) && lt.AsValue().TryGetValue(out var maxInt)) { rangeQuery = NumericRangeQuery.NewInt64Range(field, minInt, maxInt, includeLower, includeUpper); } - else if (gt.AsValue().TryGetValue(out var minFloat) && - lt.AsValue().TryGetValue(out var maxFloat)) + else if (gt.AsValue().TryGetValue(out var minFloat) && lt.AsValue().TryGetValue(out var maxFloat)) { rangeQuery = NumericRangeQuery.NewDoubleRange(field, minFloat, maxFloat, includeLower, includeUpper); } @@ -96,7 +95,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer rangeQuery = TermRangeQuery.NewStringRange(field, minString, maxString, includeLower, includeUpper); break; - default: throw new ArgumentException($"Unsupported range value type: {type}"); + default: + throw new ArgumentException($"Unsupported range value type: {type}"); } if (boost != null) @@ -105,7 +105,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer } break; - default: throw new ArgumentException("Invalid range query"); + default: + throw new ArgumentException("Invalid range query"); } booleanQuery.Add(rangeQuery, Occur.MUST); diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/TermFilterProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/TermFilterProvider.cs index b342548ca1a..41cb56f8161 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/TermFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/TermFilterProvider.cs @@ -42,7 +42,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer termQuery.Boost = boost.Value(); } break; - default: throw new ArgumentException("Invalid term query"); + default: + throw new ArgumentException("Invalid term query"); } booleanQuery.Add(termQuery, Occur.MUST); diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/TermsFilterProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/TermsFilterProvider.cs index da05e2e40c8..7b653b5d086 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/TermsFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/TermsFilterProvider.cs @@ -46,7 +46,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer case JsonValueKind.Object: throw new ArgumentException("The terms lookup query is not supported"); - default: throw new ArgumentException("Invalid terms query"); + default: + throw new ArgumentException("Invalid terms query"); } booleanQuery.Add(boolQuery, Occur.MUST); diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/WildcardFilterProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/WildcardFilterProvider.cs index 1c8162ea2f4..763708d0c3d 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/WildcardFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/Filters/WildcardFilterProvider.cs @@ -48,7 +48,8 @@ public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQuer } break; - default: throw new ArgumentException("Invalid wildcard query"); + default: + throw new ArgumentException("Invalid wildcard query"); } booleanQuery.Add(wildcardQuery, Occur.MUST); diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/FuzzyQueryProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/FuzzyQueryProvider.cs index 1d134e0f6f2..5c68be54cfb 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/FuzzyQueryProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/FuzzyQueryProvider.cs @@ -41,7 +41,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context fuzziness?.Value() ?? LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE, prefixLength?.Value() ?? 0, maxExpansions?.Value() ?? 50, - true); + true + ); if (obj.TryGetPropertyValue("boost", out var boost)) { @@ -49,7 +50,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context } return fuzzyQuery; - default: throw new ArgumentException("Invalid fuzzy query"); + default: + throw new ArgumentException("Invalid fuzzy query"); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/MatchPhraseQueryProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/MatchPhraseQueryProvider.cs index 01dad531e83..902ed83cb37 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/MatchPhraseQueryProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/MatchPhraseQueryProvider.cs @@ -43,7 +43,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context } break; - default: throw new ArgumentException("Invalid wildcard query"); + default: + throw new ArgumentException("Invalid wildcard query"); } foreach (var term in LuceneQueryService.Tokenize(first.Key, value.Value(), context.DefaultAnalyzer)) diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/MatchQueryProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/MatchQueryProvider.cs index 286a570f03c..0a3a2e01e04 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/MatchQueryProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/MatchQueryProvider.cs @@ -64,7 +64,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context } return boolQuery; - default: throw new ArgumentException("Invalid query"); + default: + throw new ArgumentException("Invalid query"); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/PrefixQueryProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/PrefixQueryProvider.cs index 9c65e3b7602..2d1a680a4ba 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/PrefixQueryProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/PrefixQueryProvider.cs @@ -49,7 +49,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context return prefixQuery; - default: throw new ArgumentException("Invalid prefix query"); + default: + throw new ArgumentException("Invalid prefix query"); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/RangeQueryProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/RangeQueryProvider.cs index 684e1dbe91b..eba5f83f6aa 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/RangeQueryProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/RangeQueryProvider.cs @@ -28,7 +28,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context var nodeKind = JsonValueKind.Undefined; float? boost = null; - bool includeLower = false, includeUpper = false; + bool includeLower = false, + includeUpper = false; foreach (var element in range.Value.AsObject()) { @@ -66,13 +67,11 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context switch (nodeKind) { case JsonValueKind.Number: - if (gt.AsValue().TryGetValue(out var minInt) && - lt.AsValue().TryGetValue(out var maxInt)) + if (gt.AsValue().TryGetValue(out var minInt) && lt.AsValue().TryGetValue(out var maxInt)) { rangeQuery = NumericRangeQuery.NewInt64Range(field, minInt, maxInt, includeLower, includeUpper); } - else if (gt.AsValue().TryGetValue(out var minFloat) && - lt.AsValue().TryGetValue(out var maxFloat)) + else if (gt.AsValue().TryGetValue(out var minFloat) && lt.AsValue().TryGetValue(out var maxFloat)) { rangeQuery = NumericRangeQuery.NewDoubleRange(field, minFloat, maxFloat, includeLower, includeUpper); } @@ -88,7 +87,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context var maxString = lt?.Value(); rangeQuery = TermRangeQuery.NewStringRange(field, minString, maxString, includeLower, includeUpper); break; - default: throw new ArgumentException($"Unsupported range value type: {type}"); + default: + throw new ArgumentException($"Unsupported range value type: {type}"); } if (boost != null) @@ -97,7 +97,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context } return rangeQuery; - default: throw new ArgumentException("Invalid range query"); + default: + throw new ArgumentException("Invalid range query"); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/RegexpQueryProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/RegexpQueryProvider.cs index 133a4d44a3b..3341b73e6b8 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/RegexpQueryProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/RegexpQueryProvider.cs @@ -41,7 +41,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context } return regexpQuery; - default: throw new ArgumentException("Invalid regexp query"); + default: + throw new ArgumentException("Invalid regexp query"); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/TermQueryProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/TermQueryProvider.cs index 824c99bdb4e..088c99fed8b 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/TermQueryProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/TermQueryProvider.cs @@ -36,7 +36,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context } return termQuery; - default: throw new ArgumentException("Invalid term query"); + default: + throw new ArgumentException("Invalid term query"); } } } diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/TermsQueryProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/TermsQueryProvider.cs index aa074cfd578..c66f7e4f9b1 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/TermsQueryProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/TermsQueryProvider.cs @@ -39,7 +39,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context case JsonValueKind.Object: throw new ArgumentException("The terms lookup query is not supported"); - default: throw new ArgumentException("Invalid terms query"); + default: + throw new ArgumentException("Invalid terms query"); } return boolQuery; diff --git a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/WildcardQueryProvider.cs b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/WildcardQueryProvider.cs index 5e1b8a6aba4..82105d0a85c 100644 --- a/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/WildcardQueryProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Lucene.Core/QueryProviders/WildcardQueryProvider.cs @@ -40,7 +40,8 @@ public Query CreateQuery(ILuceneQueryService builder, LuceneQueryContext context return wildCardQuery; - default: throw new ArgumentException("Invalid wildcard query"); + default: + throw new ArgumentException("Invalid wildcard query"); } } } diff --git a/src/OrchardCore/OrchardCore.Settings.Core/Deployment/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Settings.Core/Deployment/ServiceCollectionExtensions.cs index dcebba84a6e..461c0f50be0 100644 --- a/src/OrchardCore/OrchardCore.Settings.Core/Deployment/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Settings.Core/Deployment/ServiceCollectionExtensions.cs @@ -12,7 +12,13 @@ public static class ServiceCollectionExtensions /// /// Registers a step. /// - public static void AddSiteSettingsPropertyDeploymentStep(this IServiceCollection services, Func title, Func description) where TModel : class, new() where TLocalizer : class + public static void AddSiteSettingsPropertyDeploymentStep( + this IServiceCollection services, + Func title, + Func description + ) + where TModel : class, new() + where TLocalizer : class { services.AddTransient>(); services.AddScoped>(sp => diff --git a/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentSource.cs b/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentSource.cs index f98b0e12209..2c406967dfd 100644 --- a/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentSource.cs +++ b/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentSource.cs @@ -5,7 +5,8 @@ namespace OrchardCore.Settings.Deployment { - public class SiteSettingsPropertyDeploymentSource : IDeploymentSource where TModel : class, new() + public class SiteSettingsPropertyDeploymentSource : IDeploymentSource + where TModel : class, new() { private readonly ISiteService _siteService; @@ -34,11 +35,7 @@ public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlan } else { - result.Steps.Add(new JsonObject - { - ["name"] = "Settings", - [settingJPropertyName] = settingJPropertyValue, - }); + result.Steps.Add(new JsonObject { ["name"] = "Settings", [settingJPropertyName] = settingJPropertyValue, }); } } } diff --git a/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentStep.cs b/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentStep.cs index 6059c8162ab..bd74a4e5341 100644 --- a/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentStep.cs +++ b/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentStep.cs @@ -5,7 +5,8 @@ namespace OrchardCore.Settings.Deployment /// /// Adds a site setting from the properties dictionary to a . /// - public class SiteSettingsPropertyDeploymentStep : DeploymentStep where TModel : class, new() + public class SiteSettingsPropertyDeploymentStep : DeploymentStep + where TModel : class, new() { public SiteSettingsPropertyDeploymentStep() { diff --git a/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentStepDriver.cs b/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentStepDriver.cs index a734cb7a20d..24fbfcf37c5 100644 --- a/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentStepDriver.cs +++ b/src/OrchardCore/OrchardCore.Settings.Core/Deployment/SiteSettingsPropertyDeploymentStepDriver.cs @@ -5,7 +5,8 @@ namespace OrchardCore.Settings.Deployment { - public class SiteSettingsPropertyDeploymentStepDriver : DisplayDriver> where TModel : class, new() + public class SiteSettingsPropertyDeploymentStepDriver : DisplayDriver> + where TModel : class, new() { private readonly string _title; private readonly string _description; @@ -19,17 +20,15 @@ public SiteSettingsPropertyDeploymentStepDriver(string title, string description public override IDisplayResult Display(SiteSettingsPropertyDeploymentStep step) { return Combine( - Initialize("SiteSettingsPropertyDeploymentStep_Fields_Summary", m => BuildViewModel(m)) - .Location("Summary", "Content"), - Initialize("SiteSettingsPropertyDeploymentStep_Fields_Thumbnail", m => BuildViewModel(m)) - .Location("Thumbnail", "Content") - ); + Initialize("SiteSettingsPropertyDeploymentStep_Fields_Summary", m => BuildViewModel(m)).Location("Summary", "Content"), + Initialize("SiteSettingsPropertyDeploymentStep_Fields_Thumbnail", m => BuildViewModel(m)) + .Location("Thumbnail", "Content") + ); } public override IDisplayResult Edit(SiteSettingsPropertyDeploymentStep step) { - return Initialize("SiteSettingsPropertyDeploymentStep_Fields_Edit", m => BuildViewModel(m)) - .Location("Content"); + return Initialize("SiteSettingsPropertyDeploymentStep_Fields_Edit", m => BuildViewModel(m)).Location("Content"); } private void BuildViewModel(SiteSettingsPropertyDeploymentStepViewModel model) diff --git a/src/OrchardCore/OrchardCore.Setup.Core/SetupService.cs b/src/OrchardCore/OrchardCore.Setup.Core/SetupService.cs index 7fb1dde7d03..ff20ca6457f 100644 --- a/src/OrchardCore/OrchardCore.Setup.Core/SetupService.cs +++ b/src/OrchardCore/OrchardCore.Setup.Core/SetupService.cs @@ -60,7 +60,8 @@ public SetupService( IStringLocalizer stringLocalizer, IHostApplicationLifetime applicationLifetime, IHttpContextAccessor httpContextAccessor, - IDbConnectionValidator dbConnectionValidator) + IDbConnectionValidator dbConnectionValidator + ) { _shellHost = shellHost; _applicationName = hostingEnvironment.ApplicationName; @@ -119,13 +120,7 @@ private async Task SetupInternalAsync(SetupContext context) } // Features to enable for Setup. - string[] coreFeatures = - [ - _applicationName, - "OrchardCore.Features", - "OrchardCore.Scripting", - "OrchardCore.Recipes" - ]; + string[] coreFeatures = [_applicationName, "OrchardCore.Features", "OrchardCore.Scripting", "OrchardCore.Recipes"]; context.EnabledFeatures = coreFeatures.Union(context.EnabledFeatures ?? []).Distinct().ToList(); @@ -155,9 +150,15 @@ private async Task SetupInternalAsync(SetupContext context) var shellSettings = new ShellSettings(context.ShellSettings).ConfigureDatabaseTableOptions(); if (string.IsNullOrWhiteSpace(shellSettings["DatabaseProvider"])) { - shellSettings["DatabaseProvider"] = context.Properties.TryGetValue(SetupConstants.DatabaseProvider, out var databaseProvider) ? databaseProvider?.ToString() : string.Empty; - shellSettings["ConnectionString"] = context.Properties.TryGetValue(SetupConstants.DatabaseConnectionString, out var databaseConnectionString) ? databaseConnectionString?.ToString() : string.Empty; - shellSettings["TablePrefix"] = context.Properties.TryGetValue(SetupConstants.DatabaseTablePrefix, out var databaseTablePrefix) ? databaseTablePrefix?.ToString() : string.Empty; + shellSettings["DatabaseProvider"] = context.Properties.TryGetValue(SetupConstants.DatabaseProvider, out var databaseProvider) + ? databaseProvider?.ToString() + : string.Empty; + shellSettings["ConnectionString"] = context.Properties.TryGetValue(SetupConstants.DatabaseConnectionString, out var databaseConnectionString) + ? databaseConnectionString?.ToString() + : string.Empty; + shellSettings["TablePrefix"] = context.Properties.TryGetValue(SetupConstants.DatabaseTablePrefix, out var databaseTablePrefix) + ? databaseTablePrefix?.ToString() + : string.Empty; shellSettings["Schema"] = context.Properties.TryGetValue(SetupConstants.DatabaseSchema, out var schema) ? schema?.ToString() : null; } @@ -179,7 +180,13 @@ private async Task SetupInternalAsync(SetupContext context) context.Errors.Add(string.Empty, S["The provided connection string is invalid or server is unreachable."]); break; case DbConnectionValidatorResult.InvalidCertificate: - context.Errors.Add(string.Empty, S["The security certificate on the server is from a non-trusted source (the certificate issuing authority isn't listed as a trusted authority in Trusted Root Certification Authorities on the client machine). In a development environment, you have the option to use the '{0}' parameter in your connection string to bypass the validation performed by the certificate authority.", "TrustServerCertificate=True"]); + context.Errors.Add( + string.Empty, + S[ + "The security certificate on the server is from a non-trusted source (the certificate issuing authority isn't listed as a trusted authority in Trusted Root Certification Authorities on the client machine). In a development environment, you have the option to use the '{0}' parameter in your connection string to bypass the validation performed by the certificate authority.", + "TrustServerCertificate=True" + ] + ); break; case DbConnectionValidatorResult.DocumentTableFound: context.Errors.Add(string.Empty, S["The provided database, table prefix and schema are already in use."]); @@ -195,10 +202,7 @@ private async Task SetupInternalAsync(SetupContext context) // In theory this environment can be used to resolve any normal components by interface, and those // components will exist entirely in isolation - no crossover between the safemode container currently in effect // It is used to initialize the database before the recipe is run. - var shellDescriptor = new ShellDescriptor - { - Features = context.EnabledFeatures.Select(id => new ShellFeature(id)).ToList() - }; + var shellDescriptor = new ShellDescriptor { Features = context.EnabledFeatures.Select(id => new ShellFeature(id)).ToList() }; string executionId; @@ -209,8 +213,7 @@ private async Task SetupInternalAsync(SetupContext context) try { // Create the "minimum" shell descriptor. - await scope.ServiceProvider.GetService() - .UpdateShellDescriptorAsync(0, shellContext.Blueprint.Descriptor.Features); + await scope.ServiceProvider.GetService().UpdateShellDescriptorAsync(0, shellContext.Blueprint.Descriptor.Features); } catch (Exception e) { diff --git a/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellConfigurationSources.cs b/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellConfigurationSources.cs index b5f3541f482..2767e01899b 100644 --- a/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellConfigurationSources.cs +++ b/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellConfigurationSources.cs @@ -20,10 +20,7 @@ public class BlobShellConfigurationSources : IShellConfigurationSources private readonly string _container; private readonly string _fileStoreContainer; - public BlobShellConfigurationSources( - IShellsFileStore shellsFileStore, - BlobShellStorageOptions blobOptions, - IOptions shellOptions) + public BlobShellConfigurationSources(IShellsFileStore shellsFileStore, BlobShellStorageOptions blobOptions, IOptions shellOptions) { _shellsFileStore = shellsFileStore; _blobOptions = blobOptions; diff --git a/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellsConfigurationSources.cs b/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellsConfigurationSources.cs index 25b028162c2..dded53fd18e 100644 --- a/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellsConfigurationSources.cs +++ b/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellsConfigurationSources.cs @@ -22,7 +22,7 @@ public BlobShellsConfigurationSources( IHostEnvironment hostingEnvironment, BlobShellStorageOptions blobOptions, IOptions shellOptions - ) + ) { _shellsFileStore = shellsFileStore; _environment = hostingEnvironment.EnvironmentName; diff --git a/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellsSettingsSources.cs b/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellsSettingsSources.cs index c741bace9db..d5cb15ea21f 100644 --- a/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellsSettingsSources.cs +++ b/src/OrchardCore/OrchardCore.Shells.Azure/Configuration/BlobShellsSettingsSources.cs @@ -21,9 +21,7 @@ public class BlobShellsSettingsSources : IShellsSettingsSources private readonly string _tenantsFileSystemName; - public BlobShellsSettingsSources(IShellsFileStore shellsFileStore, - BlobShellStorageOptions blobOptions, - IOptions shellOptions) + public BlobShellsSettingsSources(IShellsFileStore shellsFileStore, BlobShellStorageOptions blobOptions, IOptions shellOptions) { _shellsFileStore = shellsFileStore; _blobOptions = blobOptions; diff --git a/src/OrchardCore/OrchardCore.Shells.Azure/Extensions/BlobShellsOrchardCoreBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Shells.Azure/Extensions/BlobShellsOrchardCoreBuilderExtensions.cs index e3f5f161dfe..8ee6ed8aaaa 100644 --- a/src/OrchardCore/OrchardCore.Shells.Azure/Extensions/BlobShellsOrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Shells.Azure/Extensions/BlobShellsOrchardCoreBuilderExtensions.cs @@ -28,8 +28,8 @@ public static OrchardCoreBuilder AddAzureShellsConfiguration(this OrchardCoreBui { var configuration = sp.GetRequiredService(); - var blobOptions = configuration.GetSectionCompat("OrchardCore:OrchardCore_Shells_Azure") - .Get() + var blobOptions = + configuration.GetSectionCompat("OrchardCore:OrchardCore_Shells_Azure").Get() ?? throw new Exception("The 'OrchardCore.Shells.Azure' configuration section must be defined"); var clock = sp.GetRequiredService(); @@ -40,36 +40,42 @@ public static OrchardCoreBuilder AddAzureShellsConfiguration(this OrchardCoreBui return new BlobShellsFileStore(fileStore); }); - services.Replace(ServiceDescriptor.Singleton(sp => - { - var shellsFileStore = sp.GetRequiredService(); - var configuration = sp.GetRequiredService(); - var blobOptions = configuration.GetSectionCompat("OrchardCore:OrchardCore_Shells_Azure").Get(); - var shellOptions = sp.GetRequiredService>(); + services.Replace( + ServiceDescriptor.Singleton(sp => + { + var shellsFileStore = sp.GetRequiredService(); + var configuration = sp.GetRequiredService(); + var blobOptions = configuration.GetSectionCompat("OrchardCore:OrchardCore_Shells_Azure").Get(); + var shellOptions = sp.GetRequiredService>(); - return new BlobShellsSettingsSources(shellsFileStore, blobOptions, shellOptions); - })); + return new BlobShellsSettingsSources(shellsFileStore, blobOptions, shellOptions); + }) + ); - services.Replace(ServiceDescriptor.Singleton(sp => - { - var shellsFileStore = sp.GetRequiredService(); - var configuration = sp.GetRequiredService(); - var blobOptions = configuration.GetSectionCompat("OrchardCore:OrchardCore_Shells_Azure").Get(); - var shellOptions = sp.GetRequiredService>(); + services.Replace( + ServiceDescriptor.Singleton(sp => + { + var shellsFileStore = sp.GetRequiredService(); + var configuration = sp.GetRequiredService(); + var blobOptions = configuration.GetSectionCompat("OrchardCore:OrchardCore_Shells_Azure").Get(); + var shellOptions = sp.GetRequiredService>(); - return new BlobShellConfigurationSources(shellsFileStore, blobOptions, shellOptions); - })); + return new BlobShellConfigurationSources(shellsFileStore, blobOptions, shellOptions); + }) + ); - services.Replace(ServiceDescriptor.Singleton(sp => - { - var shellsFileStore = sp.GetRequiredService(); - var environment = sp.GetRequiredService(); - var configuration = sp.GetRequiredService(); - var blobOptions = configuration.GetSectionCompat("OrchardCore:OrchardCore_Shells_Azure").Get(); - var shellOptions = sp.GetRequiredService>(); + services.Replace( + ServiceDescriptor.Singleton(sp => + { + var shellsFileStore = sp.GetRequiredService(); + var environment = sp.GetRequiredService(); + var configuration = sp.GetRequiredService(); + var blobOptions = configuration.GetSectionCompat("OrchardCore:OrchardCore_Shells_Azure").Get(); + var shellOptions = sp.GetRequiredService>(); - return new BlobShellsConfigurationSources(shellsFileStore, environment, blobOptions, shellOptions); - })); + return new BlobShellsConfigurationSources(shellsFileStore, environment, blobOptions, shellOptions); + }) + ); return builder; } diff --git a/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ServiceCollectionExtensions.cs index bd6e1d398dc..2ba740be51a 100644 --- a/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ServiceCollectionExtensions.cs @@ -6,10 +6,11 @@ namespace OrchardCore.Shortcodes { public static class ServiceCollectionExtensions { - public static IServiceCollection AddShortcode(this IServiceCollection services, string name) where T : class, IShortcodeProvider => - services.AddShortcode(name, null); + public static IServiceCollection AddShortcode(this IServiceCollection services, string name) + where T : class, IShortcodeProvider => services.AddShortcode(name, null); - public static IServiceCollection AddShortcode(this IServiceCollection services, string name, Action describe) where T : class, IShortcodeProvider + public static IServiceCollection AddShortcode(this IServiceCollection services, string name, Action describe) + where T : class, IShortcodeProvider { services.Configure(options => options.AddShortcode(name, describe)); services.AddScoped(); diff --git a/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ShortcodeDescriptor.cs b/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ShortcodeDescriptor.cs index d79d0eb94e3..38dbb512f00 100644 --- a/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ShortcodeDescriptor.cs +++ b/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ShortcodeDescriptor.cs @@ -25,10 +25,7 @@ public string DefaultValue return _defaultValue; } } - set - { - _defaultValue = value; - } + set { _defaultValue = value; } } /// diff --git a/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ShortcodeOption.cs b/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ShortcodeOption.cs index dc644177f83..dd27220077c 100644 --- a/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ShortcodeOption.cs +++ b/src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ShortcodeOption.cs @@ -25,10 +25,7 @@ public string DefaultValue return _defaultValue; } } - set - { - _defaultValue = value; - } + set { _defaultValue = value; } } /// diff --git a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapSourceBuilderBase.cs b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapSourceBuilderBase.cs index 8e2809545bf..a3b8a25a88c 100644 --- a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapSourceBuilderBase.cs +++ b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapSourceBuilderBase.cs @@ -6,7 +6,8 @@ namespace OrchardCore.Sitemaps.Builders /// /// Inherit to provide a sitemap source item builder. /// - public abstract class SitemapSourceBuilderBase : ISitemapSourceBuilder where TSitemapSource : SitemapSource + public abstract class SitemapSourceBuilderBase : ISitemapSourceBuilder + where TSitemapSource : SitemapSource { async Task ISitemapSourceBuilder.BuildAsync(SitemapSource source, SitemapBuilderContext context) { @@ -15,7 +16,6 @@ async Task ISitemapSourceBuilder.BuildAsync(SitemapSource source, SitemapBuilder { await BuildSourceAsync(tSource, context); } - } public abstract Task BuildSourceAsync(TSitemapSource source, SitemapBuilderContext context); diff --git a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapSourceModifiedDateProviderBase.cs b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapSourceModifiedDateProviderBase.cs index aed3e1cc840..4837dd8514e 100644 --- a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapSourceModifiedDateProviderBase.cs +++ b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapSourceModifiedDateProviderBase.cs @@ -7,7 +7,8 @@ namespace OrchardCore.Sitemaps.Builders /// /// Inherit to provide a sitemap source modified date provider. /// - public abstract class SitemapSourceModifiedDateProviderBase : ISitemapSourceModifiedDateProvider where TSitemapSource : SitemapSource + public abstract class SitemapSourceModifiedDateProviderBase : ISitemapSourceModifiedDateProvider + where TSitemapSource : SitemapSource { Task ISitemapSourceModifiedDateProvider.GetLastModifiedDateAsync(SitemapSource source) { diff --git a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapTypeBuilderBase.cs b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapTypeBuilderBase.cs index a345db81701..ef0382099b7 100644 --- a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapTypeBuilderBase.cs +++ b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Builders/SitemapTypeBuilderBase.cs @@ -6,7 +6,8 @@ namespace OrchardCore.Sitemaps.Builders /// /// Inherit to provide a sitemap type builder. /// - public abstract class SitemapTypeBuilderBase : ISitemapTypeBuilder where TSitemapType : SitemapType + public abstract class SitemapTypeBuilderBase : ISitemapTypeBuilder + where TSitemapType : SitemapType { public async Task BuildAsync(SitemapType sitemap, SitemapBuilderContext context) { diff --git a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/IRouteableContentTypeCoordinator.cs b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/IRouteableContentTypeCoordinator.cs index 97f78bf245e..3e20afb981a 100644 --- a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/IRouteableContentTypeCoordinator.cs +++ b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/IRouteableContentTypeCoordinator.cs @@ -26,6 +26,5 @@ public interface IRouteableContentTypeCoordinator /// Lists all routable content types. /// [Obsolete($"Instead, utilize the {nameof(ListRoutableTypeDefinitionsAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable ListRoutableTypeDefinitions() - => ListRoutableTypeDefinitionsAsync().GetAwaiter().GetResult(); + IEnumerable ListRoutableTypeDefinitions() => ListRoutableTypeDefinitionsAsync().GetAwaiter().GetResult(); } diff --git a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/IRouteableContentTypeProvider.cs b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/IRouteableContentTypeProvider.cs index 1865de01911..18cd9aaecc7 100644 --- a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/IRouteableContentTypeProvider.cs +++ b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/IRouteableContentTypeProvider.cs @@ -26,6 +26,5 @@ public interface IRouteableContentTypeProvider /// Provides routable content types. /// [Obsolete($"Instead, utilize the {nameof(ListRoutableTypeDefinitionsAsync)} method. This current method is slated for removal in upcoming releases.")] - IEnumerable ListRoutableTypeDefinitions() - => ListRoutableTypeDefinitionsAsync().GetAwaiter().GetResult(); + IEnumerable ListRoutableTypeDefinitions() => ListRoutableTypeDefinitionsAsync().GetAwaiter().GetResult(); } diff --git a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/ISitemapSourceFactory.cs b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/ISitemapSourceFactory.cs index aef049e898f..672227002d9 100644 --- a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/ISitemapSourceFactory.cs +++ b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Services/ISitemapSourceFactory.cs @@ -8,7 +8,8 @@ public interface ISitemapSourceFactory SitemapSource Create(); } - public class SitemapSourceFactory : ISitemapSourceFactory where TSitemapSource : SitemapSource, new() + public class SitemapSourceFactory : ISitemapSourceFactory + where TSitemapSource : SitemapSource, new() { private static readonly string _typeName = typeof(TSitemapSource).Name; @@ -23,10 +24,7 @@ public SitemapSourceFactory(ISitemapIdGenerator sitemapIdGenerator) public SitemapSource Create() { - return new TSitemapSource() - { - Id = _sitemapIdGenerator.GenerateUniqueId() - }; + return new TSitemapSource() { Id = _sitemapIdGenerator.GenerateUniqueId() }; } } } diff --git a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/SitemapsRazorPagesContentTypeOption.cs b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/SitemapsRazorPagesContentTypeOption.cs index 18dfdcbd9e2..193f26b208e 100644 --- a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/SitemapsRazorPagesContentTypeOption.cs +++ b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/SitemapsRazorPagesContentTypeOption.cs @@ -22,7 +22,7 @@ public SitemapsRazorPagesContentTypeOption(string contentType) /// /// Route values used to create the link to the razor page. - /// Must include the area, or namespace of module, the razor page belongs to. + /// Must include the area, or namespace of module, the razor page belongs to. /// public Func RouteValues { get; set; } } diff --git a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/SitemapsRazorPagesOptions.cs b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/SitemapsRazorPagesOptions.cs index 6449316c86c..372ab56be87 100644 --- a/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/SitemapsRazorPagesOptions.cs +++ b/src/OrchardCore/OrchardCore.Sitemaps.Abstractions/SitemapsRazorPagesOptions.cs @@ -5,7 +5,6 @@ namespace OrchardCore.Sitemaps { public class SitemapsRazorPagesOptions { - private readonly List _contentTypeOptions = []; public SitemapsRazorPagesOptions ConfigureContentType(string contentType, Action action) diff --git a/src/OrchardCore/OrchardCore.Sms.Abstractions/SmsProviderOptions.cs b/src/OrchardCore/OrchardCore.Sms.Abstractions/SmsProviderOptions.cs index 3822def7dae..035ba27f4ff 100644 --- a/src/OrchardCore/OrchardCore.Sms.Abstractions/SmsProviderOptions.cs +++ b/src/OrchardCore/OrchardCore.Sms.Abstractions/SmsProviderOptions.cs @@ -15,8 +15,7 @@ public class SmsProviderOptions /// The 'Key' is the technical name of the provider. /// The 'Value' is the type of the SMS provider. The type will always be an implementation of interface. /// - public IReadOnlyDictionary Providers - => _readonlyProviders ??= _providers.ToFrozenDictionary(x => x.Key, x => x.Value); + public IReadOnlyDictionary Providers => _readonlyProviders ??= _providers.ToFrozenDictionary(x => x.Key, x => x.Value); /// /// Adds a provider if one does not exist. diff --git a/src/OrchardCore/OrchardCore.Sms.Abstractions/SmsResult.cs b/src/OrchardCore/OrchardCore.Sms.Abstractions/SmsResult.cs index f1fc52996ce..980e00fbffd 100644 --- a/src/OrchardCore/OrchardCore.Sms.Abstractions/SmsResult.cs +++ b/src/OrchardCore/OrchardCore.Sms.Abstractions/SmsResult.cs @@ -8,10 +8,7 @@ public class SmsResult /// /// Returns an indicating a successful SMS operation. /// - public readonly static SmsResult Success = new() - { - Succeeded = true - }; + public readonly static SmsResult Success = new() { Succeeded = true }; /// /// An containing an errors that occurred during the SMS operation. @@ -32,10 +29,5 @@ public class SmsResult /// Creates an indicating a failed SMS operation, with a list of errors if applicable. /// /// An optional array of which caused the operation to fail. - public static SmsResult Failed(params LocalizedString[] errors) - => new() - { - Succeeded = false, - Errors = errors ?? [], - }; + public static SmsResult Failed(params LocalizedString[] errors) => new() { Succeeded = false, Errors = errors ?? [], }; } diff --git a/src/OrchardCore/OrchardCore.Sms.Core/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Sms.Core/ServiceCollectionExtensions.cs index 21a1dc924f0..fe3fc0e146d 100644 --- a/src/OrchardCore/OrchardCore.Sms.Core/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Sms.Core/ServiceCollectionExtensions.cs @@ -17,18 +17,14 @@ public static IServiceCollection AddSmsServices(this IServiceCollection services return services; } - public static void AddPhoneFormatValidator(this IServiceCollection services) - => services.TryAddScoped(); + public static void AddPhoneFormatValidator(this IServiceCollection services) => services.TryAddScoped(); public static IServiceCollection AddSmsProvider(this IServiceCollection services, string name) where T : class, ISmsProvider { services.Configure(options => { - options.TryAddProvider(name, new SmsProviderTypeOptions(typeof(T)) - { - IsEnabled = true, - }); + options.TryAddProvider(name, new SmsProviderTypeOptions(typeof(T)) { IsEnabled = true, }); }); return services; @@ -44,14 +40,18 @@ public static IServiceCollection AddSmsProviderOptionsConfiguration - { - client.BaseAddress = new Uri("https://api.twilio.com/2010-04-01/Accounts/"); - }).AddStandardResilienceHandler(); + services + .AddHttpClient( + TwilioSmsProvider.TechnicalName, + client => + { + client.BaseAddress = new Uri("https://api.twilio.com/2010-04-01/Accounts/"); + } + ) + .AddStandardResilienceHandler(); return services.AddSmsProviderOptionsConfiguration(); } - public static IServiceCollection AddLogSmsProvider(this IServiceCollection services) - => services.AddSmsProvider(LogSmsProvider.TechnicalName); + public static IServiceCollection AddLogSmsProvider(this IServiceCollection services) => services.AddSmsProvider(LogSmsProvider.TechnicalName); } diff --git a/src/OrchardCore/OrchardCore.Sms.Core/Services/DefaultSmsProviderResolver.cs b/src/OrchardCore/OrchardCore.Sms.Core/Services/DefaultSmsProviderResolver.cs index aab4b71fcef..0e39cb1b520 100644 --- a/src/OrchardCore/OrchardCore.Sms.Core/Services/DefaultSmsProviderResolver.cs +++ b/src/OrchardCore/OrchardCore.Sms.Core/Services/DefaultSmsProviderResolver.cs @@ -19,7 +19,8 @@ public DefaultSmsProviderResolver( ISiteService siteService, ILogger logger, IOptions smsProviderOptions, - IServiceProvider serviceProvider) + IServiceProvider serviceProvider + ) { _siteService = siteService; _logger = logger; diff --git a/src/OrchardCore/OrchardCore.Sms.Core/Services/LogSmsProvider.cs b/src/OrchardCore/OrchardCore.Sms.Core/Services/LogSmsProvider.cs index 947332a07c0..80befe9024c 100644 --- a/src/OrchardCore/OrchardCore.Sms.Core/Services/LogSmsProvider.cs +++ b/src/OrchardCore/OrchardCore.Sms.Core/Services/LogSmsProvider.cs @@ -13,9 +13,7 @@ public class LogSmsProvider : ISmsProvider public LocalizedString Name => S["Log - writes messages to the logs"]; - public LogSmsProvider( - IStringLocalizer stringLocalizer, - ILogger logger) + public LogSmsProvider(IStringLocalizer stringLocalizer, ILogger logger) { S = stringLocalizer; _logger = logger; diff --git a/src/OrchardCore/OrchardCore.Sms.Core/Services/SmsNotificationProvider.cs b/src/OrchardCore/OrchardCore.Sms.Core/Services/SmsNotificationProvider.cs index c27e38a093e..23f0d159e59 100644 --- a/src/OrchardCore/OrchardCore.Sms.Core/Services/SmsNotificationProvider.cs +++ b/src/OrchardCore/OrchardCore.Sms.Core/Services/SmsNotificationProvider.cs @@ -10,9 +10,7 @@ public class SmsNotificationProvider : INotificationMethodProvider private readonly ISmsService _smsService; protected readonly IStringLocalizer S; - public SmsNotificationProvider( - ISmsService smsService, - IStringLocalizer stringLocalizer) + public SmsNotificationProvider(ISmsService smsService, IStringLocalizer stringLocalizer) { _smsService = smsService; S = stringLocalizer; @@ -31,11 +29,7 @@ public async Task TrySendAsync(object notify, INotificationMessage message return false; } - var mailMessage = new SmsMessage() - { - To = user.Email, - Body = message.TextBody, - }; + var mailMessage = new SmsMessage() { To = user.Email, Body = message.TextBody, }; var result = await _smsService.SendAsync(mailMessage); diff --git a/src/OrchardCore/OrchardCore.Sms.Core/Services/SmsService.cs b/src/OrchardCore/OrchardCore.Sms.Core/Services/SmsService.cs index 8c31d811f7f..7dfd1318a3b 100644 --- a/src/OrchardCore/OrchardCore.Sms.Core/Services/SmsService.cs +++ b/src/OrchardCore/OrchardCore.Sms.Core/Services/SmsService.cs @@ -10,9 +10,7 @@ public class SmsService : ISmsService protected readonly IStringLocalizer S; - public SmsService( - ISmsProviderResolver smsProviderResolver, - IStringLocalizer stringLocalizer) + public SmsService(ISmsProviderResolver smsProviderResolver, IStringLocalizer stringLocalizer) { _smsProviderResolver = smsProviderResolver; S = stringLocalizer; diff --git a/src/OrchardCore/OrchardCore.Sms.Core/Services/TwilioSmsProvider.cs b/src/OrchardCore/OrchardCore.Sms.Core/Services/TwilioSmsProvider.cs index c81848ddb2e..130e75a69ad 100644 --- a/src/OrchardCore/OrchardCore.Sms.Core/Services/TwilioSmsProvider.cs +++ b/src/OrchardCore/OrchardCore.Sms.Core/Services/TwilioSmsProvider.cs @@ -20,10 +20,7 @@ public class TwilioSmsProvider : ISmsProvider public const string ProtectorName = "Twilio"; - private static readonly JsonSerializerOptions _jsonSerializerOptions = new() - { - PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance, - }; + private static readonly JsonSerializerOptions _jsonSerializerOptions = new() { PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance, }; public LocalizedString Name => S["Twilio"]; @@ -39,7 +36,8 @@ public TwilioSmsProvider( IDataProtectionProvider dataProtectionProvider, ILogger logger, IHttpClientFactory httpClientFactory, - IStringLocalizer stringLocalizer) + IStringLocalizer stringLocalizer + ) { _siteService = siteService; _dataProtectionProvider = dataProtectionProvider; @@ -65,12 +63,7 @@ public async Task SendAsync(SmsMessage message) try { var settings = await GetSettingsAsync(); - var data = new List> - { - new ("From", settings.PhoneNumber), - new ("To", message.To), - new ("Body", message.Body), - }; + var data = new List> { new("From", settings.PhoneNumber), new("To", message.To), new("Body", message.Body), }; var client = GetHttpClient(settings); var response = await client.PostAsync($"{settings.AccountSID}/Messages.json", new FormUrlEncodedContent(data)); @@ -79,8 +72,7 @@ public async Task SendAsync(SmsMessage message) { var result = await response.Content.ReadFromJsonAsync(_jsonSerializerOptions); - if (string.Equals(result.Status, "sent", StringComparison.OrdinalIgnoreCase) || - string.Equals(result.Status, "queued", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(result.Status, "sent", StringComparison.OrdinalIgnoreCase) || string.Equals(result.Status, "queued", StringComparison.OrdinalIgnoreCase)) { return SmsResult.Success; } diff --git a/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UpdateRolesContext.cs b/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UpdateRolesContext.cs index d98a6b25893..edcbf665e1b 100644 --- a/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UpdateRolesContext.cs +++ b/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UpdateRolesContext.cs @@ -15,7 +15,8 @@ public class UpdateRolesContext : UserContextBase /// The login provider. /// The user claims. /// The user roles. - public UpdateRolesContext(IUser user, string loginProvider, IEnumerable externalClaims, IEnumerable userRoles) : base(user) + public UpdateRolesContext(IUser user, string loginProvider, IEnumerable externalClaims, IEnumerable userRoles) + : base(user) { ExternalClaims = externalClaims.AsEnumerable(); UserRoles = userRoles; diff --git a/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserContext.cs b/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserContext.cs index d9252877e4f..4c140f7a19d 100644 --- a/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserContext.cs +++ b/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserContext.cs @@ -6,8 +6,7 @@ namespace OrchardCore.Users.Handlers public class UserContext : UserContextBase { /// - public UserContext(IUser user) : base(user) - { - } + public UserContext(IUser user) + : base(user) { } } } diff --git a/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserCreateContext.cs b/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserCreateContext.cs index b0115a37a7f..cffd8ca8dd1 100644 --- a/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserCreateContext.cs +++ b/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserCreateContext.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Users.Handlers public class UserCreateContext : UserContextBase { /// - public UserCreateContext(IUser user) : base(user) - { - } + public UserCreateContext(IUser user) + : base(user) { } public bool Cancel { get; set; } } diff --git a/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserDeleteContext.cs b/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserDeleteContext.cs index afb33232440..e4bede2563f 100644 --- a/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserDeleteContext.cs +++ b/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserDeleteContext.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Users.Handlers public class UserDeleteContext : UserContextBase { /// - public UserDeleteContext(IUser user) : base(user) - { - } + public UserDeleteContext(IUser user) + : base(user) { } public bool Cancel { get; set; } } diff --git a/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserUpdateContext.cs b/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserUpdateContext.cs index 5501b59cb43..1fc70a4d6f2 100644 --- a/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserUpdateContext.cs +++ b/src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserUpdateContext.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Users.Handlers public class UserUpdateContext : UserContextBase { /// - public UserUpdateContext(IUser user) : base(user) - { - } + public UserUpdateContext(IUser user) + : base(user) { } public bool Cancel { get; set; } } diff --git a/src/OrchardCore/OrchardCore.Users.Core/Authentication/CacheTicketStore.cs b/src/OrchardCore/OrchardCore.Users.Core/Authentication/CacheTicketStore.cs index 82bde65c04f..08711007091 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Authentication/CacheTicketStore.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Authentication/CacheTicketStore.cs @@ -24,8 +24,10 @@ public CacheTicketStore(IHttpContextAccessor httpContextAccessor) _httpContextAccessor = httpContextAccessor; } - public IDataProtector DataProtector => _dataProtector ??= _httpContextAccessor.HttpContext.RequestServices.GetService() - .CreateProtector($"{nameof(CacheTicketStore)}_{IdentityConstants.ApplicationScheme}"); + public IDataProtector DataProtector => + _dataProtector ??= _httpContextAccessor + .HttpContext.RequestServices.GetService() + .CreateProtector($"{nameof(CacheTicketStore)}_{IdentityConstants.ApplicationScheme}"); public ILogger Logger => _logger ??= _httpContextAccessor.HttpContext.RequestServices.GetService>(); @@ -95,9 +97,7 @@ public async Task StoreAsync(AuthenticationTicket ticket) } } - private static byte[] SerializeTicket(AuthenticationTicket source) - => TicketSerializer.Default.Serialize(source); + private static byte[] SerializeTicket(AuthenticationTicket source) => TicketSerializer.Default.Serialize(source); - private static AuthenticationTicket DeserializeTicket(byte[] source) - => source == null ? null : TicketSerializer.Default.Deserialize(source); + private static AuthenticationTicket DeserializeTicket(byte[] source) => source == null ? null : TicketSerializer.Default.Deserialize(source); } diff --git a/src/OrchardCore/OrchardCore.Users.Core/CommonPermissions.cs b/src/OrchardCore/OrchardCore.Users.Core/CommonPermissions.cs index c7a7cc62c95..6d2e60f1b75 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/CommonPermissions.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/CommonPermissions.cs @@ -41,12 +41,7 @@ public static Permission CreatePermissionForManageUsersInRole(string name) => CreateDynamicPermission(name, new Permission("ManageUsersInRole_{0}", "Manage users in {0} role", new[] { ManageUsers }, true)); // Dynamic permission template. - private static Permission CreateDynamicPermission(string roleName, Permission permission) - => new( - string.Format(permission.Name, roleName), - string.Format(permission.Description, roleName), - permission.ImpliedBy, - permission.IsSecurityCritical - ); + private static Permission CreateDynamicPermission(string roleName, Permission permission) => + new(string.Format(permission.Name, roleName), string.Format(permission.Description, roleName), permission.ImpliedBy, permission.IsSecurityCritical); } } diff --git a/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByClaimIndex.cs b/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByClaimIndex.cs index e17022e61d1..3833caf7b48 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByClaimIndex.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByClaimIndex.cs @@ -15,12 +15,7 @@ public class UserByClaimIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() - .Map(user => user.UserClaims.Select(x => new UserByClaimIndex - { - ClaimType = x.ClaimType, - ClaimValue = x.ClaimValue, - })); + context.For().Map(user => user.UserClaims.Select(x => new UserByClaimIndex { ClaimType = x.ClaimType, ClaimValue = x.ClaimValue, })); } } } diff --git a/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByLoginInfoIndex.cs b/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByLoginInfoIndex.cs index 7d726afe536..a03523cffdf 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByLoginInfoIndex.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByLoginInfoIndex.cs @@ -14,12 +14,9 @@ public class UserByLoginInfoIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() - .Map(user => user.LoginInfos.Select(x => new UserByLoginInfoIndex - { - LoginProvider = x.LoginProvider, - ProviderKey = x.ProviderKey, - })); + context + .For() + .Map(user => user.LoginInfos.Select(x => new UserByLoginInfoIndex { LoginProvider = x.LoginProvider, ProviderKey = x.ProviderKey, })); } } } diff --git a/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByRoleNameIndex.cs b/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByRoleNameIndex.cs index bb3fe817d39..c61d1c3fc2c 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByRoleNameIndex.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserByRoleNameIndex.cs @@ -22,7 +22,8 @@ public UserByRoleNameIndexProvider(ILookupNormalizer keyNormalizer) public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(user => { // Include a marker that the user does not have any roles, i.e. is Authenticated only. @@ -30,30 +31,21 @@ public override void Describe(DescribeContext context) { return new UserByRoleNameIndex[] { - new() { - RoleName = NormalizeKey("Authenticated"), - Count = 1 - } + new() { RoleName = NormalizeKey("Authenticated"), Count = 1 } }; } - return user.RoleNames.Select(x => new UserByRoleNameIndex - { - RoleName = NormalizeKey(x), - Count = 1 - }); + return user.RoleNames.Select(x => new UserByRoleNameIndex { RoleName = NormalizeKey(x), Count = 1 }); }) .Group(index => index.RoleName) - .Reduce(group => new UserByRoleNameIndex - { - RoleName = group.Key, - Count = group.Sum(x => x.Count) - }) - .Delete((index, map) => - { - index.Count -= map.Sum(x => x.Count); - return index.Count > 0 ? index : null; - }); + .Reduce(group => new UserByRoleNameIndex { RoleName = group.Key, Count = group.Sum(x => x.Count) }) + .Delete( + (index, map) => + { + index.Count -= map.Sum(x => x.Count); + return index.Count > 0 ? index : null; + } + ); } private string NormalizeKey(string key) diff --git a/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserIndex.cs b/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserIndex.cs index 0c60e58d8d2..198794653e9 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserIndex.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Indexes/UserIndex.cs @@ -20,7 +20,8 @@ public class UserIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(user => { return new UserIndex diff --git a/src/OrchardCore/OrchardCore.Users.Core/Models/UserMenu.cs b/src/OrchardCore/OrchardCore.Users.Core/Models/UserMenu.cs index f83e0520dce..4d3193f2356 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Models/UserMenu.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Models/UserMenu.cs @@ -2,6 +2,4 @@ namespace OrchardCore.Users.Models; -public class UserMenu : Entity -{ -} +public class UserMenu : Entity { } diff --git a/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultTwoFactorAuthenticationHandlerCoordinator.cs b/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultTwoFactorAuthenticationHandlerCoordinator.cs index 61aeae67887..f1d024d469f 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultTwoFactorAuthenticationHandlerCoordinator.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultTwoFactorAuthenticationHandlerCoordinator.cs @@ -10,8 +10,7 @@ public class DefaultTwoFactorAuthenticationHandlerCoordinator : ITwoFactorAuthen private bool? _isRequired = null; - public DefaultTwoFactorAuthenticationHandlerCoordinator( - IEnumerable twoFactorAuthenticationHandlers) + public DefaultTwoFactorAuthenticationHandlerCoordinator(IEnumerable twoFactorAuthenticationHandlers) { _twoFactorAuthenticationHandlers = twoFactorAuthenticationHandlers; } diff --git a/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultUserClaimsPrincipalFactory.cs b/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultUserClaimsPrincipalFactory.cs index bcd6de5e845..e239471b5df 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultUserClaimsPrincipalFactory.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultUserClaimsPrincipalFactory.cs @@ -13,12 +13,8 @@ namespace OrchardCore.Users.Services [Obsolete("The class 'DefaultUserClaimsPrincipalFactory' is obsolete, please implement 'IUserClaimsProvider' instead.")] public class DefaultUserClaimsPrincipalFactory : UserClaimsPrincipalFactory { - public DefaultUserClaimsPrincipalFactory( - UserManager userManager, - RoleManager roleManager, - IOptions identityOptions) : base(userManager, roleManager, identityOptions) - { - } + public DefaultUserClaimsPrincipalFactory(UserManager userManager, RoleManager roleManager, IOptions identityOptions) + : base(userManager, roleManager, identityOptions) { } protected override async Task GenerateClaimsAsync(IUser user) { diff --git a/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultUserClaimsPrincipalProviderFactory.cs b/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultUserClaimsPrincipalProviderFactory.cs index 010f8bee25d..768683c0370 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultUserClaimsPrincipalProviderFactory.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Services/DefaultUserClaimsPrincipalProviderFactory.cs @@ -22,7 +22,9 @@ public DefaultUserClaimsPrincipalProviderFactory( RoleManager roleManager, IOptions identityOptions, IEnumerable claimsProviders, - ILogger logger) : base(userManager, roleManager, identityOptions) + ILogger logger + ) + : base(userManager, roleManager, identityOptions) { _claimsProviders = claimsProviders; _logger = logger; diff --git a/src/OrchardCore/OrchardCore.Users.Core/Services/IUsersAdminListFilterParser.cs b/src/OrchardCore/OrchardCore.Users.Core/Services/IUsersAdminListFilterParser.cs index a8210aa66a5..a60ae2945fc 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Services/IUsersAdminListFilterParser.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Services/IUsersAdminListFilterParser.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Users.Services { - public interface IUsersAdminListFilterParser : IQueryParser - { - } + public interface IUsersAdminListFilterParser : IQueryParser { } } diff --git a/src/OrchardCore/OrchardCore.Users.Core/Services/NullRoleStore.cs b/src/OrchardCore/OrchardCore.Users.Core/Services/NullRoleStore.cs index 783c20e2fa4..2071a38d909 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Services/NullRoleStore.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Services/NullRoleStore.cs @@ -13,48 +13,33 @@ public class NullRoleStore : IRoleClaimStore, IQueryableRoleStore { public IQueryable Roles => Array.Empty().AsQueryable(); - public Task AddClaimAsync(IRole role, Claim claim, CancellationToken cancellationToken = default) - => Task.CompletedTask; + public Task AddClaimAsync(IRole role, Claim claim, CancellationToken cancellationToken = default) => Task.CompletedTask; - public Task CreateAsync(IRole role, CancellationToken cancellationToken) - => Task.FromResult(IdentityResult.Success); + public Task CreateAsync(IRole role, CancellationToken cancellationToken) => Task.FromResult(IdentityResult.Success); - public Task DeleteAsync(IRole role, CancellationToken cancellationToken) - => Task.FromResult(IdentityResult.Success); + public Task DeleteAsync(IRole role, CancellationToken cancellationToken) => Task.FromResult(IdentityResult.Success); #pragma warning disable CA1816 - public void Dispose() - { - } + public void Dispose() { } #pragma warning restore CA1816 - public Task FindByIdAsync(string roleId, CancellationToken cancellationToken) - => Task.FromResult(null); + public Task FindByIdAsync(string roleId, CancellationToken cancellationToken) => Task.FromResult(null); - public Task FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken) - => Task.FromResult(null); + public Task FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken) => Task.FromResult(null); - public Task> GetClaimsAsync(IRole role, CancellationToken cancellationToken = default) - => Task.FromResult>([]); + public Task> GetClaimsAsync(IRole role, CancellationToken cancellationToken = default) => Task.FromResult>([]); - public Task GetNormalizedRoleNameAsync(IRole role, CancellationToken cancellationToken) - => Task.FromResult(null); + public Task GetNormalizedRoleNameAsync(IRole role, CancellationToken cancellationToken) => Task.FromResult(null); - public Task GetRoleIdAsync(IRole role, CancellationToken cancellationToken) - => Task.FromResult(null); + public Task GetRoleIdAsync(IRole role, CancellationToken cancellationToken) => Task.FromResult(null); - public Task GetRoleNameAsync(IRole role, CancellationToken cancellationToken) - => Task.FromResult(null); + public Task GetRoleNameAsync(IRole role, CancellationToken cancellationToken) => Task.FromResult(null); - public Task RemoveClaimAsync(IRole role, Claim claim, CancellationToken cancellationToken = default) - => Task.CompletedTask; + public Task RemoveClaimAsync(IRole role, Claim claim, CancellationToken cancellationToken = default) => Task.CompletedTask; - public Task SetNormalizedRoleNameAsync(IRole role, string normalizedName, CancellationToken cancellationToken) - => Task.CompletedTask; + public Task SetNormalizedRoleNameAsync(IRole role, string normalizedName, CancellationToken cancellationToken) => Task.CompletedTask; - public Task SetRoleNameAsync(IRole role, string roleName, CancellationToken cancellationToken) - => Task.CompletedTask; + public Task SetRoleNameAsync(IRole role, string roleName, CancellationToken cancellationToken) => Task.CompletedTask; - public Task UpdateAsync(IRole role, CancellationToken cancellationToken) - => Task.FromResult(IdentityResult.Success); + public Task UpdateAsync(IRole role, CancellationToken cancellationToken) => Task.FromResult(IdentityResult.Success); } diff --git a/src/OrchardCore/OrchardCore.Users.Core/Services/UserQueryContext.cs b/src/OrchardCore/OrchardCore.Users.Core/Services/UserQueryContext.cs index bd1d8184629..e266bc878a9 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Services/UserQueryContext.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Services/UserQueryContext.cs @@ -7,7 +7,8 @@ namespace OrchardCore.Users.Services { public class UserQueryContext : QueryExecutionContext { - public UserQueryContext(IServiceProvider serviceProvider, IQuery query) : base(query) + public UserQueryContext(IServiceProvider serviceProvider, IQuery query) + : base(query) { ServiceProvider = serviceProvider; } diff --git a/src/OrchardCore/OrchardCore.Users.Core/Services/UserService.cs b/src/OrchardCore/OrchardCore.Users.Core/Services/UserService.cs index 99329d57086..f435755307b 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Services/UserService.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Services/UserService.cs @@ -33,7 +33,8 @@ public UserService( IEnumerable passwordRecoveryFormEvents, IStringLocalizer stringLocalizer, ISiteService siteService, - ILogger logger) + ILogger logger + ) { _signInManager = signInManager; _userManager = userManager; @@ -114,9 +115,7 @@ public async Task CreateUserAsync(IUser user, string password, Action CreatePrincipalAsync(IUser user) return _signInManager.CreateUserPrincipalAsync(user); } - public async Task GetUserAsync(string userName) => - (await _userManager.FindByNameAsync(userName)) ?? await _userManager.FindByEmailAsync(userName); + public async Task GetUserAsync(string userName) => (await _userManager.FindByNameAsync(userName)) ?? await _userManager.FindByEmailAsync(userName); public Task GetUserByUniqueIdAsync(string userIdentifier) => _userManager.FindByIdAsync(userIdentifier); diff --git a/src/OrchardCore/OrchardCore.Users.Core/Services/UserStore.cs b/src/OrchardCore/OrchardCore.Users.Core/Services/UserStore.cs index f542717b5e8..878dc6d144f 100644 --- a/src/OrchardCore/OrchardCore.Users.Core/Services/UserStore.cs +++ b/src/OrchardCore/OrchardCore.Users.Core/Services/UserStore.cs @@ -16,19 +16,19 @@ namespace OrchardCore.Users.Services { - public class UserStore : - IUserClaimStore, - IUserRoleStore, - IUserPasswordStore, - IUserEmailStore, - IUserSecurityStampStore, - IUserLoginStore, - IUserLockoutStore, - IUserAuthenticationTokenStore, - IUserTwoFactorRecoveryCodeStore, - IUserTwoFactorStore, - IUserAuthenticatorKeyStore, - IUserPhoneNumberStore + public class UserStore + : IUserClaimStore, + IUserRoleStore, + IUserPasswordStore, + IUserEmailStore, + IUserSecurityStampStore, + IUserLoginStore, + IUserLockoutStore, + IUserAuthenticationTokenStore, + IUserTwoFactorRecoveryCodeStore, + IUserTwoFactorStore, + IUserAuthenticatorKeyStore, + IUserPhoneNumberStore { private const string TokenProtector = "OrchardCore.UserStore.Token"; private const string InternalLoginProvider = "[OrchardCoreUserStore]"; @@ -42,13 +42,15 @@ public class UserStore : private readonly IRoleService _roleService; private readonly IDataProtectionProvider _dataProtectionProvider; - public UserStore(ISession session, + public UserStore( + ISession session, ILookupNormalizer keyNormalizer, IUserIdGenerator userIdGenerator, ILogger logger, IEnumerable handlers, IRoleService roleService, - IDataProtectionProvider dataProtectionProvider) + IDataProtectionProvider dataProtectionProvider + ) { _session = session; _keyNormalizer = keyNormalizer; @@ -688,11 +690,7 @@ public Task SetTokenAsync(IUser user, string loginProvider, string name, string if (userToken == null && user is User u) { - userToken = new UserToken - { - LoginProvider = loginProvider, - Name = name - }; + userToken = new UserToken { LoginProvider = loginProvider, Name = name }; u.UserTokens.Add(userToken); } @@ -896,11 +894,11 @@ public async Task CountCodesAsync(IUser user, CancellationToken cancellatio #endregion #region IUserAuthenticatorKeyStore - public virtual Task SetAuthenticatorKeyAsync(IUser user, string key, CancellationToken cancellationToken) - => SetTokenAsync(user, InternalLoginProvider, AuthenticatorKeyTokenName, key, cancellationToken); + public virtual Task SetAuthenticatorKeyAsync(IUser user, string key, CancellationToken cancellationToken) => + SetTokenAsync(user, InternalLoginProvider, AuthenticatorKeyTokenName, key, cancellationToken); - public virtual Task GetAuthenticatorKeyAsync(IUser user, CancellationToken cancellationToken) - => GetTokenAsync(user, InternalLoginProvider, AuthenticatorKeyTokenName, cancellationToken); + public virtual Task GetAuthenticatorKeyAsync(IUser user, CancellationToken cancellationToken) => + GetTokenAsync(user, InternalLoginProvider, AuthenticatorKeyTokenName, cancellationToken); #endregion #region IUserPhoneNumberStore diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/Activity.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/Activity.cs index b2807b7be13..972e4969078 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/Activity.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/Activity.cs @@ -139,13 +139,21 @@ protected static ActivityExecutionResult Noop() protected virtual T GetProperty(Func defaultValue = null, [CallerMemberName] string name = null) { var item = Properties[name]; - return item != null ? item.ToObject() : defaultValue != null ? defaultValue() : default; + return item != null + ? item.ToObject() + : defaultValue != null + ? defaultValue() + : default; } protected virtual T GetProperty(Type type, Func defaultValue = null, [CallerMemberName] string name = null) { var item = Properties[name]; - return item != null ? (T)item.ToObject(type) : defaultValue != null ? defaultValue() : default; + return item != null + ? (T)item.ToObject(type) + : defaultValue != null + ? defaultValue() + : default; } protected virtual void SetProperty(object value, [CallerMemberName] string name = null) diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/IEvent.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/IEvent.cs index 8180fa78e47..2dfbc53c4cc 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/IEvent.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/IEvent.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Workflows.Activities { - public interface IEvent : IActivity - { - } + public interface IEvent : IActivity { } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/ITask.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/ITask.cs index 10454bd31f3..b224f41364c 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/ITask.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/ITask.cs @@ -1,6 +1,4 @@ namespace OrchardCore.Workflows.Activities { - public interface ITask : IActivity - { - } + public interface ITask : IActivity { } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/TaskActivity.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/TaskActivity.cs index f3f2fe339be..09e96a456b6 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/TaskActivity.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Activities/TaskActivity.cs @@ -1,10 +1,9 @@ namespace OrchardCore.Workflows.Activities; -public abstract class TaskActivity : Activity, ITask -{ -} +public abstract class TaskActivity : Activity, ITask { } -public abstract class TaskActivity : TaskActivity where TActivity : ITask +public abstract class TaskActivity : TaskActivity + where TActivity : ITask { // The technical name of the activity. Within a workflow definition, activities make use of this name. public override string Name => typeof(TActivity).Name; diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Converters/LocalizedStringConverter.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Converters/LocalizedStringConverter.cs index 3fedbec9e3f..4e3dbc9ab5a 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Converters/LocalizedStringConverter.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Converters/LocalizedStringConverter.cs @@ -17,7 +17,6 @@ public override LocalizedString Read(ref Utf8JsonReader reader, Type typeToConve throw new NotImplementedException(); } - public override void Write(Utf8JsonWriter writer, LocalizedString value, JsonSerializerOptions options) - => JsonValue.Create(value.Value).WriteTo(writer, options); + public override void Write(Utf8JsonWriter writer, LocalizedString value, JsonSerializerOptions options) => JsonValue.Create(value.Value).WriteTo(writer, options); } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Display/ActivityDisplayDriver.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Display/ActivityDisplayDriver.cs index d3487a62d10..aae2db24710 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Display/ActivityDisplayDriver.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Display/ActivityDisplayDriver.cs @@ -10,7 +10,8 @@ namespace OrchardCore.Workflows.Display /// /// Base class for activity drivers. /// - public abstract class ActivityDisplayDriver : DisplayDriver where TActivity : class, IActivity + public abstract class ActivityDisplayDriver : DisplayDriver + where TActivity : class, IActivity { private static readonly string _thumbnailshapeType = $"{typeof(TActivity).Name}_Fields_Thumbnail"; private static readonly string _designShapeType = $"{typeof(TActivity).Name}_Fields_Design"; @@ -27,19 +28,27 @@ public override IDisplayResult Display(TActivity model) /// /// Base class for activity drivers using a strongly typed view model. /// - public abstract class ActivityDisplayDriver : ActivityDisplayDriver where TActivity : class, IActivity where TEditViewModel : class, new() + public abstract class ActivityDisplayDriver : ActivityDisplayDriver + where TActivity : class, IActivity + where TEditViewModel : class, new() { private static readonly string _editShapeType = $"{typeof(TActivity).Name}_Fields_Edit"; public override IDisplayResult Edit(TActivity model) { - return Initialize(_editShapeType, (System.Func)(viewModel => - { - return EditActivityAsync(model, viewModel); - })).Location("Content"); + return Initialize( + _editShapeType, + (System.Func)( + viewModel => + { + return EditActivityAsync(model, viewModel); + } + ) + ) + .Location("Content"); } - public async override Task UpdateAsync(TActivity model, IUpdateModel updater) + public override async Task UpdateAsync(TActivity model, IUpdateModel updater) { var viewModel = new TEditViewModel(); if (await updater.TryUpdateModelAsync(viewModel, Prefix)) @@ -63,9 +72,7 @@ protected virtual ValueTask EditActivityAsync(TActivity activity, TEditViewModel /// /// Edit the view model before it's used in the editor. /// - protected virtual void EditActivity(TActivity activity, TEditViewModel model) - { - } + protected virtual void EditActivity(TActivity activity, TEditViewModel model) { } /// /// Updates the activity when the view model is validated. @@ -80,8 +87,6 @@ protected virtual Task UpdateActivityAsync(TEditViewModel model, TActivity activ /// /// Updates the activity when the view model is validated. /// - protected virtual void UpdateActivity(TEditViewModel model, TActivity activity) - { - } + protected virtual void UpdateActivity(TEditViewModel model, TActivity activity) { } } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Helpers/DistributedLockExtensions.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Helpers/DistributedLockExtensions.cs index ae80c3e9ce2..58fd7530e7b 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Helpers/DistributedLockExtensions.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Helpers/DistributedLockExtensions.cs @@ -12,16 +12,15 @@ public static class DistributedLockExtensions /// Tries to acquire a lock before resuming this workflow instance, but only /// if it is an atomic workflow, otherwise returns true with a null locker. /// - public static Task<(ILocker locker, bool locked)> TryAcquireWorkflowLockAsync( - this IDistributedLock distributedLock, - Workflow workflow) + public static Task<(ILocker locker, bool locked)> TryAcquireWorkflowLockAsync(this IDistributedLock distributedLock, Workflow workflow) { if (workflow.IsAtomic) { return distributedLock.TryAcquireLockAsync( "WFI_" + workflow.WorkflowId + "_LOCK", TimeSpan.FromMilliseconds(workflow.LockTimeout), - TimeSpan.FromMilliseconds(workflow.LockExpiration)); + TimeSpan.FromMilliseconds(workflow.LockExpiration) + ); } return Task.FromResult<(ILocker, bool)>((null, true)); @@ -34,14 +33,12 @@ public static class DistributedLockExtensions public static Task<(ILocker locker, bool locked)> TryAcquireWorkflowTypeLockAsync( this IDistributedLock distributedLock, WorkflowType workflowType, - bool isExclusiveEvent = false) + bool isExclusiveEvent = false + ) { if (workflowType.IsSingleton || isExclusiveEvent) { - return distributedLock.TryAcquireLockAsync( - "WFT_" + workflowType.WorkflowTypeId + "_LOCK", - TimeSpan.FromMilliseconds(20_000), - TimeSpan.FromMilliseconds(20_000)); + return distributedLock.TryAcquireLockAsync("WFT_" + workflowType.WorkflowTypeId + "_LOCK", TimeSpan.FromMilliseconds(20_000), TimeSpan.FromMilliseconds(20_000)); } return Task.FromResult<(ILocker, bool)>((null, true)); diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Helpers/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Helpers/ServiceCollectionExtensions.cs index 2178256c3d0..eea2cd7e8f8 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Helpers/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Helpers/ServiceCollectionExtensions.cs @@ -7,7 +7,9 @@ namespace OrchardCore.Workflows.Helpers { public static class ServiceCollectionExtensions { - public static void AddActivity(this IServiceCollection services) where TActivity : class, IActivity where TDriver : class, IDisplayDriver + public static void AddActivity(this IServiceCollection services) + where TActivity : class, IActivity + where TDriver : class, IDisplayDriver { services.Configure(options => options.RegisterActivity()); } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/Outcome.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/Outcome.cs index dad5d647439..bbc4a69f3be 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/Outcome.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/Outcome.cs @@ -6,9 +6,8 @@ namespace OrchardCore.Workflows.Abstractions.Models { public class Outcome { - public Outcome(LocalizedString displayName) : this(displayName.Name, displayName) - { - } + public Outcome(LocalizedString displayName) + : this(displayName.Name, displayName) { } public Outcome(string name, LocalizedString displayName) { diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowCreatedContext.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowCreatedContext.cs index 23a3f70f875..d745469b2bb 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowCreatedContext.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowCreatedContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.Workflows.Models { public class WorkflowCreatedContext : WorkflowContext { - public WorkflowCreatedContext(Workflow workflow) : base(workflow) - { - } + public WorkflowCreatedContext(Workflow workflow) + : base(workflow) { } } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowDeletedContext.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowDeletedContext.cs index 9a1416e989a..0971aea3aa5 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowDeletedContext.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowDeletedContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.Workflows.Models { public class WorkflowDeletedContext : WorkflowContext { - public WorkflowDeletedContext(Workflow workflow) : base(workflow) - { - } + public WorkflowDeletedContext(Workflow workflow) + : base(workflow) { } } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionContext.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionContext.cs index 33fe357f6e0..d279c0c65b7 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionContext.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionContext.cs @@ -6,8 +6,7 @@ namespace OrchardCore.Workflows.Models { public class WorkflowExecutionContext { - public WorkflowExecutionContext - ( + public WorkflowExecutionContext( WorkflowType workflowType, Workflow workflow, IDictionary input, diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionExpressionContext.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionExpressionContext.cs index 9314c689f64..1f466be1579 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionExpressionContext.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionExpressionContext.cs @@ -4,7 +4,8 @@ namespace OrchardCore.Workflows.Models { public class WorkflowExecutionExpressionContext : WorkflowExecutionHandlerContextBase { - public WorkflowExecutionExpressionContext(TemplateContext templateContext, WorkflowExecutionContext workflowExecutionContext) : base(workflowExecutionContext) + public WorkflowExecutionExpressionContext(TemplateContext templateContext, WorkflowExecutionContext workflowExecutionContext) + : base(workflowExecutionContext) { TemplateContext = templateContext; } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionScriptContext.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionScriptContext.cs index 4096dd7a787..a2aacbf1c8a 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionScriptContext.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExecutionScriptContext.cs @@ -5,9 +5,8 @@ namespace OrchardCore.Workflows.Models { public class WorkflowExecutionScriptContext : WorkflowExecutionHandlerContextBase { - public WorkflowExecutionScriptContext(WorkflowExecutionContext workflowContext) : base(workflowContext) - { - } + public WorkflowExecutionScriptContext(WorkflowExecutionContext workflowContext) + : base(workflowContext) { } public IList ScopedMethodProviders { get; init; } = []; } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExpression.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExpression.cs index c22fbc0c70e..4c9b3fb3720 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExpression.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowExpression.cs @@ -2,9 +2,7 @@ namespace OrchardCore.Workflows.Models { public class WorkflowExpression { - public WorkflowExpression() - { - } + public WorkflowExpression() { } public WorkflowExpression(string expression) { diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeCreatedContext.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeCreatedContext.cs index 7ec9fc4b3a9..21a31d6a427 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeCreatedContext.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeCreatedContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.Workflows.Models { public class WorkflowTypeCreatedContext : WorkflowTypeContext { - public WorkflowTypeCreatedContext(WorkflowType workflowType) : base(workflowType) - { - } + public WorkflowTypeCreatedContext(WorkflowType workflowType) + : base(workflowType) { } } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeDeletedContext.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeDeletedContext.cs index 5be80a63acd..904858bb189 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeDeletedContext.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeDeletedContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.Workflows.Models { public class WorkflowTypeDeletedContext : WorkflowTypeContext { - public WorkflowTypeDeletedContext(WorkflowType workflowType) : base(workflowType) - { - } + public WorkflowTypeDeletedContext(WorkflowType workflowType) + : base(workflowType) { } } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeUpdatedContext.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeUpdatedContext.cs index 5c60e08553c..3c28d320324 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeUpdatedContext.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowTypeUpdatedContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.Workflows.Models { public class WorkflowTypeUpdatedContext : WorkflowTypeContext { - public WorkflowTypeUpdatedContext(WorkflowType workflowType) : base(workflowType) - { - } + public WorkflowTypeUpdatedContext(WorkflowType workflowType) + : base(workflowType) { } } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowUpdatedContext.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowUpdatedContext.cs index cdc950b7548..c6623466866 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowUpdatedContext.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Models/WorkflowUpdatedContext.cs @@ -2,8 +2,7 @@ namespace OrchardCore.Workflows.Models { public class WorkflowUpdatedContext : WorkflowContext { - public WorkflowUpdatedContext(Workflow workflow) : base(workflow) - { - } + public WorkflowUpdatedContext(Workflow workflow) + : base(workflow) { } } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Options/ActivityRegistration.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Options/ActivityRegistration.cs index 0ccd9ae4edd..f151f03816a 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Options/ActivityRegistration.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Options/ActivityRegistration.cs @@ -11,7 +11,8 @@ public ActivityRegistration(Type activityType) DriverTypes = []; } - public ActivityRegistration(Type activityType, Type driverType) : this(activityType) + public ActivityRegistration(Type activityType, Type driverType) + : this(activityType) { DriverTypes.Add(driverType); } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IActivityDisplayManager.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IActivityDisplayManager.cs index 6ecbf9f3811..579197258d4 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IActivityDisplayManager.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IActivityDisplayManager.cs @@ -3,7 +3,5 @@ namespace OrchardCore.Workflows.Services { - public interface IActivityDisplayManager : IDisplayManager - { - } + public interface IActivityDisplayManager : IDisplayManager { } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IActivityLibrary.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IActivityLibrary.cs index 4685f57b4bc..3da0ad30756 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IActivityLibrary.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IActivityLibrary.cs @@ -37,12 +37,14 @@ public interface IActivityLibrary public static class ActivityLibraryExtensions { - public static T InstantiateActivity(this IActivityLibrary library, string name) where T : IActivity + public static T InstantiateActivity(this IActivityLibrary library, string name) + where T : IActivity { return (T)library.InstantiateActivity(name); } - public static T InstantiateActivity(this IActivityLibrary library, string name, JsonObject properties) where T : IActivity + public static T InstantiateActivity(this IActivityLibrary library, string name, JsonObject properties) + where T : IActivity { var activity = InstantiateActivity(library, name); @@ -54,7 +56,8 @@ public static T InstantiateActivity(this IActivityLibrary library, string nam return activity; } - public static T InstantiateActivity(this IActivityLibrary library, ActivityRecord record) where T : IActivity + public static T InstantiateActivity(this IActivityLibrary library, ActivityRecord record) + where T : IActivity { return InstantiateActivity(library, record.Name, record.Properties); } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowFaultHandler.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowFaultHandler.cs index d92c2441513..0856d6322d7 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowFaultHandler.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowFaultHandler.cs @@ -6,10 +6,6 @@ namespace OrchardCore.Workflows.Services { public interface IWorkflowFaultHandler { - Task OnWorkflowFaultAsync( - IWorkflowManager workflowManager, - WorkflowExecutionContext workflowContext, - ActivityContext activityContext, - Exception exception); + Task OnWorkflowFaultAsync(IWorkflowManager workflowManager, WorkflowExecutionContext workflowContext, ActivityContext activityContext, Exception exception); } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowManager.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowManager.cs index 03a3cccaf44..c89be0dd819 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowManager.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowManager.cs @@ -38,7 +38,13 @@ public interface IWorkflowManager /// /// If true, to be correlated a workflow instance only needs to be halted on an event activity of the related type, regardless the 'correlationId'. False by default. /// - Task> TriggerEventAsync(string name, IDictionary input = null, string correlationId = null, bool isExclusive = false, bool isAlwaysCorrelated = false); + Task> TriggerEventAsync( + string name, + IDictionary input = null, + string correlationId = null, + bool isExclusive = false, + bool isAlwaysCorrelated = false + ); /// /// Starts a new workflow using the specified workflow definition. @@ -48,7 +54,12 @@ public interface IWorkflowManager /// Optionally specify any inputs to be used by the workflow. /// Optionally specify an application-specific value to associate the workflow instance with. For example, a content item ID. /// Returns the created workflow context. Can be used for further inspection of the workflow state. - Task StartWorkflowAsync(WorkflowType workflowType, ActivityRecord startActivity = null, IDictionary input = null, string correlationId = null); + Task StartWorkflowAsync( + WorkflowType workflowType, + ActivityRecord startActivity = null, + IDictionary input = null, + string correlationId = null + ); /// /// Starts a new workflow using the specified workflow definition. @@ -72,7 +83,12 @@ public interface IWorkflowManager public static class WorkflowManagerExtensions { - public static Task> TriggerEventAsync(this IWorkflowManager workflowManager, string name, object input = null, string correlationId = null) + public static Task> TriggerEventAsync( + this IWorkflowManager workflowManager, + string name, + object input = null, + string correlationId = null + ) { return workflowManager.TriggerEventAsync(name, new RouteValueDictionary(input), correlationId); } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowStore.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowStore.cs index 0e372b15380..dc7cb058098 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowStore.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowStore.cs @@ -26,7 +26,6 @@ public interface IWorkflowStore public static class WorkflowStoreExtensions { [Obsolete("This method will be removed in a future version, use the method accepting a collection of long ids.", false)] - public static Task> GetAsync(this IWorkflowStore store, IEnumerable ids) => - store.GetAsync(ids.Select(id => Convert.ToInt64(id))); + public static Task> GetAsync(this IWorkflowStore store, IEnumerable ids) => store.GetAsync(ids.Select(id => Convert.ToInt64(id))); } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowTypeStore.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowTypeStore.cs index 55482deda17..242042b4127 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowTypeStore.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Services/IWorkflowTypeStore.cs @@ -20,7 +20,6 @@ public interface IWorkflowTypeStore public static class WorkflowTypeStoreExtensions { [Obsolete("This method will be removed in a future version, use the method accepting a collection of long ids.", false)] - public static Task> GetAsync(this IWorkflowTypeStore store, IEnumerable ids) => - store.GetAsync(ids.Select(id => Convert.ToInt64(id))); + public static Task> GetAsync(this IWorkflowTypeStore store, IEnumerable ids) => store.GetAsync(ids.Select(id => Convert.ToInt64(id))); } } diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/ViewModels/ActivityViewModel.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/ViewModels/ActivityViewModel.cs index 7ce3b8efe7f..cfae0ba5764 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/ViewModels/ActivityViewModel.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/ViewModels/ActivityViewModel.cs @@ -4,11 +4,10 @@ namespace OrchardCore.Workflows.ViewModels { - public class ActivityViewModel : ShapeViewModel where TActivity : IActivity + public class ActivityViewModel : ShapeViewModel + where TActivity : IActivity { - public ActivityViewModel() - { - } + public ActivityViewModel() { } public ActivityViewModel(TActivity activity) { diff --git a/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcArray.cs b/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcArray.cs index 0f0d6945880..1a3e01705aa 100644 --- a/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcArray.cs +++ b/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcArray.cs @@ -8,6 +8,7 @@ public XRpcArray() { Data = []; } + public IList Data { get; set; } public object this[int index] diff --git a/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcData.cs b/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcData.cs index 86bf6d86883..66b963388f7 100644 --- a/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcData.cs +++ b/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcData.cs @@ -17,7 +17,10 @@ protected virtual void SetValue(object value) _value = value; } - public virtual Type Type { get { return typeof(object); } } + public virtual Type Type + { + get { return typeof(object); } + } public static XRpcData For(T t) { @@ -47,7 +50,10 @@ protected override void SetValue(object value) base.SetValue(value); } - public override Type Type { get { return typeof(T); } } + public override Type Type + { + get { return typeof(T); } + } } public class XRpcFault diff --git a/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcStruct.cs b/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcStruct.cs index f2ac164b20d..7097cae5784 100644 --- a/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcStruct.cs +++ b/src/OrchardCore/OrchardCore.XmlRpc.Abstractions/Models/XRpcStruct.cs @@ -8,6 +8,7 @@ public XRpcStruct() { Members = new Dictionary(); } + public IDictionary Members { get; set; } public object this[string index] diff --git a/src/OrchardCore/OrchardCore/Caching/Signal.cs b/src/OrchardCore/OrchardCore/Caching/Signal.cs index 27a48acb808..672bf5132c9 100644 --- a/src/OrchardCore/OrchardCore/Caching/Signal.cs +++ b/src/OrchardCore/OrchardCore/Caching/Signal.cs @@ -20,14 +20,16 @@ public Signal() public IChangeToken GetToken(string key) { - return _changeTokens.GetOrAdd( - key, - _ => - { - var cancellationTokenSource = new CancellationTokenSource(); - var changeToken = new CancellationChangeToken(cancellationTokenSource.Token); - return new ChangeTokenInfo(changeToken, cancellationTokenSource); - }) + return _changeTokens + .GetOrAdd( + key, + _ => + { + var cancellationTokenSource = new CancellationTokenSource(); + var changeToken = new CancellationChangeToken(cancellationTokenSource.Token); + return new ChangeTokenInfo(changeToken, cancellationTokenSource); + } + ) .ChangeToken; } diff --git a/src/OrchardCore/OrchardCore/Extensions/ExtensionInfo.cs b/src/OrchardCore/OrchardCore/Extensions/ExtensionInfo.cs index 909994f4085..a6ec8994acd 100644 --- a/src/OrchardCore/OrchardCore/Extensions/ExtensionInfo.cs +++ b/src/OrchardCore/OrchardCore/Extensions/ExtensionInfo.cs @@ -16,10 +16,7 @@ public ExtensionInfo(string extensionId) Features = []; } - public ExtensionInfo( - string subPath, - IManifestInfo manifestInfo, - Func> features) + public ExtensionInfo(string subPath, IManifestInfo manifestInfo, Func> features) { Id = manifestInfo.ModuleInfo.Id; SubPath = subPath; diff --git a/src/OrchardCore/OrchardCore/Extensions/ExtensionManager.cs b/src/OrchardCore/OrchardCore/Extensions/ExtensionManager.cs index 16a14e1bc8a..3765b22ac75 100644 --- a/src/OrchardCore/OrchardCore/Extensions/ExtensionManager.cs +++ b/src/OrchardCore/OrchardCore/Extensions/ExtensionManager.cs @@ -44,7 +44,8 @@ public ExtensionManager( IEnumerable extensionPriorityStrategies, ITypeFeatureProvider typeFeatureProvider, IFeaturesProvider featuresProvider, - ILogger logger) + ILogger logger + ) { _applicationContext = applicationContext; _extensionDependencyStrategies = extensionDependencyStrategies as IExtensionDependencyStrategy[] ?? extensionDependencyStrategies.ToArray(); @@ -79,9 +80,7 @@ public IEnumerable GetFeatures(string[] featureIdsToLoad) { EnsureInitialized(); - var allDependencyIds = new HashSet(featureIdsToLoad - .SelectMany(featureId => GetFeatureDependencies(featureId)) - .Select(x => x.Id)); + var allDependencyIds = new HashSet(featureIdsToLoad.SelectMany(featureId => GetFeatureDependencies(featureId)).Select(x => x.Id)); foreach (var featureInfo in _featureInfos) { @@ -113,8 +112,7 @@ public async Task> LoadFeaturesAsync(string[] featureI var features = new HashSet(GetFeatures(featureIdsToLoad).Select(f => f.Id)); - var loadedFeatures = _features.Values - .Where(f => features.Contains(f.FeatureInfo.Id)); + var loadedFeatures = _features.Values.Where(f => features.Contains(f.FeatureInfo.Id)); return loadedFeatures; } @@ -123,39 +121,49 @@ public IEnumerable GetFeatureDependencies(string featureId) { EnsureInitialized(); - return _featureDependencies.GetOrAdd(featureId, (key) => new Lazy>(() => - { - if (!_features.TryGetValue(key, out var entry)) - { - return []; - } + return _featureDependencies + .GetOrAdd( + featureId, + (key) => + new Lazy>(() => + { + if (!_features.TryGetValue(key, out var entry)) + { + return []; + } - var feature = entry.FeatureInfo; + var feature = entry.FeatureInfo; - return GetFeatureDependencies(feature, _featureInfos); - })).Value; + return GetFeatureDependencies(feature, _featureInfos); + }) + ) + .Value; } public IEnumerable GetDependentFeatures(string featureId) { EnsureInitialized(); - return _dependentFeatures.GetOrAdd(featureId, (key) => new Lazy>(() => - { - if (!_features.TryGetValue(key, out var entry)) - { - return []; - } + return _dependentFeatures + .GetOrAdd( + featureId, + (key) => + new Lazy>(() => + { + if (!_features.TryGetValue(key, out var entry)) + { + return []; + } - var feature = entry.FeatureInfo; + var feature = entry.FeatureInfo; - return GetDependentFeatures(feature, _featureInfos); - })).Value; + return GetDependentFeatures(feature, _featureInfos); + }) + ) + .Value; } - private IEnumerable GetFeatureDependencies( - IFeatureInfo feature, - IFeatureInfo[] features) + private IEnumerable GetFeatureDependencies(IFeatureInfo feature, IFeatureInfo[] features) { var dependencyIds = new HashSet { feature.Id }; var stack = new Stack>(); @@ -185,9 +193,7 @@ private IEnumerable GetFeatureDependencies( } } - private IEnumerable GetDependentFeatures( - IFeatureInfo feature, - IFeatureInfo[] features) + private IEnumerable GetDependentFeatures(IFeatureInfo feature, IFeatureInfo[] features) { var dependencyIds = new HashSet { feature.Id }; var stack = new Stack>(); @@ -287,7 +293,6 @@ private async Task EnsureInitializedAsync() await _semaphore.WaitAsync(); try { - if (_isInitialized) { return; @@ -297,49 +302,47 @@ private async Task EnsureInitializedAsync() var loadedExtensions = new ConcurrentDictionary(); // Load all extensions in parallel - await modules.ForEachAsync((module) => - { - if (!module.ModuleInfo.Exists) + await modules.ForEachAsync( + (module) => { - return Task.CompletedTask; - } + if (!module.ModuleInfo.Exists) + { + return Task.CompletedTask; + } - var manifestInfo = new ManifestInfo(module.ModuleInfo); - var extensionInfo = new ExtensionInfo(module.SubPath, manifestInfo, (mi, ei) => - { - return _featuresProvider.GetFeatures(ei, mi); - }); + var manifestInfo = new ManifestInfo(module.ModuleInfo); + var extensionInfo = new ExtensionInfo( + module.SubPath, + manifestInfo, + (mi, ei) => + { + return _featuresProvider.GetFeatures(ei, mi); + } + ); - var entry = new ExtensionEntry - { - ExtensionInfo = extensionInfo, - Assembly = module.Assembly, - ExportedTypes = module.Assembly.ExportedTypes - }; + var entry = new ExtensionEntry + { + ExtensionInfo = extensionInfo, + Assembly = module.Assembly, + ExportedTypes = module.Assembly.ExportedTypes + }; - loadedExtensions.TryAdd(module.Name, entry); + loadedExtensions.TryAdd(module.Name, entry); - return Task.CompletedTask; - }); + return Task.CompletedTask; + } + ); var loadedFeatures = new Dictionary(); // Get all valid types from any extension - var allTypesByExtension = loadedExtensions.SelectMany(extension => - extension.Value.ExportedTypes.Where(IsComponentType) - .Select(type => new - { - ExtensionEntry = extension.Value, - Type = type - })).ToArray(); + var allTypesByExtension = loadedExtensions + .SelectMany(extension => extension.Value.ExportedTypes.Where(IsComponentType).Select(type => new { ExtensionEntry = extension.Value, Type = type })) + .ToArray(); var typesByFeature = allTypesByExtension - .GroupBy(typeByExtension => GetSourceFeatureNameForType( - typeByExtension.Type, - typeByExtension.ExtensionEntry.ExtensionInfo.Id)) - .ToDictionary( - group => group.Key, - group => group.Select(typesByExtension => typesByExtension.Type).ToArray()); + .GroupBy(typeByExtension => GetSourceFeatureNameForType(typeByExtension.Type, typeByExtension.ExtensionEntry.ExtensionInfo.Id)) + .ToDictionary(group => group.Key, group => group.Select(typesByExtension => typesByExtension.Type).ToArray()); foreach (var loadedExtension in loadedExtensions) { @@ -369,10 +372,7 @@ await modules.ForEachAsync((module) => _features = _featureInfos.ToDictionary(f => f.Id, f => loadedFeatures[f.Id]); // Extensions are also ordered according to the weight of their first features. - _extensionsInfos = _featureInfos - .Where(f => f.Id == f.Extension.Features.First().Id) - .Select(f => f.Extension) - .ToList(); + _extensionsInfos = _featureInfos.Where(f => f.Id == f.Extension.Features.First().Id).Select(f => f.Extension).ToList(); _extensions = _extensionsInfos.ToDictionary(e => e.Id, e => loadedExtensions[e.Id]); @@ -391,10 +391,7 @@ private static bool IsComponentType(Type type) private IFeatureInfo[] Order(IEnumerable featuresToOrder) { - return featuresToOrder - .OrderBy(x => x.Id) - .OrderByDependenciesAndPriorities(HasDependency, GetPriority) - .ToArray(); + return featuresToOrder.OrderBy(x => x.Id).OrderByDependenciesAndPriorities(HasDependency, GetPriority).ToArray(); } private bool HasDependency(IFeatureInfo f1, IFeatureInfo f2) diff --git a/src/OrchardCore/OrchardCore/Extensions/Features/FeatureHash.cs b/src/OrchardCore/OrchardCore/Extensions/Features/FeatureHash.cs index dcc81d88c2e..7b4d4e98cd7 100644 --- a/src/OrchardCore/OrchardCore/Extensions/Features/FeatureHash.cs +++ b/src/OrchardCore/OrchardCore/Extensions/Features/FeatureHash.cs @@ -28,9 +28,7 @@ public async Task GetFeatureHashAsync() // Calculate a hash of all enabled features' id var enabledFeatures = await _featureManager.GetEnabledFeaturesAsync(); - serial = enabledFeatures - .OrderBy(x => x.Id) - .Aggregate(0, (a, f) => a * 7 + f.Id.GetHashCode()); + serial = enabledFeatures.OrderBy(x => x.Id).Aggregate(0, (a, f) => a * 7 + f.Id.GetHashCode()); _memoryCache.Set(FeatureHashCacheKey, serial); diff --git a/src/OrchardCore/OrchardCore/Extensions/Features/FeatureInfo.cs b/src/OrchardCore/OrchardCore/Extensions/Features/FeatureInfo.cs index 078cf64cc67..1e3515bce18 100644 --- a/src/OrchardCore/OrchardCore/Extensions/Features/FeatureInfo.cs +++ b/src/OrchardCore/OrchardCore/Extensions/Features/FeatureInfo.cs @@ -19,7 +19,8 @@ public FeatureInfo( string[] dependencies, bool defaultTenantOnly, bool isAlwaysEnabled, - bool enabledByDependencyOnly) + bool enabledByDependencyOnly + ) { Id = id; Name = name; diff --git a/src/OrchardCore/OrchardCore/Extensions/Features/FeaturesProvider.cs b/src/OrchardCore/OrchardCore/Extensions/Features/FeaturesProvider.cs index 392644a5576..358381e45c4 100644 --- a/src/OrchardCore/OrchardCore/Extensions/Features/FeaturesProvider.cs +++ b/src/OrchardCore/OrchardCore/Extensions/Features/FeaturesProvider.cs @@ -32,8 +32,7 @@ public IEnumerable GetFeatures(IExtensionInfo extensionInfo, IMani { if (string.IsNullOrWhiteSpace(feature.Id)) { - throw new ArgumentException( - $"A {nameof(feature)} is missing a mandatory '{nameof(feature.Id)}' property in the Module '{extensionInfo.Id}'"); + throw new ArgumentException($"A {nameof(feature)} is missing a mandatory '{nameof(feature.Id)}' property in the Module '{extensionInfo.Id}'"); } // Attribute properties are transparently resolved by the instances themselves for convenience @@ -80,7 +79,8 @@ public IEnumerable GetFeatures(IExtensionInfo extensionInfo, IMani context.FeatureDependencyIds, context.DefaultTenantOnly, context.IsAlwaysEnabled, - context.EnabledByDependencyOnly); + context.EnabledByDependencyOnly + ); foreach (var builder in _featureBuilderEvents) { @@ -136,7 +136,8 @@ public IEnumerable GetFeatures(IExtensionInfo extensionInfo, IMani context.FeatureDependencyIds, context.DefaultTenantOnly, context.IsAlwaysEnabled, - context.EnabledByDependencyOnly); + context.EnabledByDependencyOnly + ); foreach (var builder in _featureBuilderEvents) { diff --git a/src/OrchardCore/OrchardCore/Localization/BclCalendars.cs b/src/OrchardCore/OrchardCore/Localization/BclCalendars.cs index 64f70d72d96..b3111018b3a 100644 --- a/src/OrchardCore/OrchardCore/Localization/BclCalendars.cs +++ b/src/OrchardCore/OrchardCore/Localization/BclCalendars.cs @@ -6,12 +6,12 @@ namespace OrchardCore.Localization { internal static class BclCalendars { - public readonly static Calendar Hebrew = new HebrewCalendar(); - public readonly static Calendar Hijri = new HijriCalendar(); - public readonly static Calendar Gregorian = new GregorianCalendar(); - public readonly static Calendar Julian = new JulianCalendar(); - public readonly static Calendar Persian = new PersianCalendar(); - public readonly static Calendar UmAlQura = new UmAlQuraCalendar(); + public static readonly Calendar Hebrew = new HebrewCalendar(); + public static readonly Calendar Hijri = new HijriCalendar(); + public static readonly Calendar Gregorian = new GregorianCalendar(); + public static readonly Calendar Julian = new JulianCalendar(); + public static readonly Calendar Persian = new PersianCalendar(); + public static readonly Calendar UmAlQura = new UmAlQuraCalendar(); public static CalendarSystem GetCalendarByName(CalendarName calendarName) => calendarName switch @@ -20,9 +20,7 @@ public static CalendarSystem GetCalendarByName(CalendarName calendarName) => CalendarName.Hijri => CalendarSystem.IslamicBcl, CalendarName.Gregorian => CalendarSystem.Iso, CalendarName.Julian => CalendarSystem.Julian, - CalendarName.Persian => CultureInfo.CurrentUICulture.Calendar.IsLeapYear(1) - ? CalendarSystem.PersianSimple - : CalendarSystem.PersianAstronomical, + CalendarName.Persian => CultureInfo.CurrentUICulture.Calendar.IsLeapYear(1) ? CalendarSystem.PersianSimple : CalendarSystem.PersianAstronomical, CalendarName.UmAlQura => CalendarSystem.UmAlQura, _ => throw new NotSupportedException($"The calendar is not supported."), }; @@ -85,9 +83,7 @@ public static CalendarSystem ConvertToCalendarSystem(Calendar calendar) } else if (calendarType == typeof(PersianCalendar)) { - return calendar.IsLeapYear(1) - ? CalendarSystem.PersianSimple - : CalendarSystem.PersianAstronomical; + return calendar.IsLeapYear(1) ? CalendarSystem.PersianSimple : CalendarSystem.PersianAstronomical; } else if (calendarType == typeof(UmAlQuraCalendar)) { diff --git a/src/OrchardCore/OrchardCore/Localization/DefaultCalendarSelector.cs b/src/OrchardCore/OrchardCore/Localization/DefaultCalendarSelector.cs index 7f94edd444b..07be58ef4ff 100644 --- a/src/OrchardCore/OrchardCore/Localization/DefaultCalendarSelector.cs +++ b/src/OrchardCore/OrchardCore/Localization/DefaultCalendarSelector.cs @@ -8,11 +8,9 @@ namespace OrchardCore.Localization /// public class DefaultCalendarSelector : ICalendarSelector { - private static readonly Task _calendarResult = Task.FromResult(new CalendarSelectorResult - { - Priority = 0, - CalendarName = () => Task.FromResult(BclCalendars.GetCalendarName(CultureInfo.CurrentUICulture.Calendar)) - }); + private static readonly Task _calendarResult = Task.FromResult( + new CalendarSelectorResult { Priority = 0, CalendarName = () => Task.FromResult(BclCalendars.GetCalendarName(CultureInfo.CurrentUICulture.Calendar)) } + ); /// public Task GetCalendarAsync() => _calendarResult; diff --git a/src/OrchardCore/OrchardCore/Localization/NullHtmlLocalizer.cs b/src/OrchardCore/OrchardCore/Localization/NullHtmlLocalizer.cs index cf776b65f18..26a83387217 100644 --- a/src/OrchardCore/OrchardCore/Localization/NullHtmlLocalizer.cs +++ b/src/OrchardCore/OrchardCore/Localization/NullHtmlLocalizer.cs @@ -50,16 +50,13 @@ public LocalizedHtmlString this[string name] } /// - public IEnumerable GetAllStrings(bool includeParentCultures) - => NullStringLocalizer.Instance.GetAllStrings(includeParentCultures); + public IEnumerable GetAllStrings(bool includeParentCultures) => NullStringLocalizer.Instance.GetAllStrings(includeParentCultures); /// - public LocalizedString GetString(string name) - => NullStringLocalizer.Instance.GetString(name); + public LocalizedString GetString(string name) => NullStringLocalizer.Instance.GetString(name); /// - public LocalizedString GetString(string name, params object[] arguments) - => NullStringLocalizer.Instance.GetString(name, arguments); + public LocalizedString GetString(string name, params object[] arguments) => NullStringLocalizer.Instance.GetString(name, arguments); /// [Obsolete("This method will be removed in the upcoming ASP.NET Core major release.")] diff --git a/src/OrchardCore/OrchardCore/Localization/NullStringLocalizer.cs b/src/OrchardCore/OrchardCore/Localization/NullStringLocalizer.cs index a55d65bbe96..e2b99b4ec27 100644 --- a/src/OrchardCore/OrchardCore/Localization/NullStringLocalizer.cs +++ b/src/OrchardCore/OrchardCore/Localization/NullStringLocalizer.cs @@ -44,8 +44,7 @@ public class NullStringLocalizer : IStringLocalizer } /// - public IEnumerable GetAllStrings(bool includeParentCultures) - => Enumerable.Empty(); + public IEnumerable GetAllStrings(bool includeParentCultures) => Enumerable.Empty(); /// public LocalizedString GetString(string name) => this[name]; diff --git a/src/OrchardCore/OrchardCore/Locking/LocalLock.cs b/src/OrchardCore/OrchardCore/Locking/LocalLock.cs index caa5046e9be..8eefc2a64da 100644 --- a/src/OrchardCore/OrchardCore/Locking/LocalLock.cs +++ b/src/OrchardCore/OrchardCore/Locking/LocalLock.cs @@ -49,8 +49,7 @@ public async Task AcquireLockAsync(string key, TimeSpan? expiration = n if (_logger.IsEnabled(LogLevel.Debug)) { - _logger.LogDebug("Timeout elapsed before acquiring the named lock '{LockName}' after the given timeout of '{Timeout}'.", - key, timeout.ToString()); + _logger.LogDebug("Timeout elapsed before acquiring the named lock '{LockName}' after the given timeout of '{Timeout}'.", key, timeout.ToString()); } return (null, false); diff --git a/src/OrchardCore/OrchardCore/Modules/Extensions/ApplicationBuilderExtensions.cs b/src/OrchardCore/OrchardCore/Modules/Extensions/ApplicationBuilderExtensions.cs index d20bf380169..ce4b453c993 100644 --- a/src/OrchardCore/OrchardCore/Modules/Extensions/ApplicationBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore/Modules/Extensions/ApplicationBuilderExtensions.cs @@ -17,13 +17,10 @@ public static IApplicationBuilder UseOrchardCore(this IApplicationBuilder app, A var env = app.ApplicationServices.GetRequiredService(); var appContext = app.ApplicationServices.GetRequiredService(); - env.ContentRootFileProvider = new CompositeFileProvider( - new ModuleEmbeddedFileProvider(appContext), - env.ContentRootFileProvider); + env.ContentRootFileProvider = new CompositeFileProvider(new ModuleEmbeddedFileProvider(appContext), env.ContentRootFileProvider); // Init also the web host 'ContentRootFileProvider'. - app.ApplicationServices.GetRequiredService() - .ContentRootFileProvider = env.ContentRootFileProvider; + app.ApplicationServices.GetRequiredService().ContentRootFileProvider = env.ContentRootFileProvider; app.UseMiddleware(); diff --git a/src/OrchardCore/OrchardCore/Modules/Extensions/OrchardCoreBuilderExtensions.cs b/src/OrchardCore/OrchardCore/Modules/Extensions/OrchardCoreBuilderExtensions.cs index 0ef4cb9cded..e5ce6eb45d2 100644 --- a/src/OrchardCore/OrchardCore/Modules/Extensions/OrchardCoreBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore/Modules/Extensions/OrchardCoreBuilderExtensions.cs @@ -97,26 +97,29 @@ public static OrchardCoreBuilder AddBackgroundService(this OrchardCoreBuilder bu { builder.ApplicationServices.AddHostedService(); - builder.ApplicationServices - .AddOptions() - .Configure((options, config) => config - .Bind("OrchardCore:OrchardCore_BackgroundService", options)); + builder + .ApplicationServices.AddOptions() + .Configure((options, config) => config.Bind("OrchardCore:OrchardCore_BackgroundService", options)); - builder.Configure(app => - { - app.Use((context, next) => + builder.Configure( + app => { - // In the background only the endpoints middlewares need to be executed. - if (context.Items.ContainsKey("IsBackground")) - { - // Shortcut the tenant pipeline. - return Task.CompletedTask; - } - - return next(context); - }); - }, - order: int.MinValue); + app.Use( + (context, next) => + { + // In the background only the endpoints middlewares need to be executed. + if (context.Items.ContainsKey("IsBackground")) + { + // Shortcut the tenant pipeline. + return Task.CompletedTask; + } + + return next(context); + } + ); + }, + order: int.MinValue + ); return builder; } diff --git a/src/OrchardCore/OrchardCore/Modules/Extensions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore/Modules/Extensions/ServiceCollectionExtensions.cs index 27d408d61ed..1229d03ecd4 100644 --- a/src/OrchardCore/OrchardCore/Modules/Extensions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore/Modules/Extensions/ServiceCollectionExtensions.cs @@ -45,9 +45,7 @@ public static class ServiceCollectionExtensions /// private static readonly Type[] _routingTypesToIsolate = new ServiceCollection() .AddRouting() - .Where(sd => - sd.Lifetime == ServiceLifetime.Singleton || - sd.ServiceType == typeof(IConfigureOptions)) + .Where(sd => sd.Lifetime == ServiceLifetime.Singleton || sd.ServiceType == typeof(IConfigureOptions)) .Select(sd => sd.GetImplementationType()) .ToArray(); @@ -58,10 +56,7 @@ public static class ServiceCollectionExtensions .AddHttpClient() .Where(sd => sd.Lifetime == ServiceLifetime.Singleton) .Select(sd => sd.GetImplementationType()) - .Except(new ServiceCollection() - .AddLogging() - .Where(sd => sd.Lifetime == ServiceLifetime.Singleton) - .Select(sd => sd.GetImplementationType())) + .Except(new ServiceCollection().AddLogging().Where(sd => sd.Lifetime == ServiceLifetime.Singleton).Select(sd => sd.GetImplementationType())) .ToArray(); /// @@ -82,9 +77,7 @@ public static OrchardCoreBuilder AddOrchardCore(this IServiceCollection services // If an instance of OrchardCoreBuilder exists reuse it, // so we can call AddOrchardCore several times. - var builder = services - .LastOrDefault(d => d.ServiceType == typeof(OrchardCoreBuilder))? - .ImplementationInstance as OrchardCoreBuilder; + var builder = services.LastOrDefault(d => d.ServiceType == typeof(OrchardCoreBuilder))?.ImplementationInstance as OrchardCoreBuilder; if (builder == null) { @@ -155,16 +148,18 @@ private static void AddDefaultServices(OrchardCoreBuilder builder) services.AddScoped(); services.AddSingleton(); - builder.ConfigureServices((services, serviceProvider) => - { - services.AddSingleton(); - services.AddSingleton(sp => sp.GetRequiredService()); - services.AddSingleton(sp => sp.GetRequiredService()); + builder.ConfigureServices( + (services, serviceProvider) => + { + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(sp => sp.GetRequiredService()); - var configuration = serviceProvider.GetService(); + var configuration = serviceProvider.GetService(); - services.Configure(configuration.GetSection("OrchardCore_Localization_CultureOptions")); - }); + services.Configure(configuration.GetSection("OrchardCore_Localization_CultureOptions")); + } + ); services.AddSingleton(); } @@ -178,16 +173,10 @@ private static void AddShellServices(OrchardCoreBuilder builder) services.AddAllFeaturesDescriptor(); // Registers the application primary feature. - services.AddTransient(sp => new ShellFeature - ( - sp.GetRequiredService().ApplicationName, alwaysEnabled: true) - ); + services.AddTransient(sp => new ShellFeature(sp.GetRequiredService().ApplicationName, alwaysEnabled: true)); // Registers the application default feature. - services.AddTransient(sp => new ShellFeature - ( - Application.DefaultFeatureId, alwaysEnabled: true) - ); + services.AddTransient(sp => new ShellFeature(Application.DefaultFeatureId, alwaysEnabled: true)); builder.ConfigureServices(shellServices => { @@ -228,11 +217,7 @@ private static void AddStaticFiles(OrchardCoreBuilder builder) IModuleStaticFileProvider fileProvider; if (env.IsDevelopment()) { - var fileProviders = new List - { - new ModuleProjectStaticFileProvider(appContext), - new ModuleEmbeddedStaticFileProvider(appContext) - }; + var fileProviders = new List { new ModuleProjectStaticFileProvider(appContext), new ModuleEmbeddedStaticFileProvider(appContext) }; fileProvider = new ModuleCompositeStaticFileProvider(fileProviders); } else @@ -248,34 +233,39 @@ private static void AddStaticFiles(OrchardCoreBuilder builder) }); }); - builder.Configure((app, routes, serviceProvider) => - { - var fileProvider = serviceProvider.GetRequiredService(); - - var shellConfiguration = serviceProvider.GetRequiredService(); - // Cache static files for a year as they are coming from embedded resources and should not vary. - var cacheControl = shellConfiguration.GetValue("StaticFileOptions:CacheControl", $"public, max-age={TimeSpan.FromDays(30).TotalSeconds}, s-maxage={TimeSpan.FromDays(365.25).TotalSeconds}"); - - // Use the current options values but without mutating the resolved instance. - var options = serviceProvider.GetRequiredService>().Value; - options = new StaticFileOptions + builder.Configure( + (app, routes, serviceProvider) => { - RequestPath = string.Empty, - FileProvider = fileProvider, - RedirectToAppendTrailingSlash = options.RedirectToAppendTrailingSlash, - ContentTypeProvider = options.ContentTypeProvider, - DefaultContentType = options.DefaultContentType, - ServeUnknownFileTypes = options.ServeUnknownFileTypes, - HttpsCompression = options.HttpsCompression, - - OnPrepareResponse = ctx => + var fileProvider = serviceProvider.GetRequiredService(); + + var shellConfiguration = serviceProvider.GetRequiredService(); + // Cache static files for a year as they are coming from embedded resources and should not vary. + var cacheControl = shellConfiguration.GetValue( + "StaticFileOptions:CacheControl", + $"public, max-age={TimeSpan.FromDays(30).TotalSeconds}, s-maxage={TimeSpan.FromDays(365.25).TotalSeconds}" + ); + + // Use the current options values but without mutating the resolved instance. + var options = serviceProvider.GetRequiredService>().Value; + options = new StaticFileOptions { - ctx.Context.Response.Headers[HeaderNames.CacheControl] = cacheControl; - }, - }; + RequestPath = string.Empty, + FileProvider = fileProvider, + RedirectToAppendTrailingSlash = options.RedirectToAppendTrailingSlash, + ContentTypeProvider = options.ContentTypeProvider, + DefaultContentType = options.DefaultContentType, + ServeUnknownFileTypes = options.ServeUnknownFileTypes, + HttpsCompression = options.HttpsCompression, + + OnPrepareResponse = ctx => + { + ctx.Context.Response.Headers[HeaderNames.CacheControl] = cacheControl; + }, + }; - app.UseStaticFiles(options); - }); + app.UseStaticFiles(options); + } + ); } /// @@ -285,25 +275,23 @@ private static void AddMetrics(OrchardCoreBuilder builder) { // 'AddMetrics()' is called by the host. - builder.ConfigureServices(collection => - { - // The 'DefaultMeterFactory' caches 'Meters' in a non thread safe dictionary. - // So, we need to register an isolated 'IMeterFactory' singleton per tenant. - var descriptorsToRemove = collection - .Where(sd => - sd is ClonedSingletonDescriptor && - _metricsTypesToIsolate.Contains(sd.GetImplementationType())) - .ToArray(); - // Isolate each tenant from the host. - - foreach (var descriptor in descriptorsToRemove) + builder.ConfigureServices( + collection => { - collection.Remove(descriptor); - } + // The 'DefaultMeterFactory' caches 'Meters' in a non thread safe dictionary. + // So, we need to register an isolated 'IMeterFactory' singleton per tenant. + var descriptorsToRemove = collection.Where(sd => sd is ClonedSingletonDescriptor && _metricsTypesToIsolate.Contains(sd.GetImplementationType())).ToArray(); + // Isolate each tenant from the host. + + foreach (var descriptor in descriptorsToRemove) + { + collection.Remove(descriptor); + } - collection.AddMetrics(); - }, - order: int.MinValue + 100); + collection.AddMetrics(); + }, + order: int.MinValue + 100 + ); } /// @@ -313,28 +301,30 @@ private static void AddRouting(OrchardCoreBuilder builder) { // 'AddRouting()' is called by the host. - builder.ConfigureServices(collection => - { - // The routing system is not tenant aware and uses a global list of endpoint data sources which is - // setup by the default configuration of 'RouteOptions' and mutated on each call of 'UseEndPoints()'. - // So, we need isolated routing singletons (and a default configuration) per tenant. - - var descriptorsToRemove = collection - .Where(sd => - (sd is ClonedSingletonDescriptor || - sd.ServiceType == typeof(IConfigureOptions)) && - _routingTypesToIsolate.Contains(sd.GetImplementationType())) - .ToArray(); - - // Isolate each tenant from the host. - foreach (var descriptor in descriptorsToRemove) + builder.ConfigureServices( + collection => { - collection.Remove(descriptor); - } + // The routing system is not tenant aware and uses a global list of endpoint data sources which is + // setup by the default configuration of 'RouteOptions' and mutated on each call of 'UseEndPoints()'. + // So, we need isolated routing singletons (and a default configuration) per tenant. + + var descriptorsToRemove = collection + .Where(sd => + (sd is ClonedSingletonDescriptor || sd.ServiceType == typeof(IConfigureOptions)) + && _routingTypesToIsolate.Contains(sd.GetImplementationType()) + ) + .ToArray(); + + // Isolate each tenant from the host. + foreach (var descriptor in descriptorsToRemove) + { + collection.Remove(descriptor); + } - collection.AddRouting(); - }, - order: int.MinValue + 100); + collection.AddRouting(); + }, + order: int.MinValue + 100 + ); } /// @@ -342,38 +332,36 @@ private static void AddRouting(OrchardCoreBuilder builder) /// private static void IsolateHttpClient(OrchardCoreBuilder builder) { - builder.ConfigureServices(collection => - { - // Each tenant needs isolated http client singletons and configurations, so that - // typed clients/handlers are activated/resolved from the right tenant container. - - // Retrieve current options configurations. - var configurationDescriptorsToRemove = collection - .Where(sd => - sd.ServiceType.IsGenericType && - sd.ServiceType.GenericTypeArguments.Contains(typeof(HttpClientFactoryOptions))) - .ToArray(); - - // Retrieve all descriptors to remove. - var descriptorsToRemove = collection - .Where(sd => - sd is ClonedSingletonDescriptor && - _httpClientTypesToIsolate.Contains(sd.GetImplementationType())) - .Concat(configurationDescriptorsToRemove) - .ToArray(); - - // Isolate each tenant from the host. - foreach (var descriptor in descriptorsToRemove) + builder.ConfigureServices( + collection => { - collection.Remove(descriptor); - } + // Each tenant needs isolated http client singletons and configurations, so that + // typed clients/handlers are activated/resolved from the right tenant container. + + // Retrieve current options configurations. + var configurationDescriptorsToRemove = collection + .Where(sd => sd.ServiceType.IsGenericType && sd.ServiceType.GenericTypeArguments.Contains(typeof(HttpClientFactoryOptions))) + .ToArray(); + + // Retrieve all descriptors to remove. + var descriptorsToRemove = collection + .Where(sd => sd is ClonedSingletonDescriptor && _httpClientTypesToIsolate.Contains(sd.GetImplementationType())) + .Concat(configurationDescriptorsToRemove) + .ToArray(); + + // Isolate each tenant from the host. + foreach (var descriptor in descriptorsToRemove) + { + collection.Remove(descriptor); + } - // Make the http client factory 'IDisposable'. - collection.AddSingleton(); - collection.AddSingleton(sp => sp.GetRequiredService()); - collection.AddSingleton(sp => sp.GetRequiredService()); - }, - order: int.MinValue + 100); + // Make the http client factory 'IDisposable'. + collection.AddSingleton(); + collection.AddSingleton(sp => sp.GetRequiredService()); + collection.AddSingleton(sp => sp.GetRequiredService()); + }, + order: int.MinValue + 100 + ); } /// @@ -383,26 +371,28 @@ private static void AddEndpointsApiExplorer(OrchardCoreBuilder builder) { // 'AddEndpointsApiExplorer()' is called by the host. - builder.ConfigureServices(collection => - { - // Remove the related host singletons as they are not tenant aware. - var descriptorsToRemove = collection - .Where(sd => - sd is ClonedSingletonDescriptor && - (sd.ServiceType == typeof(IActionDescriptorCollectionProvider) || - sd.ServiceType == typeof(IApiDescriptionGroupCollectionProvider))) - .ToArray(); - - // Isolate each tenant from the host. - foreach (var descriptor in descriptorsToRemove) + builder.ConfigureServices( + collection => { - collection.Remove(descriptor); - } + // Remove the related host singletons as they are not tenant aware. + var descriptorsToRemove = collection + .Where(sd => + sd is ClonedSingletonDescriptor + && (sd.ServiceType == typeof(IActionDescriptorCollectionProvider) || sd.ServiceType == typeof(IApiDescriptionGroupCollectionProvider)) + ) + .ToArray(); + + // Isolate each tenant from the host. + foreach (var descriptor in descriptorsToRemove) + { + collection.Remove(descriptor); + } - // Configure ApiExplorer at the tenant level. - collection.AddEndpointsApiExplorer(); - }, - order: int.MinValue + 100); + // Configure ApiExplorer at the tenant level. + collection.AddEndpointsApiExplorer(); + }, + order: int.MinValue + 100 + ); } /// @@ -412,14 +402,14 @@ private static void AddAntiForgery(OrchardCoreBuilder builder) { builder.ApplicationServices.AddAntiforgery(); - builder.ConfigureServices((services, serviceProvider) => - { - var settings = serviceProvider.GetRequiredService(); - var cookieName = "__orchantiforgery_" + settings.VersionId; + builder.ConfigureServices( + (services, serviceProvider) => + { + var settings = serviceProvider.GetRequiredService(); + var cookieName = "__orchantiforgery_" + settings.VersionId; - // Re-register the antiforgery services to be tenant-aware. - var collection = new ServiceCollection() - .AddAntiforgery(options => + // Re-register the antiforgery services to be tenant-aware. + var collection = new ServiceCollection().AddAntiforgery(options => { options.Cookie.Name = cookieName; @@ -428,8 +418,9 @@ private static void AddAntiForgery(OrchardCoreBuilder builder) // tenant prefix but may also start by a path related e.g to a virtual folder. }); - services.Add(collection); - }); + services.Add(collection); + } + ); } /// @@ -437,19 +428,20 @@ private static void AddAntiForgery(OrchardCoreBuilder builder) /// private static void AddSameSiteCookieBackwardsCompatibility(OrchardCoreBuilder builder) { - builder.ConfigureServices(services => - { - services.Configure(options => + builder + .ConfigureServices(services => + { + services.Configure(options => + { + options.MinimumSameSitePolicy = SameSiteMode.Unspecified; + options.OnAppendCookie = cookieContext => CheckSameSiteBackwardsCompatibility(cookieContext.Context, cookieContext.CookieOptions); + options.OnDeleteCookie = cookieContext => CheckSameSiteBackwardsCompatibility(cookieContext.Context, cookieContext.CookieOptions); + }); + }) + .Configure(app => { - options.MinimumSameSitePolicy = SameSiteMode.Unspecified; - options.OnAppendCookie = cookieContext => CheckSameSiteBackwardsCompatibility(cookieContext.Context, cookieContext.CookieOptions); - options.OnDeleteCookie = cookieContext => CheckSameSiteBackwardsCompatibility(cookieContext.Context, cookieContext.CookieOptions); + app.UseCookiePolicy(); }); - }) - .Configure(app => - { - app.UseCookiePolicy(); - }); } private static void CheckSameSiteBackwardsCompatibility(HttpContext httpContext, CookieOptions options) @@ -479,8 +471,7 @@ private static void CheckSameSiteBackwardsCompatibility(HttpContext httpContext, // This does not include: // - Chrome on Mac OS X. // Because they do not use the Mac OS networking stack. - if (userAgent.Contains("Macintosh; Intel Mac OS X 10_14") && - userAgent.Contains("Version/") && userAgent.Contains("Safari")) + if (userAgent.Contains("Macintosh; Intel Mac OS X 10_14") && userAgent.Contains("Version/") && userAgent.Contains("Safari")) { options.SameSite = SameSiteMode.Unspecified; return; @@ -504,20 +495,24 @@ private static void AddAuthentication(OrchardCoreBuilder builder) { builder.ApplicationServices.AddAuthentication(); - builder.ConfigureServices(services => - { - services.AddAuthentication(); - - // IAuthenticationSchemeProvider is already registered at the host level. - // We need to register it again so it is taken into account at the tenant level - // because it holds a reference to an underlying dictionary, responsible of storing - // the registered schemes which need to be distinct for each tenant. - services.AddSingleton(); - }) - .Configure(app => - { - app.UseAuthentication(); - }, order: -150); + builder + .ConfigureServices(services => + { + services.AddAuthentication(); + + // IAuthenticationSchemeProvider is already registered at the host level. + // We need to register it again so it is taken into account at the tenant level + // because it holds a reference to an underlying dictionary, responsible of storing + // the registered schemes which need to be distinct for each tenant. + services.AddSingleton(); + }) + .Configure( + app => + { + app.UseAuthentication(); + }, + order: -150 + ); } /// @@ -525,34 +520,35 @@ private static void AddAuthentication(OrchardCoreBuilder builder) /// private static void AddDataProtection(OrchardCoreBuilder builder) { - builder.ConfigureServices((services, serviceProvider) => - { - var settings = serviceProvider.GetRequiredService(); - var options = serviceProvider.GetRequiredService>(); - - // The 'FileSystemXmlRepository' will create the directory, but only if it is not overridden. - var directory = new DirectoryInfo(Path.Combine( - options.Value.ShellsApplicationDataPath, - options.Value.ShellsContainerName, - settings.Name, "DataProtection-Keys")); - - // Re-register the data protection services to be tenant-aware so that modules that internally - // rely on IDataProtector/IDataProtectionProvider automatically get an isolated instance that - // manages its own key ring and doesn't allow decrypting payloads encrypted by another tenant. - // By default, the key ring is stored in the tenant directory of the configured App_Data path. - var collection = new ServiceCollection() - .AddDataProtection() - .PersistKeysToFileSystem(directory) - .SetApplicationName(settings.Name) - .AddKeyManagementOptions(o => o.XmlEncryptor ??= new NullXmlEncryptor()) - .Services; - - // Remove any previously registered options setups. - services.RemoveAll>(); - services.RemoveAll>(); - - services.Add(collection); - }); + builder.ConfigureServices( + (services, serviceProvider) => + { + var settings = serviceProvider.GetRequiredService(); + var options = serviceProvider.GetRequiredService>(); + + // The 'FileSystemXmlRepository' will create the directory, but only if it is not overridden. + var directory = new DirectoryInfo( + Path.Combine(options.Value.ShellsApplicationDataPath, options.Value.ShellsContainerName, settings.Name, "DataProtection-Keys") + ); + + // Re-register the data protection services to be tenant-aware so that modules that internally + // rely on IDataProtector/IDataProtectionProvider automatically get an isolated instance that + // manages its own key ring and doesn't allow decrypting payloads encrypted by another tenant. + // By default, the key ring is stored in the tenant directory of the configured App_Data path. + var collection = new ServiceCollection() + .AddDataProtection() + .PersistKeysToFileSystem(directory) + .SetApplicationName(settings.Name) + .AddKeyManagementOptions(o => o.XmlEncryptor ??= new NullXmlEncryptor()) + .Services; + + // Remove any previously registered options setups. + services.RemoveAll>(); + services.RemoveAll>(); + + services.Add(collection); + } + ); } } } diff --git a/src/OrchardCore/OrchardCore/Modules/Extensions/ShellPipelineExtensions.cs b/src/OrchardCore/OrchardCore/Modules/Extensions/ShellPipelineExtensions.cs index 234bb5dc7ec..0f2e2293800 100644 --- a/src/OrchardCore/OrchardCore/Modules/Extensions/ShellPipelineExtensions.cs +++ b/src/OrchardCore/OrchardCore/Modules/Extensions/ShellPipelineExtensions.cs @@ -62,10 +62,7 @@ private static async ValueTask BuildPipelineInternalAsync(this S await ConfigurePipelineAsync(builder); - var shellPipeline = new ShellRequestPipeline - { - Next = builder.Build() - }; + var shellPipeline = new ShellRequestPipeline { Next = builder.Build() }; return shellPipeline; } @@ -83,8 +80,7 @@ private static async ValueTask ConfigurePipelineAsync(IApplicationBuilder builde builder.UseRouting(); // Try to retrieve the current 'IEndpointRouteBuilder'. - if (!builder.Properties.TryGetValue(EndpointRouteBuilder, out var obj) || - obj is not IEndpointRouteBuilder routes) + if (!builder.Properties.TryGetValue(EndpointRouteBuilder, out var obj) || obj is not IEndpointRouteBuilder routes) { throw new InvalidOperationException("Failed to retrieve the current endpoint route builder."); } diff --git a/src/OrchardCore/OrchardCore/Modules/ModularBackgroundService.cs b/src/OrchardCore/OrchardCore/Modules/ModularBackgroundService.cs index 62714126e1f..16d7c05aa3e 100644 --- a/src/OrchardCore/OrchardCore/Modules/ModularBackgroundService.cs +++ b/src/OrchardCore/OrchardCore/Modules/ModularBackgroundService.cs @@ -38,7 +38,8 @@ public ModularBackgroundService( IHttpContextAccessor httpContextAccessor, IOptions options, ILogger logger, - IClock clock) + IClock clock + ) { _shellHost = shellHost; _httpContextAccessor = httpContextAccessor; @@ -102,243 +103,243 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) private async Task RunAsync(IEnumerable<(string Tenant, long UtcTicks)> runningShells, CancellationToken stoppingToken) { - await GetShellsToRun(runningShells).ForEachAsync(async tenant => - { - // Check if the shell is still registered and running. - if (!_shellHost.TryGetShellContext(tenant, out var shell) || !shell.Settings.IsRunning()) - { - return; - } - - // Create a new 'HttpContext' to be used in the background. - _httpContextAccessor.HttpContext = shell.CreateHttpContext(); - - var schedulers = GetSchedulersToRun(tenant); - foreach (var scheduler in schedulers) + await GetShellsToRun(runningShells) + .ForEachAsync(async tenant => { - if (stoppingToken.IsCancellationRequested) + // Check if the shell is still registered and running. + if (!_shellHost.TryGetShellContext(tenant, out var shell) || !shell.Settings.IsRunning()) { - break; - } - - // Try to create a shell scope on this shell context. - var (shellScope, success) = await _shellHost.TryGetScopeAsync(shell.Settings.Name); - if (!success) - { - break; + return; } - // Check if the shell has no pipeline and should not be warmed up. - if (!_options.ShellWarmup && !shellScope.ShellContext.HasPipeline()) - { - await shellScope.TerminateShellAsync(); - break; - } + // Create a new 'HttpContext' to be used in the background. + _httpContextAccessor.HttpContext = shell.CreateHttpContext(); - var locked = false; - ILocker locker = null; - try + var schedulers = GetSchedulersToRun(tenant); + foreach (var scheduler in schedulers) { - // Try to acquire a lock before using the scope, so that a next process gets the last committed data. - var distributedLock = shellScope.ShellContext.ServiceProvider.GetRequiredService(); - (locker, locked) = await distributedLock.TryAcquireBackgroundTaskLockAsync(scheduler.Settings); - if (!locked) + if (stoppingToken.IsCancellationRequested) { - await shellScope.TerminateShellAsync(); - _logger.LogInformation("Timeout to acquire a lock on background task '{TaskName}' on tenant '{TenantName}'.", scheduler.Name, tenant); break; } - } - catch (Exception ex) when (!ex.IsFatal()) - { - await shellScope.TerminateShellAsync(); - _logger.LogError(ex, "Failed to acquire a lock on background task '{TaskName}' on tenant '{TenantName}'.", scheduler.Name, tenant); - break; - } - - await using var acquiredLock = locker; - await shellScope.UsingAsync(async scope => - { - var taskName = scheduler.Name; - - var task = scope.ServiceProvider.GetServices().GetTaskByName(taskName); - if (task is null) + // Try to create a shell scope on this shell context. + var (shellScope, success) = await _shellHost.TryGetScopeAsync(shell.Settings.Name); + if (!success) { - return; + break; } - var siteService = scope.ServiceProvider.GetService(); - if (siteService is not null) + // Check if the shell has no pipeline and should not be warmed up. + if (!_options.ShellWarmup && !shellScope.ShellContext.HasPipeline()) { - try - { - // Use the base url, if defined, to override the 'Scheme', 'Host' and 'PathBase'. - _httpContextAccessor.HttpContext.SetBaseUrl((await siteService.GetSiteSettingsAsync()).BaseUrl); - } - catch (Exception ex) when (!ex.IsFatal()) - { - _logger.LogError(ex, "Error while getting the base url from the site settings of the tenant '{TenantName}'.", tenant); - } + await shellScope.TerminateShellAsync(); + break; } + var locked = false; + ILocker locker = null; try { - if (scheduler.Settings.UsePipeline) + // Try to acquire a lock before using the scope, so that a next process gets the last committed data. + var distributedLock = shellScope.ShellContext.ServiceProvider.GetRequiredService(); + (locker, locked) = await distributedLock.TryAcquireBackgroundTaskLockAsync(scheduler.Settings); + if (!locked) { - if (!scope.ShellContext.HasPipeline()) - { - // Build the shell pipeline to configure endpoint data sources. - await scope.ShellContext.BuildPipelineAsync(); - } - - // Run the pipeline to make the 'HttpContext' aware of endpoints. - await scope.ShellContext.Pipeline.Invoke(_httpContextAccessor.HttpContext); + await shellScope.TerminateShellAsync(); + _logger.LogInformation("Timeout to acquire a lock on background task '{TaskName}' on tenant '{TenantName}'.", scheduler.Name, tenant); + break; } } catch (Exception ex) when (!ex.IsFatal()) { - _logger.LogError(ex, "Error while running in the background the pipeline of tenant '{TenantName}'.", tenant); + await shellScope.TerminateShellAsync(); + _logger.LogError(ex, "Failed to acquire a lock on background task '{TaskName}' on tenant '{TenantName}'.", scheduler.Name, tenant); + break; } - var context = new BackgroundTaskEventContext(taskName, scope); - var handlers = scope.ServiceProvider.GetServices(); - - await handlers.InvokeAsync((handler, context, token) => handler.ExecutingAsync(context, token), context, stoppingToken, _logger); + await using var acquiredLock = locker; - try + await shellScope.UsingAsync(async scope => { - _logger.LogInformation("Start processing background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); + var taskName = scheduler.Name; - scheduler.Run(); - await task.DoWorkAsync(scope.ServiceProvider, stoppingToken); + var task = scope.ServiceProvider.GetServices().GetTaskByName(taskName); + if (task is null) + { + return; + } - _logger.LogInformation("Finished processing background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); - } - catch (Exception ex) when (!ex.IsFatal()) - { - _logger.LogError(ex, "Error while processing background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); - context.Exception = ex; + var siteService = scope.ServiceProvider.GetService(); + if (siteService is not null) + { + try + { + // Use the base url, if defined, to override the 'Scheme', 'Host' and 'PathBase'. + _httpContextAccessor.HttpContext.SetBaseUrl((await siteService.GetSiteSettingsAsync()).BaseUrl); + } + catch (Exception ex) when (!ex.IsFatal()) + { + _logger.LogError(ex, "Error while getting the base url from the site settings of the tenant '{TenantName}'.", tenant); + } + } - await scope.HandleExceptionAsync(ex); - } + try + { + if (scheduler.Settings.UsePipeline) + { + if (!scope.ShellContext.HasPipeline()) + { + // Build the shell pipeline to configure endpoint data sources. + await scope.ShellContext.BuildPipelineAsync(); + } + + // Run the pipeline to make the 'HttpContext' aware of endpoints. + await scope.ShellContext.Pipeline.Invoke(_httpContextAccessor.HttpContext); + } + } + catch (Exception ex) when (!ex.IsFatal()) + { + _logger.LogError(ex, "Error while running in the background the pipeline of tenant '{TenantName}'.", tenant); + } - await handlers.InvokeAsync((handler, context, token) => handler.ExecutedAsync(context, token), context, stoppingToken, _logger); - }); - } + var context = new BackgroundTaskEventContext(taskName, scope); + var handlers = scope.ServiceProvider.GetServices(); - // Clear the 'HttpContext' for this async flow. - _httpContextAccessor.HttpContext = null; - }); - } + await handlers.InvokeAsync((handler, context, token) => handler.ExecutingAsync(context, token), context, stoppingToken, _logger); - private async Task UpdateAsync( - (string Tenant, long UtcTicks)[] previousShells, - (string Tenant, long UtcTicks)[] runningShells, CancellationToken stoppingToken) - { - var referenceTime = DateTime.UtcNow; + try + { + _logger.LogInformation("Start processing background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); - await GetShellsToUpdate(previousShells, runningShells).ForEachAsync(async tenant => - { - if (stoppingToken.IsCancellationRequested) - { - return; - } + scheduler.Run(); + await task.DoWorkAsync(scope.ServiceProvider, stoppingToken); - // Check if the shell is still registered and running. - if (!_shellHost.TryGetShellContext(tenant, out var shell) || !shell.Settings.IsRunning()) - { - return; - } + _logger.LogInformation("Finished processing background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); + } + catch (Exception ex) when (!ex.IsFatal()) + { + _logger.LogError(ex, "Error while processing background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); + context.Exception = ex; - // Try to create a shell scope on this shell context. - var (shellScope, success) = await _shellHost.TryGetScopeAsync(shell.Settings.Name); - if (!success) - { - return; - } + await scope.HandleExceptionAsync(ex); + } - // Check if the shell has no pipeline and should not be warmed up. - if (!_options.ShellWarmup && !shellScope.ShellContext.HasPipeline()) - { - await shellScope.TerminateShellAsync(); - return; - } + await handlers.InvokeAsync((handler, context, token) => handler.ExecutedAsync(context, token), context, stoppingToken, _logger); + }); + } - // Create a new 'HttpContext' to be used in the background. - _httpContextAccessor.HttpContext = shell.CreateHttpContext(); + // Clear the 'HttpContext' for this async flow. + _httpContextAccessor.HttpContext = null; + }); + } - await shellScope.UsingAsync(async scope => - { - var tasks = scope.ServiceProvider.GetServices(); + private async Task UpdateAsync((string Tenant, long UtcTicks)[] previousShells, (string Tenant, long UtcTicks)[] runningShells, CancellationToken stoppingToken) + { + var referenceTime = DateTime.UtcNow; - CleanSchedulers(tenant, tasks); + await GetShellsToUpdate(previousShells, runningShells) + .ForEachAsync(async tenant => + { + if (stoppingToken.IsCancellationRequested) + { + return; + } - if (!tasks.Any()) + // Check if the shell is still registered and running. + if (!_shellHost.TryGetShellContext(tenant, out var shell) || !shell.Settings.IsRunning()) { return; } - var settingsProvider = scope.ServiceProvider.GetService(); - _changeTokens[tenant] = settingsProvider?.ChangeToken ?? NullChangeToken.Singleton; + // Try to create a shell scope on this shell context. + var (shellScope, success) = await _shellHost.TryGetScopeAsync(shell.Settings.Name); + if (!success) + { + return; + } - ITimeZone timeZone = null; - var siteService = scope.ServiceProvider.GetService(); - if (siteService is not null) + // Check if the shell has no pipeline and should not be warmed up. + if (!_options.ShellWarmup && !shellScope.ShellContext.HasPipeline()) { - try - { - timeZone = _clock.GetTimeZone((await siteService.GetSiteSettingsAsync()).TimeZoneId); - } - catch (Exception ex) when (!ex.IsFatal()) - { - _logger.LogError(ex, "Error while getting the time zone from the site settings of the tenant '{TenantName}'.", tenant); - } + await shellScope.TerminateShellAsync(); + return; } - foreach (var task in tasks) + // Create a new 'HttpContext' to be used in the background. + _httpContextAccessor.HttpContext = shell.CreateHttpContext(); + + await shellScope.UsingAsync(async scope => { - var taskName = task.GetTaskName(); - var tenantTaskName = tenant + taskName; - if (!_schedulers.TryGetValue(tenantTaskName, out var scheduler)) - { - _schedulers[tenantTaskName] = scheduler = new BackgroundTaskScheduler(tenant, taskName, referenceTime, _clock); - } + var tasks = scope.ServiceProvider.GetServices(); + + CleanSchedulers(tenant, tasks); - scheduler.TimeZone = timeZone; - if (!scheduler.Released && scheduler.Updated) + if (!tasks.Any()) { - continue; + return; } - BackgroundTaskSettings settings = null; - if (settingsProvider is not null) + var settingsProvider = scope.ServiceProvider.GetService(); + _changeTokens[tenant] = settingsProvider?.ChangeToken ?? NullChangeToken.Singleton; + + ITimeZone timeZone = null; + var siteService = scope.ServiceProvider.GetService(); + if (siteService is not null) { try { - settings = await settingsProvider.GetSettingsAsync(task); + timeZone = _clock.GetTimeZone((await siteService.GetSiteSettingsAsync()).TimeZoneId); } catch (Exception ex) when (!ex.IsFatal()) { - _logger.LogError(ex, "Error while updating settings of background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); + _logger.LogError(ex, "Error while getting the time zone from the site settings of the tenant '{TenantName}'.", tenant); } } - settings ??= task.GetDefaultSettings(); - if (scheduler.Released || !scheduler.Settings.Schedule.Equals(settings.Schedule)) + foreach (var task in tasks) { - scheduler.ReferenceTime = referenceTime; + var taskName = task.GetTaskName(); + var tenantTaskName = tenant + taskName; + if (!_schedulers.TryGetValue(tenantTaskName, out var scheduler)) + { + _schedulers[tenantTaskName] = scheduler = new BackgroundTaskScheduler(tenant, taskName, referenceTime, _clock); + } + + scheduler.TimeZone = timeZone; + if (!scheduler.Released && scheduler.Updated) + { + continue; + } + + BackgroundTaskSettings settings = null; + if (settingsProvider is not null) + { + try + { + settings = await settingsProvider.GetSettingsAsync(task); + } + catch (Exception ex) when (!ex.IsFatal()) + { + _logger.LogError(ex, "Error while updating settings of background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); + } + } + + settings ??= task.GetDefaultSettings(); + if (scheduler.Released || !scheduler.Settings.Schedule.Equals(settings.Schedule)) + { + scheduler.ReferenceTime = referenceTime; + } + + scheduler.Settings = settings; + scheduler.Released = false; + scheduler.Updated = true; } + }); - scheduler.Settings = settings; - scheduler.Released = false; - scheduler.Updated = true; - } + // Clear the 'HttpContext' for this async flow. + _httpContextAccessor.HttpContext = null; }); - - // Clear the 'HttpContext' for this async flow. - _httpContextAccessor.HttpContext = null; - }); } private static async Task WaitAsync(Task pollingDelay, CancellationToken stoppingToken) @@ -348,29 +349,21 @@ private static async Task WaitAsync(Task pollingDelay, CancellationToken stoppin await Task.Delay(_minIdleTime, stoppingToken); await pollingDelay; } - catch (OperationCanceledException) - { - } + catch (OperationCanceledException) { } } - private (string Tenant, long UtcTicks)[] GetRunningShells() => _shellHost - .ListShellContexts() - .Where(shell => shell.Settings.IsRunning() && (_options.ShellWarmup || shell.HasPipeline())) - .Select(shell => (shell.Settings.Name, shell.UtcTicks)) - .ToArray(); + private (string Tenant, long UtcTicks)[] GetRunningShells() => + _shellHost + .ListShellContexts() + .Where(shell => shell.Settings.IsRunning() && (_options.ShellWarmup || shell.HasPipeline())) + .Select(shell => (shell.Settings.Name, shell.UtcTicks)) + .ToArray(); private string[] GetShellsToRun(IEnumerable<(string Tenant, long UtcTicks)> shells) { - var tenantsToRun = _schedulers - .Where(scheduler => scheduler.Value.CanRun()) - .Select(scheduler => scheduler.Value.Tenant) - .Distinct() - .ToArray(); + var tenantsToRun = _schedulers.Where(scheduler => scheduler.Value.CanRun()).Select(scheduler => scheduler.Value.Tenant).Distinct().ToArray(); - return shells - .Select(shell => shell.Tenant) - .Where(tenant => tenantsToRun.Contains(tenant)) - .ToArray(); + return shells.Select(shell => shell.Tenant).Where(tenant => tenantsToRun.Contains(tenant)).ToArray(); } private string[] GetShellsToUpdate((string Tenant, long UtcTicks)[] previousShells, (string Tenant, long UtcTicks)[] runningShells) @@ -380,9 +373,7 @@ private string[] GetShellsToUpdate((string Tenant, long UtcTicks)[] previousShel var releasedTenants = new List(); foreach (var (tenant, utcTicks) in previousShells) { - if (_shellHost.TryGetShellContext(tenant, out var existing) && - existing.UtcTicks == utcTicks && - !existing.Released) + if (_shellHost.TryGetShellContext(tenant, out var existing) && existing.UtcTicks == utcTicks && !existing.Released) { continue; } @@ -408,10 +399,8 @@ private string[] GetShellsToUpdate((string Tenant, long UtcTicks)[] previousShel return runningTenants.Where(tenant => tenantsToUpdate.Contains(tenant)).ToArray(); } - private BackgroundTaskScheduler[] GetSchedulersToRun(string tenant) => _schedulers - .Where(scheduler => scheduler.Value.Tenant == tenant && scheduler.Value.CanRun()) - .Select(scheduler => scheduler.Value) - .ToArray(); + private BackgroundTaskScheduler[] GetSchedulersToRun(string tenant) => + _schedulers.Where(scheduler => scheduler.Value.Tenant == tenant && scheduler.Value.CanRun()).Select(scheduler => scheduler.Value).ToArray(); private void UpdateSchedulers(string[] tenants, Action action) { diff --git a/src/OrchardCore/OrchardCore/Modules/ModularTenantContainerMiddleware.cs b/src/OrchardCore/OrchardCore/Modules/ModularTenantContainerMiddleware.cs index c0bc28dcba8..6fc86923701 100644 --- a/src/OrchardCore/OrchardCore/Modules/ModularTenantContainerMiddleware.cs +++ b/src/OrchardCore/OrchardCore/Modules/ModularTenantContainerMiddleware.cs @@ -15,10 +15,7 @@ public class ModularTenantContainerMiddleware private readonly IShellHost _shellHost; private readonly IRunningShellTable _runningShellTable; - public ModularTenantContainerMiddleware( - RequestDelegate next, - IShellHost shellHost, - IRunningShellTable runningShellTable) + public ModularTenantContainerMiddleware(RequestDelegate next, IShellHost shellHost, IRunningShellTable runningShellTable) { _next = next; _shellHost = shellHost; @@ -49,12 +46,14 @@ public async Task Invoke(HttpContext httpContext) var shellScope = await _shellHost.GetScopeAsync(shellSettings); // Holds the 'ShellContext' for the full request. - httpContext.Features.Set(new ShellContextFeature - { - ShellContext = shellScope.ShellContext, - OriginalPath = httpContext.Request.Path, - OriginalPathBase = httpContext.Request.PathBase - }); + httpContext.Features.Set( + new ShellContextFeature + { + ShellContext = shellScope.ShellContext, + OriginalPath = httpContext.Request.Path, + OriginalPathBase = httpContext.Request.PathBase + } + ); await shellScope.UsingAsync(async scope => { diff --git a/src/OrchardCore/OrchardCore/Modules/ModularTenantRouterMiddleware.cs b/src/OrchardCore/OrchardCore/Modules/ModularTenantRouterMiddleware.cs index b344ff717e0..2ad719d675a 100644 --- a/src/OrchardCore/OrchardCore/Modules/ModularTenantRouterMiddleware.cs +++ b/src/OrchardCore/OrchardCore/Modules/ModularTenantRouterMiddleware.cs @@ -15,8 +15,7 @@ public class ModularTenantRouterMiddleware { private readonly ILogger _logger; - public ModularTenantRouterMiddleware(RequestDelegate _, ILogger logger) - => _logger = logger; + public ModularTenantRouterMiddleware(RequestDelegate _, ILogger logger) => _logger = logger; public async Task Invoke(HttpContext httpContext) { diff --git a/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/ActiveHandlerTrackingEntry.cs b/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/ActiveHandlerTrackingEntry.cs index 1a2493023d6..0e52d970204 100644 --- a/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/ActiveHandlerTrackingEntry.cs +++ b/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/ActiveHandlerTrackingEntry.cs @@ -22,11 +22,7 @@ internal sealed class ActiveHandlerTrackingEntry : IDisposable // OC: Implement IDisposable. private bool _disposed; - public ActiveHandlerTrackingEntry( - string name, - LifetimeTrackingHttpMessageHandler handler, - IServiceScope scope, - TimeSpan lifetime) + public ActiveHandlerTrackingEntry(string name, LifetimeTrackingHttpMessageHandler handler, IServiceScope scope, TimeSpan lifetime) { Name = name; Handler = handler; diff --git a/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/LifetimeTrackingHttpMessageHandler.cs b/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/LifetimeTrackingHttpMessageHandler.cs index 68190dbc5b1..0cb2c25a2f9 100644 --- a/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/LifetimeTrackingHttpMessageHandler.cs +++ b/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/LifetimeTrackingHttpMessageHandler.cs @@ -11,9 +11,7 @@ namespace Microsoft.Extensions.Http internal sealed class LifetimeTrackingHttpMessageHandler : DelegatingHandler { public LifetimeTrackingHttpMessageHandler(HttpMessageHandler innerHandler) - : base(innerHandler) - { - } + : base(innerHandler) { } protected override void Dispose(bool disposing) { diff --git a/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/TenantHttpClientFactory.cs b/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/TenantHttpClientFactory.cs index 07359c8104a..cd0de5226f8 100644 --- a/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/TenantHttpClientFactory.cs +++ b/src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/TenantHttpClientFactory.cs @@ -69,7 +69,8 @@ public TenantHttpClientFactory( IServiceProvider services, IServiceScopeFactory scopeFactory, IOptionsMonitor optionsMonitor, - IEnumerable filters) + IEnumerable filters + ) { // ThrowHelper.ThrowIfNull(services); // ThrowHelper.ThrowIfNull(scopeFactory); @@ -90,10 +91,13 @@ public TenantHttpClientFactory( _activeHandlers = new ConcurrentDictionary>(StringComparer.Ordinal); _entryFactory = (name) => { - return new Lazy(() => - { - return CreateHandlerEntry(name); - }, LazyThreadSafetyMode.ExecutionAndPublication); + return new Lazy( + () => + { + return CreateHandlerEntry(name); + }, + LazyThreadSafetyMode.ExecutionAndPublication + ); }; _expiredHandlers = new ConcurrentQueue(); @@ -108,11 +112,10 @@ public TenantHttpClientFactory( // to prevent creation of unnecessary ILogger objects in case several handlers expired at the same time. // OC: Null check on '_services'. - _logger = new Lazy(() => - _services is not null - ? _services.GetRequiredService().CreateLogger() - : NullLogger.Instance, - LazyThreadSafetyMode.ExecutionAndPublication); + _logger = new Lazy( + () => _services is not null ? _services.GetRequiredService().CreateLogger() : NullLogger.Instance, + LazyThreadSafetyMode.ExecutionAndPublication + ); } public HttpClient CreateClient(string name) @@ -386,23 +389,26 @@ public static class EventIds private static readonly Action _cleanupCycleStart = LoggerMessage.Define( LogLevel.Debug, EventIds.CleanupCycleStart, - "Starting HttpMessageHandler cleanup cycle with {InitialCount} items"); + "Starting HttpMessageHandler cleanup cycle with {InitialCount} items" + ); private static readonly Action _cleanupCycleEnd = LoggerMessage.Define( LogLevel.Debug, EventIds.CleanupCycleEnd, - "Ending HttpMessageHandler cleanup cycle after {ElapsedMilliseconds}ms - processed: {DisposedCount} items - remaining: {RemainingItems} items"); + "Ending HttpMessageHandler cleanup cycle after {ElapsedMilliseconds}ms - processed: {DisposedCount} items - remaining: {RemainingItems} items" + ); private static readonly Action _cleanupItemFailed = LoggerMessage.Define( LogLevel.Error, EventIds.CleanupItemFailed, - "HttpMessageHandler.Dispose() threw an unhandled exception for client: '{ClientName}'"); + "HttpMessageHandler.Dispose() threw an unhandled exception for client: '{ClientName}'" + ); private static readonly Action _handlerExpired = LoggerMessage.Define( LogLevel.Debug, EventIds.HandlerExpired, - "HttpMessageHandler expired after {HandlerLifetime}ms for client '{ClientName}'"); - + "HttpMessageHandler expired after {HandlerLifetime}ms for client '{ClientName}'" + ); public static void CleanupCycleStart(Lazy loggerLazy, int initialCount) { diff --git a/src/OrchardCore/OrchardCore/Modules/Services/LocalClock.cs b/src/OrchardCore/OrchardCore/Modules/Services/LocalClock.cs index 6c6661e2642..eb165ed394b 100644 --- a/src/OrchardCore/OrchardCore/Modules/Services/LocalClock.cs +++ b/src/OrchardCore/OrchardCore/Modules/Services/LocalClock.cs @@ -22,10 +22,7 @@ public LocalClock(IEnumerable timeZoneSelectors, IClock clock public Task LocalNowAsync { - get - { - return GetLocalNowAsync(); - } + get { return GetLocalNowAsync(); } } private async Task GetLocalNowAsync() diff --git a/src/OrchardCore/OrchardCore/Shell/Builders/CompositionStrategy.cs b/src/OrchardCore/OrchardCore/Shell/Builders/CompositionStrategy.cs index a75445aea2c..09f0a83598f 100644 --- a/src/OrchardCore/OrchardCore/Shell/Builders/CompositionStrategy.cs +++ b/src/OrchardCore/OrchardCore/Shell/Builders/CompositionStrategy.cs @@ -16,9 +16,7 @@ public class CompositionStrategy : ICompositionStrategy private readonly IExtensionManager _extensionManager; private readonly ILogger _logger; - public CompositionStrategy( - IExtensionManager extensionManager, - ILogger logger) + public CompositionStrategy(IExtensionManager extensionManager, ILogger logger) { _extensionManager = extensionManager; _logger = logger; diff --git a/src/OrchardCore/OrchardCore/Shell/Builders/Extensions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore/Shell/Builders/Extensions/ServiceCollectionExtensions.cs index eb726a706d9..5d0fab9cd08 100644 --- a/src/OrchardCore/OrchardCore/Shell/Builders/Extensions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore/Shell/Builders/Extensions/ServiceCollectionExtensions.cs @@ -7,10 +7,7 @@ namespace OrchardCore.Environment.Shell.Builders { internal static class ServiceCollectionExtensions { - public static IServiceCollection CloneSingleton( - this IServiceCollection services, - ServiceDescriptor parent, - object implementationInstance) + public static IServiceCollection CloneSingleton(this IServiceCollection services, ServiceDescriptor parent, object implementationInstance) { var cloned = parent.ServiceKey is not null ? new ClonedSingletonDescriptor(parent, parent.ServiceKey, implementationInstance) @@ -21,10 +18,7 @@ public static IServiceCollection CloneSingleton( return services; } - public static IServiceCollection CloneSingleton( - this IServiceCollection collection, - ServiceDescriptor parent, - Func implementationFactory) + public static IServiceCollection CloneSingleton(this IServiceCollection collection, ServiceDescriptor parent, Func implementationFactory) { var cloned = new ClonedSingletonDescriptor(parent, implementationFactory); collection.Add(cloned); @@ -32,10 +26,7 @@ public static IServiceCollection CloneSingleton( return collection; } - public static IServiceCollection CloneSingleton( - this IServiceCollection collection, - ServiceDescriptor parent, - Func implementationFactory) + public static IServiceCollection CloneSingleton(this IServiceCollection collection, ServiceDescriptor parent, Func implementationFactory) { var cloned = new ClonedSingletonDescriptor(parent, parent.ServiceKey, implementationFactory); collection.Add(cloned); diff --git a/src/OrchardCore/OrchardCore/Shell/Builders/Extensions/ServiceProviderExtensions.cs b/src/OrchardCore/OrchardCore/Shell/Builders/Extensions/ServiceProviderExtensions.cs index 2f2c7c44442..a18f0650139 100644 --- a/src/OrchardCore/OrchardCore/Shell/Builders/Extensions/ServiceProviderExtensions.cs +++ b/src/OrchardCore/OrchardCore/Shell/Builders/Extensions/ServiceProviderExtensions.cs @@ -22,10 +22,7 @@ public static IServiceCollection CreateChildContainer(this IServiceProvider serv foreach (var services in servicesByType) { // Prevent hosting 'IStartupFilter' to re-add middleware to the tenant pipeline. - if (services.Key.ServiceType == typeof(IStartupFilter)) - { - } - + if (services.Key.ServiceType == typeof(IStartupFilter)) { } // A generic type definition is rather used to create other constructed generic types. else if (services.Key.ServiceType.IsGenericTypeDefinition) { @@ -35,7 +32,6 @@ public static IServiceCollection CreateChildContainer(this IServiceProvider serv clonedCollection.Add(service); } } - // If only one service of a given type. else if (services.Count() == 1) { @@ -44,8 +40,7 @@ public static IServiceCollection CreateChildContainer(this IServiceProvider serv { // An host singleton is shared across tenant containers but only registered instances are not disposed // by the DI, so we check if it is disposable or if it uses a factory which may return a different type. - if (typeof(IDisposable).IsAssignableFrom(service.GetImplementationType()) || - service.GetImplementationFactory() is not null) + if (typeof(IDisposable).IsAssignableFrom(service.GetImplementationType()) || service.GetImplementationFactory() is not null) { // If disposable, register an instance that we resolve immediately from the main container. var instance = service.IsKeyedService @@ -57,16 +52,14 @@ public static IServiceCollection CreateChildContainer(this IServiceProvider serv else if (!service.IsKeyedService) { // If not disposable, the singleton can be resolved through a factory when first requested. - clonedCollection.CloneSingleton(service, sp => - serviceProvider.GetRequiredService(service.ServiceType)); + clonedCollection.CloneSingleton(service, sp => serviceProvider.GetRequiredService(service.ServiceType)); // Note: Most of the time a singleton of a given type is unique and not disposable. So, // most of the time it will be resolved when first requested through a tenant container. } else { - clonedCollection.CloneSingleton(service, (sp, key) => - serviceProvider.GetRequiredKeyedService(service.ServiceType, key)); + clonedCollection.CloneSingleton(service, (sp, key) => serviceProvider.GetRequiredKeyedService(service.ServiceType, key)); } } else @@ -74,7 +67,6 @@ public static IServiceCollection CreateChildContainer(this IServiceProvider serv clonedCollection.Add(service); } } - // If all services of the same type are not singletons. else if (services.All(s => s.Lifetime != ServiceLifetime.Singleton)) { @@ -84,7 +76,6 @@ public static IServiceCollection CreateChildContainer(this IServiceProvider serv clonedCollection.Add(service); } } - // If all services of the same type are singletons. else if (services.All(s => s.Lifetime == ServiceLifetime.Singleton)) { @@ -104,7 +95,6 @@ public static IServiceCollection CreateChildContainer(this IServiceProvider serv clonedCollection.CloneSingleton(services.ElementAt(i), instance); } } - // If singletons and scoped services are mixed. else { diff --git a/src/OrchardCore/OrchardCore/Shell/Builders/ShellContainerFactory.cs b/src/OrchardCore/OrchardCore/Shell/Builders/ShellContainerFactory.cs index 4ae3c1281de..bf444ed6425 100644 --- a/src/OrchardCore/OrchardCore/Shell/Builders/ShellContainerFactory.cs +++ b/src/OrchardCore/OrchardCore/Shell/Builders/ShellContainerFactory.cs @@ -25,7 +25,8 @@ public ShellContainerFactory( IHostEnvironment hostingEnvironment, IExtensionManager extensionManager, IServiceProvider serviceProvider, - IServiceCollection applicationServices) + IServiceCollection applicationServices + ) { _hostingEnvironment = hostingEnvironment; _extensionManager = extensionManager; @@ -80,19 +81,14 @@ public async Task CreateContainerAsync(ShellSettings settings, null, CallingConventions.Any, [typeof(IServiceCollection)], - null); + null + ); - var configureMethod = rawStartup.GetMethod( - nameof(IStartup.Configure), - BindingFlags.Public | BindingFlags.Instance); + var configureMethod = rawStartup.GetMethod(nameof(IStartup.Configure), BindingFlags.Public | BindingFlags.Instance); - var orderProperty = rawStartup.GetProperty( - nameof(IStartup.Order), - BindingFlags.Public | BindingFlags.Instance); + var orderProperty = rawStartup.GetProperty(nameof(IStartup.Order), BindingFlags.Public | BindingFlags.Instance); - var configureOrderProperty = rawStartup.GetProperty( - nameof(IStartup.ConfigureOrder), - BindingFlags.Public | BindingFlags.Instance); + var configureOrderProperty = rawStartup.GetProperty(nameof(IStartup.ConfigureOrder), BindingFlags.Public | BindingFlags.Instance); // Add the startup class to the DI so we can instantiate it with // valid ctor arguments @@ -151,9 +147,7 @@ public async Task CreateContainerAsync(ShellSettings settings, if (attribute is not null) { - feature = featureServiceCollection.Key.Extension.Features - .FirstOrDefault(f => f.Id == attribute.FeatureName) - ?? feature; + feature = featureServiceCollection.Key.Extension.Features.FirstOrDefault(f => f.Id == attribute.FeatureName) ?? feature; } } @@ -171,8 +165,7 @@ private void EnsureApplicationFeature() { lock (this) { - _applicationFeature ??= _extensionManager.GetFeatures() - .FirstOrDefault(f => f.Id == _hostingEnvironment.ApplicationName); + _applicationFeature ??= _extensionManager.GetFeatures().FirstOrDefault(f => f.Id == _hostingEnvironment.ApplicationName); } } } diff --git a/src/OrchardCore/OrchardCore/Shell/Builders/ShellContextFactory.cs b/src/OrchardCore/OrchardCore/Shell/Builders/ShellContextFactory.cs index f06f0d477cd..7b037b0df81 100644 --- a/src/OrchardCore/OrchardCore/Shell/Builders/ShellContextFactory.cs +++ b/src/OrchardCore/OrchardCore/Shell/Builders/ShellContextFactory.cs @@ -20,7 +20,8 @@ public ShellContextFactory( ICompositionStrategy compositionStrategy, IShellContainerFactory shellContainerFactory, IEnumerable shellFeatures, - ILogger logger) + ILogger logger + ) { _compositionStrategy = compositionStrategy; _shellContainerFactory = shellContainerFactory; @@ -111,11 +112,7 @@ private ShellDescriptor MinimumShellDescriptor() { // Load default features from the list of registered ShellFeature instances in the DI - return new ShellDescriptor - { - SerialNumber = -1, - Features = new List(_shellFeatures) - }; + return new ShellDescriptor { SerialNumber = -1, Features = new List(_shellFeatures) }; } } } diff --git a/src/OrchardCore/OrchardCore/Shell/Builders/StartupBaseMock.cs b/src/OrchardCore/OrchardCore/Shell/Builders/StartupBaseMock.cs index 0d371658049..8d624478de1 100644 --- a/src/OrchardCore/OrchardCore/Shell/Builders/StartupBaseMock.cs +++ b/src/OrchardCore/OrchardCore/Shell/Builders/StartupBaseMock.cs @@ -14,12 +14,7 @@ internal class StartupBaseMock : StartupBase private readonly MethodInfo _configureService; private readonly MethodInfo _configure; - public StartupBaseMock( - object startup, - MethodInfo configureService, - MethodInfo configure, - PropertyInfo order, - PropertyInfo configureOrder) + public StartupBaseMock(object startup, MethodInfo configureService, MethodInfo configure, PropertyInfo order, PropertyInfo configureOrder) { _startup = startup; _configureService = configureService; @@ -57,23 +52,25 @@ public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder ro // Resolve all services - var parameters = _configure.GetParameters().Select(x => - { - if (x.ParameterType == typeof(IServiceProvider)) - { - return serviceProvider; - } - else if (x.ParameterType == typeof(IApplicationBuilder)) - { - return app; - } - else if (x.ParameterType == typeof(IEndpointRouteBuilder)) + var parameters = _configure + .GetParameters() + .Select(x => { - return routes; - } + if (x.ParameterType == typeof(IServiceProvider)) + { + return serviceProvider; + } + else if (x.ParameterType == typeof(IApplicationBuilder)) + { + return app; + } + else if (x.ParameterType == typeof(IEndpointRouteBuilder)) + { + return routes; + } - return serviceProvider.GetService(x.ParameterType); - }); + return serviceProvider.GetService(x.ParameterType); + }); _configure.Invoke(_startup, parameters.ToArray()); } diff --git a/src/OrchardCore/OrchardCore/Shell/Configuration/ShellConfigurationSources.cs b/src/OrchardCore/OrchardCore/Shell/Configuration/ShellConfigurationSources.cs index 5fa363f22da..c74a5c03bec 100644 --- a/src/OrchardCore/OrchardCore/Shell/Configuration/ShellConfigurationSources.cs +++ b/src/OrchardCore/OrchardCore/Shell/Configuration/ShellConfigurationSources.cs @@ -78,9 +78,7 @@ public Task RemoveAsync(string tenant) } catch (IOException ex) { - _logger.LogError( - ex, - "Error while deleting the '{AppSettings}' file of tenant '{TenantName}'", appsettings, tenant); + _logger.LogError(ex, "Error while deleting the '{AppSettings}' file of tenant '{TenantName}'", appsettings, tenant); } } diff --git a/src/OrchardCore/OrchardCore/Shell/Configuration/ShellsConfigurationSources.cs b/src/OrchardCore/OrchardCore/Shell/Configuration/ShellsConfigurationSources.cs index 811d0bf6324..61564326213 100644 --- a/src/OrchardCore/OrchardCore/Shell/Configuration/ShellsConfigurationSources.cs +++ b/src/OrchardCore/OrchardCore/Shell/Configuration/ShellsConfigurationSources.cs @@ -19,9 +19,7 @@ public ShellsConfigurationSources(IHostEnvironment hostingEnvironment, IOptions< public Task AddSourcesAsync(IConfigurationBuilder builder) { - builder - .AddTenantJsonFile($"{_appsettings}.json", optional: true) - .AddTenantJsonFile($"{_appsettings}.{_environment}.json", optional: true); + builder.AddTenantJsonFile($"{_appsettings}.json", optional: true).AddTenantJsonFile($"{_appsettings}.{_environment}.json", optional: true); return Task.CompletedTask; } diff --git a/src/OrchardCore/OrchardCore/Shell/DefaultTenantOnlyFeatureValidationProvider.cs b/src/OrchardCore/OrchardCore/Shell/DefaultTenantOnlyFeatureValidationProvider.cs index cd116b720b0..89984ccd22f 100644 --- a/src/OrchardCore/OrchardCore/Shell/DefaultTenantOnlyFeatureValidationProvider.cs +++ b/src/OrchardCore/OrchardCore/Shell/DefaultTenantOnlyFeatureValidationProvider.cs @@ -9,10 +9,7 @@ public class DefaultTenantOnlyFeatureValidationProvider : IFeatureValidationProv private readonly IExtensionManager _extensionManager; private readonly ShellSettings _shellSettings; - public DefaultTenantOnlyFeatureValidationProvider( - IExtensionManager extensionManager, - ShellSettings shellSettings - ) + public DefaultTenantOnlyFeatureValidationProvider(IExtensionManager extensionManager, ShellSettings shellSettings) { _extensionManager = extensionManager; _shellSettings = shellSettings; diff --git a/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/AllFeaturesShellDescriptorManager.cs b/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/AllFeaturesShellDescriptorManager.cs index 28141776802..e67f7d9da51 100644 --- a/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/AllFeaturesShellDescriptorManager.cs +++ b/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/AllFeaturesShellDescriptorManager.cs @@ -22,10 +22,7 @@ public AllFeaturesShellDescriptorManager(IExtensionManager extensionManager) public Task GetShellDescriptorAsync() { - _shellDescriptor ??= new ShellDescriptor - { - Features = _extensionManager.GetFeatures().Select(x => new ShellFeature { Id = x.Id }).ToList(), - }; + _shellDescriptor ??= new ShellDescriptor { Features = _extensionManager.GetFeatures().Select(x => new ShellFeature { Id = x.Id }).ToList(), }; return Task.FromResult(_shellDescriptor); } diff --git a/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/ConfiguredFeaturesShellDescriptorManager.cs b/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/ConfiguredFeaturesShellDescriptorManager.cs index 054c507c06f..5ded74acda3 100644 --- a/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/ConfiguredFeaturesShellDescriptorManager.cs +++ b/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/ConfiguredFeaturesShellDescriptorManager.cs @@ -19,10 +19,7 @@ public class ConfiguredFeaturesShellDescriptorManager : IShellDescriptorManager private ShellDescriptor _shellDescriptor; - public ConfiguredFeaturesShellDescriptorManager( - IShellConfiguration shellConfiguration, - IEnumerable shellFeatures, - IExtensionManager extensionManager) + public ConfiguredFeaturesShellDescriptorManager(IShellConfiguration shellConfiguration, IEnumerable shellFeatures, IExtensionManager extensionManager) { _shellConfiguration = shellConfiguration; _alwaysEnabledFeatures = shellFeatures.Where(f => f.AlwaysEnabled).ToArray(); @@ -36,9 +33,7 @@ public async Task GetShellDescriptorAsync() var configuredFeatures = new ConfiguredFeatures(); _shellConfiguration.Bind(configuredFeatures); - var features = _alwaysEnabledFeatures - .Concat(configuredFeatures.Features.Select(id => new ShellFeature(id) { AlwaysEnabled = true })) - .Distinct(); + var features = _alwaysEnabledFeatures.Concat(configuredFeatures.Features.Select(id => new ShellFeature(id) { AlwaysEnabled = true })).Distinct(); var featureIds = features.Select(sf => sf.Id).ToArray(); @@ -47,12 +42,7 @@ public async Task GetShellDescriptorAsync() .Except(featureIds) .Select(id => new ShellFeature(id)); - _shellDescriptor = new ShellDescriptor - { - Features = features - .Concat(missingDependencies) - .ToList() - }; + _shellDescriptor = new ShellDescriptor { Features = features.Concat(missingDependencies).ToList() }; } return _shellDescriptor; diff --git a/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/SetFeaturesShellDescriptorManager.cs b/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/SetFeaturesShellDescriptorManager.cs index bbbc349b007..17189ab175b 100644 --- a/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/SetFeaturesShellDescriptorManager.cs +++ b/src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/SetFeaturesShellDescriptorManager.cs @@ -34,12 +34,7 @@ public async Task GetShellDescriptorAsync() .Except(featureIds) .Select(id => new ShellFeature(id)); - _shellDescriptor = new ShellDescriptor - { - Features = _shellFeatures - .Concat(missingDependencies) - .ToList() - }; + _shellDescriptor = new ShellDescriptor { Features = _shellFeatures.Concat(missingDependencies).ToList() }; } return _shellDescriptor; diff --git a/src/OrchardCore/OrchardCore/Shell/Distributed/DistributedShellHostedService.cs b/src/OrchardCore/OrchardCore/Shell/Distributed/DistributedShellHostedService.cs index 02ebbf30323..5a19d79e519 100644 --- a/src/OrchardCore/OrchardCore/Shell/Distributed/DistributedShellHostedService.cs +++ b/src/OrchardCore/OrchardCore/Shell/Distributed/DistributedShellHostedService.cs @@ -52,7 +52,8 @@ public DistributedShellHostedService( IShellContextFactory shellContextFactory, IShellSettingsManager shellSettingsManager, IShellRemovalManager shellRemovingManager, - ILogger logger) + ILogger logger + ) { _shellHost = shellHost; _shellContextFactory = shellContextFactory; @@ -102,9 +103,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) } // Manage the second counter used to sync the default tenant while it is 'Uninitialized'. - defaultTenantSyncingSeconds = defaultContext.Settings.IsUninitialized() - ? defaultTenantSyncingSeconds - : 0; + defaultTenantSyncingSeconds = defaultContext.Settings.IsUninitialized() ? defaultTenantSyncingSeconds : 0; // Check periodically if the default tenant is still 'Uninitialized'. if (defaultTenantSyncingSeconds++ > DefaultTenantSyncingPeriod) @@ -112,9 +111,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) defaultTenantSyncingSeconds = 0; // Load the settings of the default tenant that may have been setup by another instance. - using var loadedDefaultSettings = (await _shellSettingsManager - .LoadSettingsAsync(ShellSettings.DefaultShellName)) - .AsDisposable(); + using var loadedDefaultSettings = (await _shellSettingsManager.LoadSettingsAsync(ShellSettings.DefaultShellName)).AsDisposable(); if (loadedDefaultSettings.IsRunning()) { @@ -192,9 +189,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) // Load all new created tenants. foreach (var tenant in tenantsToCreate) { - loadedSettings.Add((await _shellSettingsManager - .LoadSettingsAsync(tenant)) - .AsDisposable()); + loadedSettings.Add((await _shellSettingsManager.LoadSettingsAsync(tenant)).AsDisposable()); } // Retrieve all removed tenants that are not yet removed locally. @@ -342,9 +337,7 @@ public async Task LoadingAsync() } // Load a first isolated configuration before the default context is initialized. - var defaultSettings = (await _shellSettingsManager - .LoadSettingsAsync(ShellSettings.DefaultShellName)) - .AsDisposable(); + var defaultSettings = (await _shellSettingsManager.LoadSettingsAsync(ShellSettings.DefaultShellName)).AsDisposable(); // If there is no default tenant or it is not running, nothing to do. if (!defaultSettings.IsRunning()) @@ -354,8 +347,7 @@ public async Task LoadingAsync() } // Create a distributed context based on the first loaded isolated configuration. - var context = _context = (await CreateDistributedContextAsync(defaultSettings)) - ?.WithoutSharedSettings(); + var context = _context = (await CreateDistributedContextAsync(defaultSettings))?.WithoutSharedSettings(); if (context is null) { @@ -420,8 +412,7 @@ public async Task ReleasingAsync(string name) } // If there is no default tenant or it is not running, nothing to do. - if (!_shellHost.TryGetShellContext(ShellSettings.DefaultShellName, out var defaultContext) || - !defaultContext.Settings.IsRunning()) + if (!_shellHost.TryGetShellContext(ShellSettings.DefaultShellName, out var defaultContext) || !defaultContext.Settings.IsRunning()) { return; } @@ -471,8 +462,7 @@ public async Task ReloadingAsync(string name) } // If there is no default tenant or it is not running, nothing to do. - if (!_shellHost.TryGetShellContext(ShellSettings.DefaultShellName, out var defaultContext) || - !defaultContext.Settings.IsRunning()) + if (!_shellHost.TryGetShellContext(ShellSettings.DefaultShellName, out var defaultContext) || !defaultContext.Settings.IsRunning()) { return; } @@ -537,8 +527,7 @@ public async Task RemovingAsync(string name) } // If there is no default tenant or it is not running, nothing to do. - if (!_shellHost.TryGetShellContext(ShellSettings.DefaultShellName, out var defaultContext) || - !defaultContext.Settings.IsRunning()) + if (!_shellHost.TryGetShellContext(ShellSettings.DefaultShellName, out var defaultContext) || !defaultContext.Settings.IsRunning()) { return; } @@ -576,6 +565,7 @@ public async Task RemovingAsync(string name) } private static string ReleaseIdKey(string name) => $"{name}{ReleaseIdKeySuffix}"; + private static string ReloadIdKey(string name) => $"{name}{ReloadIdKeySuffix}"; /// @@ -635,8 +625,7 @@ private async Task ReuseOrCreateDistributedContextAsync(Shel } // Check if the default tenant descriptor or tenant configuration was updated. - if (_context.Context.Blueprint.Descriptor.SerialNumber != descriptor.SerialNumber || - !_context.Context.Settings.HasConfiguration()) + if (_context.Context.Blueprint.Descriptor.SerialNumber != descriptor.SerialNumber || !_context.Context.Settings.HasConfiguration()) { // Creates a new context based on the default settings and descriptor. return await CreateDistributedContextAsync(defaultContext.Settings, descriptor); @@ -767,9 +756,7 @@ private async Task GetDefaultShellDescriptorAsync(ShellSettings return descriptor; } } - catch - { - } + catch { } return null; } diff --git a/src/OrchardCore/OrchardCore/Shell/FeatureProfilesValidationProvider.cs b/src/OrchardCore/OrchardCore/Shell/FeatureProfilesValidationProvider.cs index 24d06442117..6639ac63fbc 100644 --- a/src/OrchardCore/OrchardCore/Shell/FeatureProfilesValidationProvider.cs +++ b/src/OrchardCore/OrchardCore/Shell/FeatureProfilesValidationProvider.cs @@ -23,7 +23,8 @@ public FeatureProfilesValidationProvider( IExtensionManager extensionManager, IShellHost shellHost, ShellSettings shellSettings, - IOptions featureOptions) + IOptions featureOptions + ) { _extensionManager = extensionManager; _shellHost = shellHost; @@ -44,24 +45,26 @@ public async ValueTask IsFeatureValidAsync(string id) { var scope = await _shellHost.GetScopeAsync(ShellSettings.DefaultShellName); - await scope.UsingAsync(async (scope) => - { - var featureProfilesService = scope.ServiceProvider.GetService(); + await scope.UsingAsync( + async (scope) => + { + var featureProfilesService = scope.ServiceProvider.GetService(); - var featureProfiles = await featureProfilesService.GetFeatureProfilesAsync(); + var featureProfiles = await featureProfilesService.GetFeatureProfilesAsync(); - foreach (var profileName in profileNames.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) - { - if (featureProfiles.TryGetValue(profileName, out var featureProfile)) + foreach (var profileName in profileNames.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { - _featureProfileLookup = (false, featureProfile); + if (featureProfiles.TryGetValue(profileName, out var featureProfile)) + { + _featureProfileLookup = (false, featureProfile); - continue; - } + continue; + } - _featureProfileLookup = (true, null); + _featureProfileLookup = (true, null); + } } - }); + ); } // When the management feature is not enabled we need to pass feature validation. diff --git a/src/OrchardCore/OrchardCore/Shell/NullFeatureProfilesService.cs b/src/OrchardCore/OrchardCore/Shell/NullFeatureProfilesService.cs index 8652f9101ea..f0776f8691e 100644 --- a/src/OrchardCore/OrchardCore/Shell/NullFeatureProfilesService.cs +++ b/src/OrchardCore/OrchardCore/Shell/NullFeatureProfilesService.cs @@ -8,7 +8,6 @@ public class NullFeatureProfilesService : IFeatureProfilesService { private static readonly IDictionary _featureProfiles = new Dictionary(); - public Task> GetFeatureProfilesAsync() - => Task.FromResult(_featureProfiles); + public Task> GetFeatureProfilesAsync() => Task.FromResult(_featureProfiles); } } diff --git a/src/OrchardCore/OrchardCore/Shell/Removing/ShellRemovalManager.cs b/src/OrchardCore/OrchardCore/Shell/Removing/ShellRemovalManager.cs index 6cd6b4b48de..923b5ecb98e 100644 --- a/src/OrchardCore/OrchardCore/Shell/Removing/ShellRemovalManager.cs +++ b/src/OrchardCore/OrchardCore/Shell/Removing/ShellRemovalManager.cs @@ -23,7 +23,8 @@ public ShellRemovalManager( IShellContextFactory shellContextFactory, IEnumerable shellRemovingHandlers, IStringLocalizer localizer, - ILogger logger) + ILogger logger + ) { _shellHost = shellHost; _shellContextFactory = shellContextFactory; @@ -34,11 +35,7 @@ public ShellRemovalManager( public async Task RemoveAsync(ShellSettings shellSettings, bool localResourcesOnly = false) { - var context = new ShellRemovingContext - { - ShellSettings = shellSettings, - LocalResourcesOnly = localResourcesOnly, - }; + var context = new ShellRemovingContext { ShellSettings = shellSettings, LocalResourcesOnly = localResourcesOnly, }; if (shellSettings.IsDefaultShell()) { @@ -64,10 +61,7 @@ public async Task RemoveAsync(ShellSettings shellSettings, } catch (Exception ex) { - _logger.LogError( - ex, - "Failed to create a 'ShellContext' before removing the tenant '{TenantName}'.", - shellSettings.Name); + _logger.LogError(ex, "Failed to create a 'ShellContext' before removing the tenant '{TenantName}'.", shellSettings.Name); context.ErrorMessage = S["Failed to create a 'ShellContext' before removing the tenant."]; context.Error = ex; @@ -79,9 +73,7 @@ public async Task RemoveAsync(ShellSettings shellSettings, (var locker, var locked) = await shellContext.TryAcquireShellRemovingLockAsync(); if (!locked) { - _logger.LogError( - "Failed to acquire a lock before executing the tenant handlers while removing the tenant '{TenantName}'.", - shellSettings.Name); + _logger.LogError("Failed to acquire a lock before executing the tenant handlers while removing the tenant '{TenantName}'.", shellSettings.Name); context.ErrorMessage = S["Failed to acquire a lock before executing the tenant handlers."]; return context; @@ -110,11 +102,7 @@ public async Task RemoveAsync(ShellSettings shellSettings, { var type = handler.GetType().FullName; - _logger.LogError( - ex, - "Failed to execute the tenant handler '{TenantHandler}' while removing the tenant '{TenantName}'.", - type, - shellSettings.Name); + _logger.LogError(ex, "Failed to execute the tenant handler '{TenantHandler}' while removing the tenant '{TenantName}'.", type, shellSettings.Name); context.ErrorMessage = S["Failed to execute the tenant handler '{0}'.", type]; context.Error = ex; @@ -132,9 +120,7 @@ public async Task RemoveAsync(ShellSettings shellSettings, (var locker, var locked) = await shellContext.TryAcquireShellRemovingLockAsync(); if (!locked) { - _logger.LogError( - "Failed to acquire a lock before executing the host handlers while removing the tenant '{TenantName}'.", - shellSettings.Name); + _logger.LogError("Failed to acquire a lock before executing the host handlers while removing the tenant '{TenantName}'.", shellSettings.Name); context.ErrorMessage = S["Failed to acquire a lock before executing the host handlers."]; @@ -165,11 +151,7 @@ public async Task RemoveAsync(ShellSettings shellSettings, { var type = handler.GetType().FullName; - _logger.LogError( - ex, - "Failed to execute the host handler '{HostHandler}' while removing the tenant '{TenantName}'.", - type, - shellSettings.Name); + _logger.LogError(ex, "Failed to execute the host handler '{HostHandler}' while removing the tenant '{TenantName}'.", type, shellSettings.Name); context.ErrorMessage = S["Failed to execute the host handler '{0}'.", type]; context.Error = ex; diff --git a/src/OrchardCore/OrchardCore/Shell/Removing/ShellSettingsRemovingHandler.cs b/src/OrchardCore/OrchardCore/Shell/Removing/ShellSettingsRemovingHandler.cs index 0d706f08716..9440dfffc0d 100644 --- a/src/OrchardCore/OrchardCore/Shell/Removing/ShellSettingsRemovingHandler.cs +++ b/src/OrchardCore/OrchardCore/Shell/Removing/ShellSettingsRemovingHandler.cs @@ -14,10 +14,7 @@ public class ShellSettingsRemovingHandler : IShellRemovingHandler protected readonly IStringLocalizer S; private readonly ILogger _logger; - public ShellSettingsRemovingHandler( - IShellHost shellHost, - IStringLocalizer localizer, - ILogger logger) + public ShellSettingsRemovingHandler(IShellHost shellHost, IStringLocalizer localizer, ILogger logger) { _shellHost = shellHost; S = localizer; @@ -40,10 +37,7 @@ public async Task RemovingAsync(ShellRemovingContext context) } catch (Exception ex) { - _logger.LogError( - ex, - "Failed to remove the shell settings of tenant '{TenantName}'.", - context.ShellSettings.Name); + _logger.LogError(ex, "Failed to remove the shell settings of tenant '{TenantName}'.", context.ShellSettings.Name); context.ErrorMessage = S["Failed to remove the shell settings."]; context.Error = ex; diff --git a/src/OrchardCore/OrchardCore/Shell/Removing/ShellSiteFolderRemovingHandler.cs b/src/OrchardCore/OrchardCore/Shell/Removing/ShellSiteFolderRemovingHandler.cs index de8a2e024f2..70327949def 100644 --- a/src/OrchardCore/OrchardCore/Shell/Removing/ShellSiteFolderRemovingHandler.cs +++ b/src/OrchardCore/OrchardCore/Shell/Removing/ShellSiteFolderRemovingHandler.cs @@ -20,7 +20,8 @@ public class ShellSiteFolderRemovingHandler : IShellRemovingHandler public ShellSiteFolderRemovingHandler( IOptions shellOptions, IStringLocalizer localizer, - ILogger logger) + ILogger logger + ) { _shellOptions = shellOptions.Value; S = localizer; @@ -32,18 +33,13 @@ public ShellSiteFolderRemovingHandler( /// public Task RemovingAsync(ShellRemovingContext context) { - var shellAppDataFolder = Path.Combine( - _shellOptions.ShellsApplicationDataPath, - _shellOptions.ShellsContainerName, - context.ShellSettings.Name); + var shellAppDataFolder = Path.Combine(_shellOptions.ShellsApplicationDataPath, _shellOptions.ShellsContainerName, context.ShellSettings.Name); try { Directory.Delete(shellAppDataFolder, true); } - catch (Exception ex) when (ex is DirectoryNotFoundException) - { - } + catch (Exception ex) when (ex is DirectoryNotFoundException) { } catch (Exception ex) when (ex.IsFileSharingViolation()) { // Sharing violation, may happen if multiple nodes share the same file system @@ -52,20 +48,17 @@ public Task RemovingAsync(ShellRemovingContext context) { _logger.LogWarning( ex, -@"Sharing violation while removing the site folder '{TenantFolder}' of tenant '{TenantName}'. + @"Sharing violation while removing the site folder '{TenantFolder}' of tenant '{TenantName}'. Sharing violation may happen if multiple nodes share the same file system without using a distributed lock. In that case let another node do the job.", shellAppDataFolder, - context.ShellSettings.Name); + context.ShellSettings.Name + ); } } catch (Exception ex) { - _logger.LogError( - ex, - "Failed to remove the site folder '{TenantFolder}' of tenant '{TenantName}'.", - shellAppDataFolder, - context.ShellSettings.Name); + _logger.LogError(ex, "Failed to remove the site folder '{TenantFolder}' of tenant '{TenantName}'.", shellAppDataFolder, context.ShellSettings.Name); context.ErrorMessage = S["Failed to remove the site folder '{0}'.", shellAppDataFolder]; context.Error = ex; diff --git a/src/OrchardCore/OrchardCore/Shell/Removing/ShellWebRootRemovingHandler.cs b/src/OrchardCore/OrchardCore/Shell/Removing/ShellWebRootRemovingHandler.cs index 5c362405368..96a94edff06 100644 --- a/src/OrchardCore/OrchardCore/Shell/Removing/ShellWebRootRemovingHandler.cs +++ b/src/OrchardCore/OrchardCore/Shell/Removing/ShellWebRootRemovingHandler.cs @@ -17,10 +17,7 @@ public class ShellWebRootRemovingHandler : IShellRemovingHandler protected readonly IStringLocalizer S; private readonly ILogger _logger; - public ShellWebRootRemovingHandler( - IWebHostEnvironment webHostEnvironment, - IStringLocalizer localizer, - ILogger logger) + public ShellWebRootRemovingHandler(IWebHostEnvironment webHostEnvironment, IStringLocalizer localizer, ILogger logger) { _webHostEnvironment = webHostEnvironment; S = localizer; @@ -37,17 +34,13 @@ public Task RemovingAsync(ShellRemovingContext context) return Task.CompletedTask; } - var shellWebRootFolder = Path.Combine( - _webHostEnvironment.WebRootPath, - context.ShellSettings.Name); + var shellWebRootFolder = Path.Combine(_webHostEnvironment.WebRootPath, context.ShellSettings.Name); try { Directory.Delete(shellWebRootFolder, true); } - catch (Exception ex) when (ex is DirectoryNotFoundException) - { - } + catch (Exception ex) when (ex is DirectoryNotFoundException) { } catch (Exception ex) when (ex.IsFileSharingViolation()) { // Sharing violation, may happen if multiple nodes share the same file system @@ -56,20 +49,17 @@ public Task RemovingAsync(ShellRemovingContext context) { _logger.LogWarning( ex, -@"Sharing violation while removing the web root folder '{TenantFolder}' of tenant '{TenantName}'. + @"Sharing violation while removing the web root folder '{TenantFolder}' of tenant '{TenantName}'. Sharing violation may happen if multiple nodes share the same file system without using a distributed lock. In that case let another node do the job.", shellWebRootFolder, - context.ShellSettings.Name); + context.ShellSettings.Name + ); } } catch (Exception ex) { - _logger.LogError( - ex, - "Failed to remove the web root folder '{TenantFolder}' of tenant '{TenantName}'.", - shellWebRootFolder, - context.ShellSettings.Name); + _logger.LogError(ex, "Failed to remove the web root folder '{TenantFolder}' of tenant '{TenantName}'.", shellWebRootFolder, context.ShellSettings.Name); context.ErrorMessage = S["Failed to remove the web root folder '{0}'.", shellWebRootFolder]; context.Error = ex; diff --git a/src/OrchardCore/OrchardCore/Shell/RunningShellTable.cs b/src/OrchardCore/OrchardCore/Shell/RunningShellTable.cs index b634d2410a1..0f13149829c 100644 --- a/src/OrchardCore/OrchardCore/Shell/RunningShellTable.cs +++ b/src/OrchardCore/OrchardCore/Shell/RunningShellTable.cs @@ -9,7 +9,9 @@ namespace OrchardCore.Environment.Shell { public class RunningShellTable : IRunningShellTable { - private ImmutableDictionary _shellsByHostAndPrefix = ImmutableDictionary.Empty.WithComparers(StringComparer.OrdinalIgnoreCase); + private ImmutableDictionary _shellsByHostAndPrefix = ImmutableDictionary.Empty.WithComparers( + StringComparer.OrdinalIgnoreCase + ); private ShellSettings _default; private bool _hasStarMapping = false; @@ -38,10 +40,7 @@ public void Add(ShellSettings settings) public void Remove(ShellSettings settings) { - var allHostsAndPrefix = _shellsByHostAndPrefix - .Where(kv => kv.Value.Name == settings.Name) - .Select(kv => kv.Key) - .ToArray(); + var allHostsAndPrefix = _shellsByHostAndPrefix.Where(kv => kv.Value.Name == settings.Name).Select(kv => kv.Key).ToArray(); lock (this) { @@ -166,10 +165,7 @@ private static string[] GetAllHostsAndPrefix(ShellSettings shellSettings) return ["/" + shellSettings.RequestUrlPrefix]; } - return shellSettings - .RequestUrlHosts - .Select(ruh => ruh + "/" + shellSettings.RequestUrlPrefix) - .ToArray(); + return shellSettings.RequestUrlHosts.Select(ruh => ruh + "/" + shellSettings.RequestUrlPrefix).ToArray(); } private bool DefaultIsCatchAll() diff --git a/src/OrchardCore/OrchardCore/Shell/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore/Shell/ServiceCollectionExtensions.cs index 09fe1a06ff5..3978d9392a7 100644 --- a/src/OrchardCore/OrchardCore/Shell/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore/Shell/ServiceCollectionExtensions.cs @@ -57,37 +57,34 @@ public static IServiceCollection AddSetFeaturesDescriptor(this IServiceCollectio return services; } - public static IServiceCollection AddNullFeatureProfilesService(this IServiceCollection services) - => services.AddScoped(); + public static IServiceCollection AddNullFeatureProfilesService(this IServiceCollection services) => + services.AddScoped(); - public static IServiceCollection AddFeatureValidation(this IServiceCollection services) - => services - .AddScoped() - .AddScoped(); + public static IServiceCollection AddFeatureValidation(this IServiceCollection services) => + services.AddScoped().AddScoped(); - public static IServiceCollection ConfigureFeatureProfilesRuleOptions(this IServiceCollection services) - => services - .Configure(o => + public static IServiceCollection ConfigureFeatureProfilesRuleOptions(this IServiceCollection services) => + services.Configure(o => + { + o.Rules["Include"] = (expression, name) => { - o.Rules["Include"] = (expression, name) => + if (FileSystemName.MatchesSimpleExpression(expression, name)) { - if (FileSystemName.MatchesSimpleExpression(expression, name)) - { - return (true, true); - } + return (true, true); + } - return (false, false); - }; + return (false, false); + }; - o.Rules["Exclude"] = (expression, name) => + o.Rules["Exclude"] = (expression, name) => + { + if (FileSystemName.MatchesSimpleExpression(expression, name)) { - if (FileSystemName.MatchesSimpleExpression(expression, name)) - { - return (true, false); - } - - return (false, false); - }; - }); + return (true, false); + } + + return (false, false); + }; + }); } } diff --git a/src/OrchardCore/OrchardCore/Shell/ShellDescriptorFeaturesManager.cs b/src/OrchardCore/OrchardCore/Shell/ShellDescriptorFeaturesManager.cs index f86d77a8bab..2e6d98371e9 100644 --- a/src/OrchardCore/OrchardCore/Shell/ShellDescriptorFeaturesManager.cs +++ b/src/OrchardCore/OrchardCore/Shell/ShellDescriptorFeaturesManager.cs @@ -23,7 +23,8 @@ public ShellDescriptorFeaturesManager( IExtensionManager extensionManager, IEnumerable shellFeatures, IShellDescriptorManager shellDescriptorManager, - ILogger logger) + ILogger logger + ) { _extensionManager = extensionManager; _alwaysEnabledFeatures = shellFeatures.Where(f => f.AlwaysEnabled).ToArray(); @@ -31,27 +32,24 @@ public ShellDescriptorFeaturesManager( _logger = logger; } - public async Task<(IEnumerable, IEnumerable)> UpdateFeaturesAsync(ShellDescriptor shellDescriptor, - IEnumerable featuresToDisable, IEnumerable featuresToEnable, bool force) + public async Task<(IEnumerable, IEnumerable)> UpdateFeaturesAsync( + ShellDescriptor shellDescriptor, + IEnumerable featuresToDisable, + IEnumerable featuresToEnable, + bool force + ) { var featureEventHandlers = ShellScope.Services.GetServices(); - var enabledFeatures = _extensionManager.GetFeatures() - .Where(feature => shellDescriptor.Features.Any(shellFeature => shellFeature.Id == feature.Id)) - .ToArray(); + var enabledFeatures = _extensionManager.GetFeatures().Where(feature => shellDescriptor.Features.Any(shellFeature => shellFeature.Id == feature.Id)).ToArray(); - var enabledFeatureIds = enabledFeatures - .Select(feature => feature.Id) - .ToHashSet(); + var enabledFeatureIds = enabledFeatures.Select(feature => feature.Id).ToHashSet(); - var installedFeatureIds = enabledFeatureIds - .Concat(shellDescriptor.Installed.Select(shellFeature => shellFeature.Id)) - .ToHashSet(); + var installedFeatureIds = enabledFeatureIds.Concat(shellDescriptor.Installed.Select(shellFeature => shellFeature.Id)).ToHashSet(); var alwaysEnabledIds = _alwaysEnabledFeatures.Select(shellFeature => shellFeature.Id).ToArray(); - var byDependencyOnlyFeaturesToDisable = enabledFeatures - .Where(feature => feature.EnabledByDependencyOnly); + var byDependencyOnlyFeaturesToDisable = enabledFeatures.Where(feature => feature.EnabledByDependencyOnly); var allFeaturesToDisable = featuresToDisable .Where(feature => !feature.EnabledByDependencyOnly && !alwaysEnabledIds.Contains(feature.Id)) @@ -91,9 +89,7 @@ public ShellDescriptorFeaturesManager( await featureEventHandlers.InvokeAsync((handler, featureInfo) => handler.EnablingAsync(featureInfo), feature, _logger); } - var allFeaturesToInstall = allFeaturesToEnable - .Where(f => !installedFeatureIds.Contains(f.Id)) - .ToList(); + var allFeaturesToInstall = allFeaturesToEnable.Where(f => !installedFeatureIds.Contains(f.Id)).ToList(); foreach (var feature in allFeaturesToInstall) { @@ -112,9 +108,7 @@ public ShellDescriptorFeaturesManager( if (allFeaturesToDisable.Count > 0 || allFeaturesToEnable.Count > 0) { - await _shellDescriptorManager.UpdateShellDescriptorAsync( - shellDescriptor.SerialNumber, - enabledFeatureIds.Select(id => new ShellFeature(id)).ToArray()); + await _shellDescriptorManager.UpdateShellDescriptorAsync(shellDescriptor.SerialNumber, enabledFeatureIds.Select(id => new ShellFeature(id)).ToArray()); ShellScope.AddDeferredTask(async scope => { @@ -165,10 +159,7 @@ await _shellDescriptorManager.UpdateShellDescriptorAsync( /// An enumeration of the features to disable, empty if 'force' = true and a dependency is disabled. private List GetFeaturesToEnable(IFeatureInfo featureInfo, IEnumerable enabledFeatureIds, bool force) { - var featuresToEnable = _extensionManager - .GetFeatureDependencies(featureInfo.Id) - .Where(f => !enabledFeatureIds.Contains(f.Id)) - .ToList(); + var featuresToEnable = _extensionManager.GetFeatureDependencies(featureInfo.Id).Where(f => !enabledFeatureIds.Contains(f.Id)).ToList(); if (featuresToEnable.Count > 1 && !force) { @@ -192,10 +183,7 @@ private List GetFeaturesToEnable(IFeatureInfo featureInfo, IEnumer /// An enumeration of the features to enable, empty if 'force' = true and a dependent is enabled. private List GetFeaturesToDisable(IFeatureInfo featureInfo, IEnumerable enabledFeatureIds, bool force) { - var featuresToDisable = _extensionManager - .GetDependentFeatures(featureInfo.Id) - .Where(f => enabledFeatureIds.Contains(f.Id)) - .ToList(); + var featuresToDisable = _extensionManager.GetDependentFeatures(featureInfo.Id).Where(f => enabledFeatureIds.Contains(f.Id)).ToList(); if (featuresToDisable.Count > 1 && !force) { diff --git a/src/OrchardCore/OrchardCore/Shell/ShellFeaturesManager.cs b/src/OrchardCore/OrchardCore/Shell/ShellFeaturesManager.cs index 1245c4904c3..c54414fb07d 100644 --- a/src/OrchardCore/OrchardCore/Shell/ShellFeaturesManager.cs +++ b/src/OrchardCore/OrchardCore/Shell/ShellFeaturesManager.cs @@ -18,7 +18,8 @@ public ShellFeaturesManager( IExtensionManager extensionManager, ShellDescriptor shellDescriptor, IShellDescriptorFeaturesManager shellDescriptorFeaturesManager, - IEnumerable featureValidators) + IEnumerable featureValidators + ) { _extensionManager = extensionManager; _shellDescriptor = shellDescriptor; @@ -67,7 +68,11 @@ public Task> GetDisabledFeaturesAsync() return Task.FromResult(_extensionManager.GetFeatures().Where(f => _shellDescriptor.Features.All(sf => sf.Id != f.Id))); } - public Task<(IEnumerable, IEnumerable)> UpdateFeaturesAsync(IEnumerable featuresToDisable, IEnumerable featuresToEnable, bool force) + public Task<(IEnumerable, IEnumerable)> UpdateFeaturesAsync( + IEnumerable featuresToDisable, + IEnumerable featuresToEnable, + bool force + ) { return _shellDescriptorFeaturesManager.UpdateFeaturesAsync(_shellDescriptor, featuresToDisable, featuresToEnable, force); } @@ -75,8 +80,7 @@ public Task> GetDisabledFeaturesAsync() public Task> GetEnabledExtensionsAsync() { // enabled extensions are those which have at least one enabled feature. - var enabledIds = _extensionManager.GetFeatures().Where(f => _shellDescriptor - .Features.Any(sf => sf.Id == f.Id)).Select(f => f.Extension.Id).Distinct().ToArray(); + var enabledIds = _extensionManager.GetFeatures().Where(f => _shellDescriptor.Features.Any(sf => sf.Id == f.Id)).Select(f => f.Extension.Id).Distinct().ToArray(); // Extensions are still ordered according to the weight of their first features. return Task.FromResult(_extensionManager.GetExtensions().Where(e => enabledIds.Contains(e.Id))); diff --git a/src/OrchardCore/OrchardCore/Shell/ShellHost.cs b/src/OrchardCore/OrchardCore/Shell/ShellHost.cs index f2f6b68c354..41370741c0e 100644 --- a/src/OrchardCore/OrchardCore/Shell/ShellHost.cs +++ b/src/OrchardCore/OrchardCore/Shell/ShellHost.cs @@ -39,7 +39,8 @@ public ShellHost( IShellContextFactory shellContextFactory, IRunningShellTable runningShellTable, IExtensionManager extensionManager, - ILogger logger) + ILogger logger + ) { _shellSettingsManager = shellSettingsManager; _shellContextFactory = shellContextFactory; @@ -175,8 +176,7 @@ public async Task RemoveShellSettingsAsync(ShellSettings settings) /// /// A feature is enabled / disabled, the tenant needs to be released so that a new shell will be built. /// - public Task ChangedAsync(ShellDescriptor descriptor, ShellSettings settings) - => ReleaseShellContextAsync(settings); + public Task ChangedAsync(ShellDescriptor descriptor, ShellSettings settings) => ReleaseShellContextAsync(settings); /// /// Reloads the settings and releases the shell so that a new one will be @@ -245,8 +245,7 @@ public async Task ReloadShellContextAsync(ShellSettings settings, bool eventSour settings = loaded; } - throw new ShellHostReloadException( - $"Unable to reload the tenant '{settings.Name}' as too many concurrent processes are trying to do so."); + throw new ShellHostReloadException($"Unable to reload the tenant '{settings.Name}' as too many concurrent processes are trying to do so."); } /// @@ -370,7 +369,8 @@ private async Task PreCreateAndRegisterShellsAsync() foreach (var settings in allSettings) { AddAndRegisterShell(new ShellContext.PlaceHolder { Settings = settings, PreCreated = true }); - }; + } + ; if (_logger.IsEnabled(LogLevel.Information)) { @@ -429,11 +429,7 @@ private async Task CreateSetupContextAsync(ShellSettings defaultSe if (defaultSettings is null) { // Creates a default shell settings based on the configuration. - defaultSettings = _shellSettingsManager - .CreateDefaultSettings() - .AsDefaultShell() - .AsUninitialized() - .AsDisposable(); + defaultSettings = _shellSettingsManager.CreateDefaultSettings().AsDefaultShell().AsUninitialized().AsDisposable(); await UpdateShellSettingsAsync(defaultSettings); } @@ -492,18 +488,12 @@ private void RegisterShellSettings(ShellSettings settings) /// Whether or not a shell can be added to the list of available shells. /// private static bool CanCreateShell(ShellSettings shellSettings) => - shellSettings.IsRunning() || - shellSettings.IsUninitialized() || - shellSettings.IsInitializing() || - shellSettings.IsDisabled(); + shellSettings.IsRunning() || shellSettings.IsUninitialized() || shellSettings.IsInitializing() || shellSettings.IsDisabled(); /// /// Whether or not a shell can be activated and added to the running shells. /// - private static bool CanRegisterShell(ShellSettings shellSettings) => - shellSettings.IsRunning() || - shellSettings.IsUninitialized() || - shellSettings.IsInitializing(); + private static bool CanRegisterShell(ShellSettings shellSettings) => shellSettings.IsRunning() || shellSettings.IsUninitialized() || shellSettings.IsInitializing(); /// /// Whether or not a shell can be released and removed from the list, false if disabled and still in use. @@ -525,18 +515,14 @@ private void CheckCanRemoveShell(ShellSettings settings) // A disabled shell may be still in use in at least one active scope. if (!settings.IsRemovable() || IsShellActive(settings)) { - throw new InvalidOperationException( - $"The tenant '{settings.Name}' can't be removed as it is neither uninitialized nor disabled."); + throw new InvalidOperationException($"The tenant '{settings.Name}' can't be removed as it is neither uninitialized nor disabled."); } } /// /// Whether or not a shell is in use in at least one active scope. /// - private bool IsShellActive(ShellSettings settings) => - settings is { Name: not null } && - _shellContexts.TryGetValue(settings.Name, out var context) && - context.IsActive(); + private bool IsShellActive(ShellSettings settings) => settings is { Name: not null } && _shellContexts.TryGetValue(settings.Name, out var context) && context.IsActive(); public void Dispose() { diff --git a/src/OrchardCore/OrchardCore/Shell/ShellSettingsManager.cs b/src/OrchardCore/OrchardCore/Shell/ShellSettingsManager.cs index e391ba70d65..59635ada70d 100644 --- a/src/OrchardCore/OrchardCore/Shell/ShellSettingsManager.cs +++ b/src/OrchardCore/OrchardCore/Shell/ShellSettingsManager.cs @@ -33,7 +33,8 @@ public ShellSettingsManager( IConfiguration applicationConfiguration, IShellsConfigurationSources tenantsConfigSources, IShellConfigurationSources tenantConfigSources, - IShellsSettingsSources tenantsSettingsSources) + IShellsSettingsSources tenantsSettingsSources + ) { _applicationConfiguration = applicationConfiguration; _tenantsConfigSources = tenantsConfigSources; @@ -43,11 +44,7 @@ public ShellSettingsManager( public ShellSettings CreateDefaultSettings() { - return new ShellSettings - ( - new ShellConfiguration(_configuration), - new ShellConfiguration(_configuration) - ); + return new ShellSettings(new ShellConfiguration(_configuration), new ShellConfiguration(_configuration)); } public async Task> LoadSettingsAsync() @@ -73,13 +70,11 @@ public async Task> LoadSettingsAsync() var settings = new ShellConfiguration(tenantSettingsBuilder); var configuration = new ShellConfiguration(tenant, _tenantConfigFactoryAsync); - var shellSettings = new ShellSettings(settings, configuration) - { - Name = tenant, - }; + var shellSettings = new ShellSettings(settings, configuration) { Name = tenant, }; allSettings.Add(shellSettings); - }; + } + ; return allSettings; } @@ -122,10 +117,7 @@ public async Task LoadSettingsAsync(string tenant) var settings = new ShellConfiguration(tenantSettingsBuilder); var configuration = new ShellConfiguration(tenant, _tenantConfigFactoryAsync); - return new ShellSettings(settings, configuration) - { - Name = tenant, - }; + return new ShellSettings(settings, configuration) { Name = tenant, }; } finally { @@ -142,15 +134,9 @@ public async Task SaveSettingsAsync(ShellSettings settings) ArgumentNullException.ThrowIfNull(settings); - var configuration = new ConfigurationBuilder() - .AddConfiguration(_configuration) - .AddConfiguration(_configuration.GetSection(settings.Name)) - .Build(); + var configuration = new ConfigurationBuilder().AddConfiguration(_configuration).AddConfiguration(_configuration.GetSection(settings.Name)).Build(); - var shellSettings = new ShellSettings() - { - Name = settings.Name - }; + var shellSettings = new ShellSettings() { Name = settings.Name }; configuration.Bind(shellSettings); @@ -246,15 +232,12 @@ private async Task EnsureConfigurationAsync() return; } - var lastProviders = (_applicationConfiguration as IConfigurationRoot)?.Providers - .Where(p => p is EnvironmentVariablesConfigurationProvider || - p is CommandLineConfigurationProvider) - .ToArray() - ?? []; + var lastProviders = + (_applicationConfiguration as IConfigurationRoot) + ?.Providers.Where(p => p is EnvironmentVariablesConfigurationProvider || p is CommandLineConfigurationProvider) + .ToArray() ?? []; - var configurationBuilder = await new ConfigurationBuilder() - .AddConfiguration(_applicationConfiguration) - .AddSourcesAsync(_tenantsConfigSources); + var configurationBuilder = await new ConfigurationBuilder().AddConfiguration(_applicationConfiguration).AddSourcesAsync(_tenantsConfigSources); if (lastProviders.Length > 0) { @@ -264,7 +247,8 @@ private async Task EnsureConfigurationAsync() _configurationRoot = configurationBuilder.Build(); var configuration = _configurationRoot.GetSection("OrchardCore"); - _configuredTenants = configuration.GetChildren() + _configuredTenants = configuration + .GetChildren() .Where(section => Enum.TryParse(section["State"], ignoreCase: true, out _)) .Select(section => section.Key) .Distinct() @@ -297,9 +281,7 @@ private async Task ReloadTenantsSettingsAsync() { using var disposable = _tenantsSettingsRoot as IDisposable; - _tenantsSettingsRoot = (await new ConfigurationBuilder() - .AddSourcesAsync(_tenantsSettingsSources)) - .Build(); + _tenantsSettingsRoot = (await new ConfigurationBuilder().AddSourcesAsync(_tenantsSettingsSources)).Build(); } public void Dispose() diff --git a/src/OrchardCore/OrchardCore/Shell/SingleShellSettingsManager.cs b/src/OrchardCore/OrchardCore/Shell/SingleShellSettingsManager.cs index 2b00c386274..b136ebf1f9f 100644 --- a/src/OrchardCore/OrchardCore/Shell/SingleShellSettingsManager.cs +++ b/src/OrchardCore/OrchardCore/Shell/SingleShellSettingsManager.cs @@ -8,11 +8,9 @@ public class SingleShellSettingsManager : IShellSettingsManager { public ShellSettings CreateDefaultSettings() => new ShellSettings().AsDefaultShell().AsRunning(); - public Task> LoadSettingsAsync() => - Task.FromResult((new ShellSettings[] { CreateDefaultSettings() }).AsEnumerable()); + public Task> LoadSettingsAsync() => Task.FromResult((new ShellSettings[] { CreateDefaultSettings() }).AsEnumerable()); - public Task> LoadSettingsNamesAsync() => - Task.FromResult((new string[] { ShellSettings.DefaultShellName }).AsEnumerable()); + public Task> LoadSettingsNamesAsync() => Task.FromResult((new string[] { ShellSettings.DefaultShellName }).AsEnumerable()); public Task LoadSettingsAsync(string tenant) => Task.FromResult(CreateDefaultSettings()); diff --git a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Drivers/MyTestPartDisplayDriver.cs b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Drivers/MyTestPartDisplayDriver.cs index 6caa2d66899..85c06017b84 100644 --- a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Drivers/MyTestPartDisplayDriver.cs +++ b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Drivers/MyTestPartDisplayDriver.cs @@ -23,18 +23,20 @@ public override IDisplayResult Display(MyTestPart part, BuildPartDisplayContext { return Initialize(GetDisplayShapeType(context), m => BuildViewModel(m, part, context)) .Location("Detail", "Content:10") - .Location("Summary", "Content:10") - ; + .Location("Summary", "Content:10"); } public override IDisplayResult Edit(MyTestPart part, BuildPartEditorContext context) { - return Initialize(GetEditorShapeType(context), model => - { - model.Show = part.Show; - model.ContentItem = part.ContentItem; - model.MyTestPart = part; - }); + return Initialize( + GetEditorShapeType(context), + model => + { + model.Show = part.Show; + model.ContentItem = part.ContentItem; + model.MyTestPart = part; + } + ); } public override async Task UpdateAsync(MyTestPart model, IUpdateModel updater) diff --git a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Handlers/MyTestPartHandler.cs b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Handlers/MyTestPartHandler.cs index 9a0e7b21fe1..8ddcfdb5710 100644 --- a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Handlers/MyTestPartHandler.cs +++ b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Handlers/MyTestPartHandler.cs @@ -1,5 +1,5 @@ -using OrchardCore.ContentManagement.Handlers; -using System.Threading.Tasks; +using System.Threading.Tasks; +using OrchardCore.ContentManagement.Handlers; using OrchardCore.Templates.Cms.Module.Models; namespace OrchardCore.Templates.Cms.Module.Handlers @@ -13,4 +13,4 @@ public override Task InitializingAsync(InitializingContentContext context, MyTes return Task.CompletedTask; } } -} \ No newline at end of file +} diff --git a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Migrations.cs b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Migrations.cs index fecea5ef41a..518f1f003e6 100644 --- a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Migrations.cs +++ b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Migrations.cs @@ -1,5 +1,5 @@ -using OrchardCore.ContentManagement.Metadata.Settings; using OrchardCore.ContentManagement.Metadata; +using OrchardCore.ContentManagement.Metadata.Settings; using OrchardCore.Data.Migration; namespace OrchardCore.Templates.Cms.Module @@ -15,9 +15,7 @@ public Migrations(IContentDefinitionManager contentDefinitionManager) public int Create() { - _contentDefinitionManager.AlterPartDefinition("MyTestPart", builder => builder - .Attachable() - .WithDescription("Provides a MyTest part for your content item.")); + _contentDefinitionManager.AlterPartDefinition("MyTestPart", builder => builder.Attachable().WithDescription("Provides a MyTest part for your content item.")); return 1; } diff --git a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Settings/MyTestPartSettingsDisplayDriver.cs b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Settings/MyTestPartSettingsDisplayDriver.cs index bea241dbf06..9a9d702bfcd 100644 --- a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Settings/MyTestPartSettingsDisplayDriver.cs +++ b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Settings/MyTestPartSettingsDisplayDriver.cs @@ -17,13 +17,17 @@ public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDef return null; } - return Initialize("MyTestPartSettings_Edit", model => - { - var settings = contentTypePartDefinition.GetSettings(); + return Initialize( + "MyTestPartSettings_Edit", + model => + { + var settings = contentTypePartDefinition.GetSettings(); - model.MySetting = settings.MySetting; - model.MyTestPartSettings = settings; - }).Location("Content"); + model.MySetting = settings.MySetting; + model.MyTestPartSettings = settings; + } + ) + .Location("Content"); } public override async Task UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context) diff --git a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Startup.cs b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Startup.cs index 0b40e707c44..27ba891ea07 100644 --- a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Startup.cs +++ b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Module/Startup.cs @@ -1,9 +1,11 @@ -#if (AddPart) -using Fluid; -#endif using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; +using OrchardCore.Modules; +#if (AddPart) +using Fluid; +#endif + #if (AddPart) using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display.ContentDisplay; @@ -16,7 +18,6 @@ using OrchardCore.Templates.Cms.Module.Settings; using OrchardCore.Templates.Cms.Module.ViewModels; #endif -using OrchardCore.Modules; namespace OrchardCore.Templates.Cms.Module { @@ -30,9 +31,7 @@ public override void ConfigureServices(IServiceCollection services) o.MemberAccessStrategy.Register(); }); - services.AddContentPart() - .UseDisplayDriver() - .AddHandler(); + services.AddContentPart().UseDisplayDriver().AddHandler(); services.AddScoped(); services.AddDataMigration(); diff --git a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Web/Program.cs b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Web/Program.cs index b65a7ae859d..2af584aebd3 100644 --- a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Web/Program.cs +++ b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Cms.Web/Program.cs @@ -12,20 +12,20 @@ builder.Host.UseNLogHost(); #endif #if (UseSerilog) -builder.Host.UseSerilog((hostingContext, configBuilder) => +builder.Host.UseSerilog( + (hostingContext, configBuilder) => { - configBuilder.ReadFrom.Configuration(hostingContext.Configuration) - .Enrich.FromLogContext(); - }); + configBuilder.ReadFrom.Configuration(hostingContext.Configuration).Enrich.FromLogContext(); + } +); #endif -builder.Services - .AddOrchardCms() - // // Orchard Specific Pipeline - // .ConfigureServices( services => { - // }) - // .Configure( (app, routes, services) => { - // }) +builder.Services.AddOrchardCms() +// // Orchard Specific Pipeline +// .ConfigureServices( services => { +// }) +// .Configure( (app, routes, services) => { +// }) ; var app = builder.Build(); diff --git a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Mvc.Module/Startup.cs b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Mvc.Module/Startup.cs index ba43b11c947..b2c5629e7ce 100644 --- a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Mvc.Module/Startup.cs +++ b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Mvc.Module/Startup.cs @@ -7,12 +7,8 @@ namespace OrchardCore.Templates.Mvc.Module { public class Startup : StartupBase { - public override void ConfigureServices(IServiceCollection services) - { - } + public override void ConfigureServices(IServiceCollection services) { } - public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) - { - } + public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { } } -} \ No newline at end of file +} diff --git a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Mvc.Web/Program.cs b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Mvc.Web/Program.cs index 301d3d14ec5..f2d125629cb 100644 --- a/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Mvc.Web/Program.cs +++ b/src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Mvc.Web/Program.cs @@ -1,15 +1,13 @@ var builder = WebApplication.CreateBuilder(args); -builder.Services - .AddOrchardCore() - .AddMvc() - // // Orchard Specific Pipeline - // .ConfigureServices( services => { +builder.Services.AddOrchardCore().AddMvc() +// // Orchard Specific Pipeline +// .ConfigureServices( services => { - // }) - // .Configure( (app, routes, services) => { +// }) +// .Configure( (app, routes, services) => { - // }) +// }) ; var app = builder.Build(); diff --git a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/FeatureAttributeTests.Attribute.cs b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/FeatureAttributeTests.Attribute.cs index 7246778b64a..fb049342d8f 100644 --- a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/FeatureAttributeTests.Attribute.cs +++ b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/FeatureAttributeTests.Attribute.cs @@ -106,14 +106,12 @@ protected virtual TAttribute CreateFromArgs(Func classifier, var allAttributeCtors = typeof(TAttribute).GetConstructors(CtorFlags); // Identify the Ctor with the Parameters aligned to the Classified Arguments. - var allAttributeCtorWithParameterTypes = allAttributeCtors.Select(ctor => new - { - Callback = ctor, - Types = ctor.GetParameters().Select(_ => _.ParameterType).ToArray(), - }).ToArray(); + var allAttributeCtorWithParameterTypes = allAttributeCtors + .Select(ctor => new { Callback = ctor, Types = ctor.GetParameters().Select(_ => _.ParameterType).ToArray(), }) + .ToArray(); - var attributeCtor = allAttributeCtorWithParameterTypes.SingleOrDefault(_ => _.Types.SequenceEqual(types)) - ?.Callback + var attributeCtor = + allAttributeCtorWithParameterTypes.SingleOrDefault(_ => _.Types.SequenceEqual(types))?.Callback ?? throw new ArgumentException($"Unable to align ctor to args({args.Length}).", nameof(args)); var feature = attributeCtor.Invoke(args); @@ -199,7 +197,7 @@ public FeatureAttributeTests(ITestOutputHelper outputHelper) } /// - /// + /// /// /// /// @@ -213,7 +211,7 @@ protected static IEnumerable GetValues(params T[] values) } /// - /// + /// /// /// /// @@ -319,21 +317,18 @@ internal void Deconstruct(out string key, out object value, out Func - /// + /// /// /// /// protected virtual string RenderKeyValuePairs(params RenderKeyValuePair[] pairs) => - string.Join( - string.Join(", ", pairs.Select(_ => $"{_}")), "{}".ToCharArray().Select(_ => $"{_}") - ); + string.Join(string.Join(", ", pairs.Select(_ => $"{_}")), "{}".ToCharArray().Select(_ => $"{_}")); /// - /// + /// /// /// - protected virtual void ReportKeyValuePairs(params RenderKeyValuePair[] pairs) => - OutputHelper.WriteLine($"{RenderKeyValuePairs(pairs)}"); + protected virtual void ReportKeyValuePairs(params RenderKeyValuePair[] pairs) => OutputHelper.WriteLine($"{RenderKeyValuePairs(pairs)}"); /// /// Override in order to enhance the Default coverage. @@ -354,7 +349,8 @@ protected virtual void VerifyDefault(TAttribute feature) Assert.Equal($"{DefaultPriority}", feature.Priority); } - private static bool DefaultAssemblyAttribPredicate(T _) where T : Attribute => _ is not null; + private static bool DefaultAssemblyAttribPredicate(T _) + where T : Attribute => _ is not null; /// /// Returns the Attributes of type exposed by the diff --git a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/FeatureAttributeTests.cs b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/FeatureAttributeTests.cs index e9077c9a376..f44873d632f 100644 --- a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/FeatureAttributeTests.cs +++ b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/FeatureAttributeTests.cs @@ -7,7 +7,7 @@ namespace OrchardCore.Modules.Manifest using Xunit.Abstractions; /// - /// + /// /// public class FeatureAttributeTests : FeatureAttributeTests { @@ -16,9 +16,7 @@ public class FeatureAttributeTests : FeatureAttributeTests /// /// public FeatureAttributeTests(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } + : base(outputHelper) { } /// /// Verifies default Static and Constant assets, as exposed by fixture properties. @@ -161,7 +159,18 @@ public virtual void Ipsum_Ctor_Id_Name_Cat_Pri() new RenderKeyValuePair(nameof(enabledByDependencyOnly), enabledByDependencyOnly) ); - var feature = CreateFromArgs(FeatureString6Object3CtorClassifier, id, name, category, priString, description, depString, defaultTenant, alwaysEnabled, enabledByDependencyOnly); + var feature = CreateFromArgs( + FeatureString6Object3CtorClassifier, + id, + name, + category, + priString, + description, + depString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); Assert.True(feature.Exists); Assert.Equal(id, feature.Id); @@ -279,18 +288,19 @@ public virtual void Prioritize() var expected = priority + 1; // TODO: TBD: also for attributes created using property initializers - FeatureAttribute CreateForPriority(string priString = null) => CreateFromArgs( - FeatureString6Object3CtorClassifier, - LoremWords(1), - name, - category, - priString ?? string.Empty, - description, - depString, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly - ); + FeatureAttribute CreateForPriority(string priString = null) => + CreateFromArgs( + FeatureString6Object3CtorClassifier, + LoremWords(1), + name, + category, + priString ?? string.Empty, + description, + depString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); var alpha = CreateForPriority(); var bravo = CreateForPriority($"{expected}"); @@ -320,18 +330,19 @@ public virtual void Describe() var expected = LoremWords(7); // TODO: TBD: also for attributes created using property initializers - FeatureAttribute CreateForDescription(string description = null) => CreateFromArgs( - FeatureString6Object3CtorClassifier, - LoremWords(1), - name, - category, - priority, - description, - depString, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly - ); + FeatureAttribute CreateForDescription(string description = null) => + CreateFromArgs( + FeatureString6Object3CtorClassifier, + LoremWords(1), + name, + category, + priority, + description, + depString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); var alpha = CreateForDescription(); var bravo = CreateForDescription(expected); @@ -361,18 +372,19 @@ public virtual void Categorize() var expected = LoremWords(1); // TODO: TBD: also for attributes created using property initializers - FeatureAttribute CreateForCategory(string category = null) => CreateFromArgs( - FeatureString6Object3CtorClassifier, - LoremWords(1), - name, - category, - priority, - description, - depString, - defaultTenant, - alwaysEnabled, - enabledByDependencyOnly - ); + FeatureAttribute CreateForCategory(string category = null) => + CreateFromArgs( + FeatureString6Object3CtorClassifier, + LoremWords(1), + name, + category, + priority, + description, + depString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); var alpha = CreateForCategory(); var bravo = CreateForCategory(expected); @@ -389,13 +401,7 @@ FeatureAttribute CreateForCategory(string category = null) => CreateFromArgs( /// a handful of delimiter scenarios. /// /// - [ - Theory, - InlineData(';'), - InlineData(','), - InlineData(' '), - InlineData(':') - ] + [Theory, InlineData(';'), InlineData(','), InlineData(' '), InlineData(':')] public virtual void Dependencies(char delim) { var deps = LoremWords(5).Split(' '); @@ -403,18 +409,8 @@ public virtual void Dependencies(char delim) var listDelims = FeatureAttribute.ListDelims; - FeatureAttribute CreateForDeps(params string[] deps) => CreateFromArgs( - FeatureString6Object3CtorClassifier, - LoremWords(1), - null, - null, - null, - null, - depString, - default(bool), - default(bool), - default(bool) - ); + FeatureAttribute CreateForDeps(params string[] deps) => + CreateFromArgs(FeatureString6Object3CtorClassifier, LoremWords(1), null, null, null, null, depString, default(bool), default(bool), default(bool)); var feature = CreateForDeps(deps); diff --git a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.Attribute.cs b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.Attribute.cs index 7fa7b08462d..ecf50c384bc 100644 --- a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.Attribute.cs +++ b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.Attribute.cs @@ -40,9 +40,8 @@ public abstract class ModuleAttributeTests : FeatureAttributeTests /// - public ModuleAttributeTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } + public ModuleAttributeTests(ITestOutputHelper outputHelper) + : base(outputHelper) { } /// /// Returns the based on the given @@ -52,8 +51,7 @@ public ModuleAttributeTests(ITestOutputHelper outputHelper) : base(outputHelper) /// /// /// - protected static TDetails GetAssemblyDetails(Assembly assembly, Func extract) => - extract.Invoke(assembly, assembly.GetName()); + protected static TDetails GetAssemblyDetails(Assembly assembly, Func extract) => extract.Invoke(assembly, assembly.GetName()); protected override void VerifyDefault(TAttribute module) { diff --git a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.cs b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.cs index 25e59bd5123..7523b72e359 100644 --- a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.cs +++ b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.cs @@ -19,9 +19,8 @@ public class ModuleAttributeTests : ModuleAttributeTests /// Constructor. /// /// - public ModuleAttributeTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } + public ModuleAttributeTests(ITestOutputHelper outputHelper) + : base(outputHelper) { } /// /// "Module" @@ -45,12 +44,7 @@ public class TestAttributePrefix : Attribute { } /// /// /// - [ - Theory, - InlineData(typeof(ModuleAttribute), "Module"), - InlineData(typeof(ThemeAttribute), "Theme"), - InlineData(typeof(TestAttributePrefix), nameof(TestAttributePrefix)) - ] + [Theory, InlineData(typeof(ModuleAttribute), "Module"), InlineData(typeof(ThemeAttribute), "Theme"), InlineData(typeof(TestAttributePrefix), nameof(TestAttributePrefix))] public virtual void AttributePrefix(Type attributeType, string expected) { Assert.Equal(expected, ModuleAttribute.GetAttributePrefix(attributeType)); @@ -92,7 +86,19 @@ public virtual void Ipsum_Ctor_Id() new RenderKeyValuePair(nameof(enabledByDependencyOnly), enabledByDependencyOnly) ); - var module = CreateFromArgs(ModuleString7Object3CtorClassifier, id, description, author, semVer, website, depString, tagString, defaultTenant, alwaysEnabled, enabledByDependencyOnly); + var module = CreateFromArgs( + ModuleString7Object3CtorClassifier, + id, + description, + author, + semVer, + website, + depString, + tagString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); Assert.Equal(id, module.Id); Assert.Equal(id, module.Name); @@ -161,7 +167,20 @@ public virtual void Ipsum_Ctor_Id_Name() new RenderKeyValuePair(nameof(enabledByDependencyOnly), enabledByDependencyOnly) ); - var module = CreateFromArgs(ModuleString8Object3CtorClassifier, id, name, description, author, semVer, website, depString, tagString, defaultTenant, alwaysEnabled, enabledByDependencyOnly); + var module = CreateFromArgs( + ModuleString8Object3CtorClassifier, + id, + name, + description, + author, + semVer, + website, + depString, + tagString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); Assert.Equal(id, module.Id); Assert.Equal(name, module.Name); @@ -233,7 +252,22 @@ public virtual void Ipsum_Ctor_Id_Name_Cat_Pri() new RenderKeyValuePair(nameof(enabledByDependencyOnly), enabledByDependencyOnly) ); - var module = CreateFromArgs(ModuleString10Object3CtorClassifier, id, name, category, priString, description, author, semVer, website, depString, tagString, defaultTenant, alwaysEnabled, enabledByDependencyOnly); + var module = CreateFromArgs( + ModuleString10Object3CtorClassifier, + id, + name, + category, + priString, + description, + author, + semVer, + website, + depString, + tagString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); Assert.Equal(id, module.Id); Assert.Equal(name, module.Name); @@ -305,7 +339,23 @@ public virtual void Ipsum_Ctor_Id_Name_Type_Cat_Pri() new RenderKeyValuePair(nameof(enabledByDependencyOnly), enabledByDependencyOnly) ); - var module = CreateFromArgs(ModuleString11Object3CtorClassifier, id, name, type, category, priString, description, author, semVer, website, depString, tagString, defaultTenant, alwaysEnabled, enabledByDependencyOnly); + var module = CreateFromArgs( + ModuleString11Object3CtorClassifier, + id, + name, + type, + category, + priString, + description, + author, + semVer, + website, + depString, + tagString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); Assert.Equal(id, module.Id); Assert.Equal(name, module.Name); @@ -603,7 +653,8 @@ public virtual void Csproj_OrchardCoreModules_MSBuild_ItemLists() var module = GetAssemblyAttribute(rootType, _ => _.GetType() == typeof(ModuleAttribute)); var features = GetAssemblyAttributes(rootType, _ => _.GetType() == typeof(FeatureAttribute)) // We shall assume the test case includes a valid sortable Priority - .OrderBy(_ => _.InternalPriority).ToArray(); + .OrderBy(_ => _.InternalPriority) + .ToArray(); // TODO: MWP: note that targets are mining for project properties and are also injecting a ModuleMarkerAttribute... // TODO: MWP: ...which is also a 'Module', which is a possible source of confusion, spoofing, counterfeit, fraud, etc @@ -641,26 +692,30 @@ public virtual void Csproj_OrchardCoreModules_MSBuild_ItemLists() /* Features should contain the following composites as well, which, by definition, * should contain 'two' in the following shapes: */ - Assert.Contains(features, _ => - _.Id == string.Join(".", baseId, One) && - _.Name == _.Id && - _.Category.Equals(Two, StringComparison.CurrentCultureIgnoreCase) && - _.InternalPriority == _3 && - _.Description == four && - _.Dependencies.SequenceEqual(GetValues(five, six, seven)) && - _.DefaultTenantOnly == tenant && - _.IsAlwaysEnabled == enabled + Assert.Contains( + features, + _ => + _.Id == string.Join(".", baseId, One) + && _.Name == _.Id + && _.Category.Equals(Two, StringComparison.CurrentCultureIgnoreCase) + && _.InternalPriority == _3 + && _.Description == four + && _.Dependencies.SequenceEqual(GetValues(five, six, seven)) + && _.DefaultTenantOnly == tenant + && _.IsAlwaysEnabled == enabled ); - Assert.Contains(features, _ => - _.Id == string.Join(".", baseId, Two) && - _.Name == _.Id && - _.Category == three && - _.InternalPriority == _4 && - _.Description == five && - _.Dependencies.SequenceEqual(GetValues(six, seven, eight)) && - _.DefaultTenantOnly == tenant && - _.IsAlwaysEnabled == enabled + Assert.Contains( + features, + _ => + _.Id == string.Join(".", baseId, Two) + && _.Name == _.Id + && _.Category == three + && _.InternalPriority == _4 + && _.Description == five + && _.Dependencies.SequenceEqual(GetValues(six, seven, eight)) + && _.DefaultTenantOnly == tenant + && _.IsAlwaysEnabled == enabled ); } diff --git a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ThemeAttributeTests.cs b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ThemeAttributeTests.cs index 8ef3aeedea3..0b3325ab579 100644 --- a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ThemeAttributeTests.cs +++ b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ThemeAttributeTests.cs @@ -16,9 +16,8 @@ public class ThemeAttributeTests : ModuleAttributeTests /// Constructor. /// /// - public ThemeAttributeTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } + public ThemeAttributeTests(ITestOutputHelper outputHelper) + : base(outputHelper) { } /// /// Classifier supporting @@ -115,7 +114,20 @@ public virtual void Ipsum_Ctor_Id() new RenderKeyValuePair(nameof(enabledByDependencyOnly), enabledByDependencyOnly) ); - var theme = CreateFromArgs(ThemeString8Bool3CtorClassifier, id, baseTheme, description, author, semVer, website, depString, tagString, defaultTenant, alwaysEnabled, enabledByDependencyOnly); + var theme = CreateFromArgs( + ThemeString8Bool3CtorClassifier, + id, + baseTheme, + description, + author, + semVer, + website, + depString, + tagString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); Assert.Equal(id, theme.Id); Assert.Equal(id, theme.Name); @@ -183,7 +195,21 @@ public virtual void Ipsum_Ctor_Id_Name() new RenderKeyValuePair(nameof(enabledByDependencyOnly), enabledByDependencyOnly) ); - var theme = CreateFromArgs(ThemeString9Bool3CtorClassifier, id, name, baseTheme, description, author, semVer, website, depString, tagString, defaultTenant, alwaysEnabled, enabledByDependencyOnly); + var theme = CreateFromArgs( + ThemeString9Bool3CtorClassifier, + id, + name, + baseTheme, + description, + author, + semVer, + website, + depString, + tagString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); Assert.Equal(id, theme.Id); Assert.Equal(name, theme.Name); @@ -256,7 +282,23 @@ public virtual void Ipsum_Ctor_Id_Name_Cat_Pri() new RenderKeyValuePair(nameof(enabledByDependencyOnly), enabledByDependencyOnly) ); - var theme = CreateFromArgs(ThemeString11Bool3CtorClassifier, id, name, baseTheme, category, priString, description, author, semVer, website, depString, tagString, defaultTenant, alwaysEnabled, enabledByDependencyOnly); + var theme = CreateFromArgs( + ThemeString11Bool3CtorClassifier, + id, + name, + baseTheme, + category, + priString, + description, + author, + semVer, + website, + depString, + tagString, + defaultTenant, + alwaysEnabled, + enabledByDependencyOnly + ); Assert.Equal(id, theme.Id); Assert.Equal(name, theme.Name); diff --git a/test/OrchardCore.Benchmarks/FluidShapeRenderBenchmark.cs b/test/OrchardCore.Benchmarks/FluidShapeRenderBenchmark.cs index d46b6ee3066..cb894199eca 100644 --- a/test/OrchardCore.Benchmarks/FluidShapeRenderBenchmark.cs +++ b/test/OrchardCore.Benchmarks/FluidShapeRenderBenchmark.cs @@ -17,7 +17,9 @@ namespace OrchardCore.Benchmark [MemoryDiagnoser] public class FluidShapeRenderBenchmark { - private static readonly FilterArguments _filterArguments = new FilterArguments().Add("utc", new DateTimeValue(DateTime.UtcNow)).Add("format", StringValue.Create("MMMM dd, yyyy")); + private static readonly FilterArguments _filterArguments = new FilterArguments() + .Add("utc", new DateTimeValue(DateTime.UtcNow)) + .Add("format", StringValue.Create("MMMM dd, yyyy")); private static readonly FluidValue _input = ObjectValue.Create(HtmlString.Empty, new TemplateOptions()); private static readonly LiquidFilterDelegateResolver _liquidFilterDelegateResolver; private static readonly IServiceProvider _serviceProvider; diff --git a/test/OrchardCore.Benchmarks/MediaTokenServiceBenchmark.cs b/test/OrchardCore.Benchmarks/MediaTokenServiceBenchmark.cs index 4676971ef6b..7af27ac0eb4 100644 --- a/test/OrchardCore.Benchmarks/MediaTokenServiceBenchmark.cs +++ b/test/OrchardCore.Benchmarks/MediaTokenServiceBenchmark.cs @@ -58,13 +58,17 @@ public string AddTokenToPath_NoCache() [Benchmark] public string AddTokenToPath_LongPath() { - return _mediaTokenService.AddTokenToPath("/media/portfolio/1.jpg?width=LOOOOOOOOOOOOOOONG&height=LOOOOOOOOOOOOOOONG&rmode=LOOOOOOOOOOOOOOONG&rxy=LOOOOOOOOOOOOOOONG&rsampler=LOOOOOOOOOOOOOOONG&ranchor=LOOOOOOOOOOOOOOONG&compand=LOOOOOOOOOOOOOOONG&token=LOOOOOOOOOOOOOOONG&quality=LOOOOOOOOOOOOOOONG"); + return _mediaTokenService.AddTokenToPath( + "/media/portfolio/1.jpg?width=LOOOOOOOOOOOOOOONG&height=LOOOOOOOOOOOOOOONG&rmode=LOOOOOOOOOOOOOOONG&rxy=LOOOOOOOOOOOOOOONG&rsampler=LOOOOOOOOOOOOOOONG&ranchor=LOOOOOOOOOOOOOOONG&compand=LOOOOOOOOOOOOOOONG&token=LOOOOOOOOOOOOOOONG&quality=LOOOOOOOOOOOOOOONG" + ); } [Benchmark] public string AddTokenToPath_LongPath_NoCache() { - return _mediaTokenServiceWithoutCache.AddTokenToPath("/media/portfolio/1.jpg?width=LOOOOOOOOOOOOOOONG&height=LOOOOOOOOOOOOOOONG&rmode=LOOOOOOOOOOOOOOONG&rxy=LOOOOOOOOOOOOOOONG&rsampler=LOOOOOOOOOOOOOOONG&ranchor=LOOOOOOOOOOOOOOONG&compand=LOOOOOOOOOOOOOOONG&token=LOOOOOOOOOOOOOOONG&quality=LOOOOOOOOOOOOOOONG"); + return _mediaTokenServiceWithoutCache.AddTokenToPath( + "/media/portfolio/1.jpg?width=LOOOOOOOOOOOOOOONG&height=LOOOOOOOOOOOOOOONG&rmode=LOOOOOOOOOOOOOOONG&rxy=LOOOOOOOOOOOOOOONG&rsampler=LOOOOOOOOOOOOOOONG&ranchor=LOOOOOOOOOOOOOOONG&compand=LOOOOOOOOOOOOOOONG&token=LOOOOOOOOOOOOOOONG&quality=LOOOOOOOOOOOOOOONG" + ); } #pragma warning restore CA1822 // Mark members as static } @@ -76,9 +80,7 @@ public ICacheEntry CreateEntry(object key) return new NullCacheEntry(); } - public void Remove(object key) - { - } + public void Remove(object key) { } public bool TryGetValue(object key, out object value) { @@ -86,9 +88,7 @@ public bool TryGetValue(object key, out object value) return false; } - public void Dispose() - { - } + public void Dispose() { } private sealed class NullCacheEntry : ICacheEntry { @@ -102,9 +102,7 @@ private sealed class NullCacheEntry : ICacheEntry public TimeSpan? SlidingExpiration { get; set; } public object Value { get; set; } - public void Dispose() - { - } + public void Dispose() { } } } } diff --git a/test/OrchardCore.Benchmarks/ResourceManagerBenchmark.cs b/test/OrchardCore.Benchmarks/ResourceManagerBenchmark.cs index 889878f420d..35e77b7e47d 100644 --- a/test/OrchardCore.Benchmarks/ResourceManagerBenchmark.cs +++ b/test/OrchardCore.Benchmarks/ResourceManagerBenchmark.cs @@ -11,10 +11,7 @@ namespace OrchardCore.Benchmark [MemoryDiagnoser] public class ResourceManagerBenchmark { - private static readonly ShellFileVersionProvider _fileVersionProvider = new( - [], - new FakeWebHostEnvironment(), - new MemoryCache(Options.Create(new MemoryCacheOptions()))); + private static readonly ShellFileVersionProvider _fileVersionProvider = new([], new FakeWebHostEnvironment(), new MemoryCache(Options.Create(new MemoryCacheOptions()))); private static readonly OptionsWrapper _options; @@ -46,9 +43,7 @@ static ResourceManagerBenchmark() public void RenderStylesheet() #pragma warning restore CA1822 // Mark members as static { - var manager = new ResourceManager( - options: _options, - fileVersionProvider: _fileVersionProvider); + var manager = new ResourceManager(options: _options, fileVersionProvider: _fileVersionProvider); manager.RegisterResource("stylesheet", "some1").UseVersion("1.0.0").ShouldAppendVersion(true); manager.RegisterResource("stylesheet", "some2").UseVersion("1.0.0").ShouldAppendVersion(true); diff --git a/test/OrchardCore.Benchmarks/RuleBenchmark.cs b/test/OrchardCore.Benchmarks/RuleBenchmark.cs index c6dfe844f39..d48cf84c1ef 100644 --- a/test/OrchardCore.Benchmarks/RuleBenchmark.cs +++ b/test/OrchardCore.Benchmarks/RuleBenchmark.cs @@ -25,7 +25,8 @@ public class RuleBenchmark static RuleBenchmark() { - var services = RuleTests.CreateRuleServiceCollection() + var services = RuleTests + .CreateRuleServiceCollection() .AddCondition>() .AddSingleton() .AddMemoryCache() @@ -47,16 +48,7 @@ static RuleBenchmark() _scope = _engine.CreateScope(scriptingManager.GlobalMethodProviders.SelectMany(x => x.GetMethods()), serviceProvider, null, null); _ruleService = serviceProvider.GetRequiredService(); - _rule = new Rule - { - Conditions = - [ - new HomepageCondition - { - Value = true - } - ] - }; + _rule = new Rule { Conditions = [new HomepageCondition { Value = true }] }; } // Summary 19th May 2021: dotnet run -c Release --filter *RuleBenchmark* --framework netcoreapp3.1 --job short diff --git a/test/OrchardCore.Benchmarks/ShapeFactoryBenchmark.cs b/test/OrchardCore.Benchmarks/ShapeFactoryBenchmark.cs index 0862be7b057..1a54ee9867f 100644 --- a/test/OrchardCore.Benchmarks/ShapeFactoryBenchmark.cs +++ b/test/OrchardCore.Benchmarks/ShapeFactoryBenchmark.cs @@ -19,24 +19,23 @@ namespace OrchardCore.Benchmark [MemoryDiagnoser] public class ShapeFactoryBenchmark { - private static readonly FilterArguments _filterArguments = new FilterArguments().Add("utc", new DateTimeValue(DateTime.UtcNow)).Add("format", StringValue.Create("MMMM dd, yyyy")); + private static readonly FilterArguments _filterArguments = new FilterArguments() + .Add("utc", new DateTimeValue(DateTime.UtcNow)) + .Add("format", StringValue.Create("MMMM dd, yyyy")); private static readonly FluidValue _input = StringValue.Create("DateTime"); private static readonly TemplateContext _templateContext; static ShapeFactoryBenchmark() { _templateContext = new TemplateContext(); - var defaultShapeTable = new ShapeTable - ( - [], - [] - ); + var defaultShapeTable = new ShapeTable([], []); var shapeFactory = new DefaultShapeFactory( serviceProvider: new ServiceCollection().BuildServiceProvider(), events: [], shapeTableManager: new TestShapeTableManager(defaultShapeTable), - themeManager: new MockThemeManager(new ExtensionInfo("path", new ManifestInfo(new ModuleAttribute()), (x, y) => []))); + themeManager: new MockThemeManager(new ExtensionInfo("path", new ManifestInfo(new ModuleAttribute()), (x, y) => [])) + ); _templateContext.AmbientValues["DisplayHelper"] = new DisplayHelper(null, shapeFactory, null); } @@ -50,7 +49,6 @@ public async Task OriginalShapeRender() await ShapeRenderOriginal(_input, _filterArguments, _templateContext); } - // [Benchmark] // public async Task NewShapeRender() // { diff --git a/test/OrchardCore.Benchmarks/SlugBenchmark.cs b/test/OrchardCore.Benchmarks/SlugBenchmark.cs index 72837069f65..dbc6ea3595d 100644 --- a/test/OrchardCore.Benchmarks/SlugBenchmark.cs +++ b/test/OrchardCore.Benchmarks/SlugBenchmark.cs @@ -25,7 +25,7 @@ static SlugBenchmark() * * Job=ShortRun IterationCount = 3 LaunchCount=1 * WarmupCount=3 - * + * * | Method | Mean | Error | StdDev | Gen 0 | Allocated | * |---------------- |---------:|----------:|----------:|-------:|----------:| * | EvaluateSlugify | 1.477 us | 0.5187 us | 0.0284 us | 0.2174 | 456 B | @@ -41,7 +41,9 @@ public void EvaluateSlugifyWithShortSlug() [Benchmark] public void EvaluateSlugifyWithLongSlug() { - _slugService.Slugify("Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne"); + _slugService.Slugify( + "Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne Je veux aller à Saint-Étienne" + ); } #pragma warning restore CA1822 // Mark members as static } diff --git a/test/OrchardCore.Tests.Features/Examples.Features.AssyAttrib/Root.cs b/test/OrchardCore.Tests.Features/Examples.Features.AssyAttrib/Root.cs index 57a1f12c467..be14a25ac25 100644 --- a/test/OrchardCore.Tests.Features/Examples.Features.AssyAttrib/Root.cs +++ b/test/OrchardCore.Tests.Features/Examples.Features.AssyAttrib/Root.cs @@ -3,7 +3,5 @@ namespace Examples.Features.AssyAttrib /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } diff --git a/test/OrchardCore.Tests.Modules/Errors.OrchardCoreModules.TwoPlus/Root.cs b/test/OrchardCore.Tests.Modules/Errors.OrchardCoreModules.TwoPlus/Root.cs index 90d603912bb..eef1675de55 100644 --- a/test/OrchardCore.Tests.Modules/Errors.OrchardCoreModules.TwoPlus/Root.cs +++ b/test/OrchardCore.Tests.Modules/Errors.OrchardCoreModules.TwoPlus/Root.cs @@ -4,9 +4,7 @@ namespace Errors.OrchardCoreModules.TwoPlus /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } // TODO: MWP: would be better if perhaps we could verify a BUILD cycle from code // TODO: MWP: but this would also require a bit of xUnit scaffold to support diff --git a/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Alpha/Root.cs b/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Alpha/Root.cs index ad64f9c972b..f9682a353b0 100644 --- a/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Alpha/Root.cs +++ b/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Alpha/Root.cs @@ -3,7 +3,5 @@ namespace Examples.Modules.AssyAttrib.Alpha /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } diff --git a/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Bravo/Root.cs b/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Bravo/Root.cs index 89de88f5bfa..5d8b41e0e2a 100644 --- a/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Bravo/Root.cs +++ b/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Bravo/Root.cs @@ -3,7 +3,5 @@ namespace Examples.Modules.AssyAttrib.Bravo /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } diff --git a/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Charlie/Root.cs b/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Charlie/Root.cs index 62ab0e968be..33bee10d766 100644 --- a/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Charlie/Root.cs +++ b/test/OrchardCore.Tests.Modules/Examples.Modules.AssyAttrib.Charlie/Root.cs @@ -3,7 +3,5 @@ namespace Examples.Modules.AssyAttrib.Charlie /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } diff --git a/test/OrchardCore.Tests.Modules/Examples.OrchardCoreModules.Alpha/Root.cs b/test/OrchardCore.Tests.Modules/Examples.OrchardCoreModules.Alpha/Root.cs index 254e8984bac..910da0435ef 100644 --- a/test/OrchardCore.Tests.Modules/Examples.OrchardCoreModules.Alpha/Root.cs +++ b/test/OrchardCore.Tests.Modules/Examples.OrchardCoreModules.Alpha/Root.cs @@ -3,7 +3,5 @@ namespace Examples.OrchardCoreModules.Alpha /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } diff --git a/test/OrchardCore.Tests.Modules/ModuleSample/Manifest.cs b/test/OrchardCore.Tests.Modules/ModuleSample/Manifest.cs index 0fe41d36658..c8632e53a91 100644 --- a/test/OrchardCore.Tests.Modules/ModuleSample/Manifest.cs +++ b/test/OrchardCore.Tests.Modules/ModuleSample/Manifest.cs @@ -8,30 +8,10 @@ Category = "Test" )] -[assembly: Feature( - Id = "Sample1", - Name = "Sample 1", - Description = "Feature with no dependencies.", - Dependencies = new string[0] -)] +[assembly: Feature(Id = "Sample1", Name = "Sample 1", Description = "Feature with no dependencies.", Dependencies = new string[0])] -[assembly: Feature( - Id = "Sample2", - Name = "Sample 2", - Description = "Module with dependency one sample 1.", - Dependencies = ["Sample1"] -)] +[assembly: Feature(Id = "Sample2", Name = "Sample 2", Description = "Module with dependency one sample 1.", Dependencies = ["Sample1"])] -[assembly: Feature( - Id = "Sample3", - Name = "Sample 3", - Description = "Module with dependency one sample 2.", - Dependencies = ["Sample2"] -)] +[assembly: Feature(Id = "Sample3", Name = "Sample 3", Description = "Module with dependency one sample 2.", Dependencies = ["Sample2"])] -[assembly: Feature( - Id = "Sample4", - Name = "Sample 4", - Description = "Module with dependency one sample 2.", - Dependencies = ["Sample2"] -)] +[assembly: Feature(Id = "Sample4", Name = "Sample 4", Description = "Module with dependency one sample 2.", Dependencies = ["Sample2"])] diff --git a/test/OrchardCore.Tests.Pages/OrchardCore.Themes.Pages/Theme.Pages/PlaceHolder.cs b/test/OrchardCore.Tests.Pages/OrchardCore.Themes.Pages/Theme.Pages/PlaceHolder.cs index e402868238f..4f3e2f9611b 100644 --- a/test/OrchardCore.Tests.Pages/OrchardCore.Themes.Pages/Theme.Pages/PlaceHolder.cs +++ b/test/OrchardCore.Tests.Pages/OrchardCore.Themes.Pages/Theme.Pages/PlaceHolder.cs @@ -1,7 +1,5 @@ namespace Theme.Pages { // Just a class so that an assembly gets created - public class Placeholder - { - } + public class Placeholder { } } diff --git a/test/OrchardCore.Tests.Themes/Errors.OrchardCoreThemes.ThemeAndModule/Root.cs b/test/OrchardCore.Tests.Themes/Errors.OrchardCoreThemes.ThemeAndModule/Root.cs index 4723f33be55..5ea7e8e4bba 100644 --- a/test/OrchardCore.Tests.Themes/Errors.OrchardCoreThemes.ThemeAndModule/Root.cs +++ b/test/OrchardCore.Tests.Themes/Errors.OrchardCoreThemes.ThemeAndModule/Root.cs @@ -4,9 +4,7 @@ namespace Errors.OrchardCoreThemes.ThemeAndModule /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } // TODO: MWP: would be better if perhaps we could verify a BUILD cycle from code // TODO: MWP: but this would also require a bit of xUnit scaffold to support diff --git a/test/OrchardCore.Tests.Themes/Errors.OrchardCoreThemes.TwoPlus/Root.cs b/test/OrchardCore.Tests.Themes/Errors.OrchardCoreThemes.TwoPlus/Root.cs index c5398485372..4540189fe7d 100644 --- a/test/OrchardCore.Tests.Themes/Errors.OrchardCoreThemes.TwoPlus/Root.cs +++ b/test/OrchardCore.Tests.Themes/Errors.OrchardCoreThemes.TwoPlus/Root.cs @@ -4,9 +4,7 @@ namespace Errors.OrchardCoreThemes.TwoPlus /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } // TODO: MWP: would be better if perhaps we could verify a BUILD cycle from code // TODO: MWP: but this would also require a bit of xUnit scaffold to support diff --git a/test/OrchardCore.Tests.Themes/Examples.OrchardCoreThemes.Alpha/Root.cs b/test/OrchardCore.Tests.Themes/Examples.OrchardCoreThemes.Alpha/Root.cs index 458a55ed596..05fdbba93c2 100644 --- a/test/OrchardCore.Tests.Themes/Examples.OrchardCoreThemes.Alpha/Root.cs +++ b/test/OrchardCore.Tests.Themes/Examples.OrchardCoreThemes.Alpha/Root.cs @@ -3,7 +3,5 @@ namespace Examples.OrchardCoreThemes.Alpha /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } diff --git a/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Alpha/Root.cs b/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Alpha/Root.cs index e50b306d9c1..c23151627c5 100644 --- a/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Alpha/Root.cs +++ b/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Alpha/Root.cs @@ -3,7 +3,5 @@ namespace Examples.Themes.AssyAttrib.Alpha /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } diff --git a/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Bravo/Root.cs b/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Bravo/Root.cs index 106aa26ca01..4b8e0efbf7c 100644 --- a/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Bravo/Root.cs +++ b/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Bravo/Root.cs @@ -3,7 +3,5 @@ namespace Examples.Themes.AssyAttrib.Bravo /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } diff --git a/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Charlie/Root.cs b/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Charlie/Root.cs index 3bdf48abc93..5dbb13b2ecd 100644 --- a/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Charlie/Root.cs +++ b/test/OrchardCore.Tests.Themes/Examples.Themes.AssyAttrib.Charlie/Root.cs @@ -3,7 +3,5 @@ namespace Examples.Themes.AssyAttrib.Charlie /// /// Hooks provided for purposes of identifying the class and assembly context. /// - internal class Root - { - } + internal class Root { } } diff --git a/test/OrchardCore.Tests/Apis/ContentManagement/ContentApiController/BlogPostApiControllerTests.cs b/test/OrchardCore.Tests/Apis/ContentManagement/ContentApiController/BlogPostApiControllerTests.cs index ca0181cb5f0..004a1c0c62e 100644 --- a/test/OrchardCore.Tests/Apis/ContentManagement/ContentApiController/BlogPostApiControllerTests.cs +++ b/test/OrchardCore.Tests/Apis/ContentManagement/ContentApiController/BlogPostApiControllerTests.cs @@ -68,8 +68,7 @@ public async Task ShouldOnlyCreateTwoContentItemRecordsForExistingContentItem() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPosts = await session.Query(x => - x.ContentType == "BlogPost").ListAsync(); + var blogPosts = await session.Query(x => x.ContentType == "BlogPost").ListAsync(); Assert.Equal(2, blogPosts.Count()); }); @@ -92,33 +91,16 @@ public async Task ShouldCreateDraftOfNewContentItem() Published = true, // Deliberately set these values incorrectly. }; - contentItem - .Weld(new AutoroutePart - { - Path = "Path2", - }); + contentItem.Weld(new AutoroutePart { Path = "Path2", }); - contentItem - .Weld(new ContainedPart - { - ListContentItemId = context.BlogContentItemId - }); + contentItem.Weld(new ContainedPart { ListContentItemId = context.BlogContentItemId }); var blogFields = new ContentPart(); - blogFields - .Weld("Categories", new TaxonomyField - { - TaxonomyContentItemId = context.CategoriesTaxonomyContentItemId, - }); + blogFields.Weld("Categories", new TaxonomyField { TaxonomyContentItemId = context.CategoriesTaxonomyContentItemId, }); - blogFields - .Weld("Tags", new TaxonomyField - { - TaxonomyContentItemId = context.TagsTaxonomyContentItemId, - }); + blogFields.Weld("Tags", new TaxonomyField { TaxonomyContentItemId = context.TagsTaxonomyContentItemId, }); - contentItem - .Weld("BlogPost", blogFields); + contentItem.Weld("BlogPost", blogFields); // Act var content = await context.Client.PostAsJsonAsync("api/content?draft=true", contentItem); @@ -149,33 +131,16 @@ public async Task ShouldCreateAndPublishNewContentItem() Published = false, // Deliberately set these values incorrectly. }; - contentItem - .Weld(new AutoroutePart - { - Path = path, - }); + contentItem.Weld(new AutoroutePart { Path = path, }); - contentItem - .Weld(new ContainedPart - { - ListContentItemId = context.BlogContentItemId, - }); + contentItem.Weld(new ContainedPart { ListContentItemId = context.BlogContentItemId, }); var blogFields = new ContentPart(); - blogFields - .Weld("Categories", new TaxonomyField - { - TaxonomyContentItemId = context.CategoriesTaxonomyContentItemId, - }); + blogFields.Weld("Categories", new TaxonomyField { TaxonomyContentItemId = context.CategoriesTaxonomyContentItemId, }); - blogFields - .Weld("Tags", new TaxonomyField - { - TaxonomyContentItemId = context.TagsTaxonomyContentItemId, - }); + blogFields.Weld("Tags", new TaxonomyField { TaxonomyContentItemId = context.TagsTaxonomyContentItemId, }); - contentItem - .Weld("BlogPost", blogFields); + contentItem.Weld("BlogPost", blogFields); // Act var content = await context.Client.PostAsJsonAsync("api/content", contentItem); @@ -204,33 +169,21 @@ public async Task ShouldFailValidationWhenAutoroutePathIsNotUnique() Published = false, // Deliberately set these values incorrectly. }; - contentItem - .Weld(new AutoroutePart + contentItem.Weld( + new AutoroutePart { Path = "blog/post-1", // Deliberately set to an existing path. - }); + } + ); - contentItem - .Weld(new ContainedPart - { - ListContentItemId = context.BlogContentItemId, - }); + contentItem.Weld(new ContainedPart { ListContentItemId = context.BlogContentItemId, }); var blogFields = new ContentPart(); - blogFields - .Weld("Categories", new TaxonomyField - { - TaxonomyContentItemId = context.CategoriesTaxonomyContentItemId, - }); + blogFields.Weld("Categories", new TaxonomyField { TaxonomyContentItemId = context.CategoriesTaxonomyContentItemId, }); - blogFields - .Weld("Tags", new TaxonomyField - { - TaxonomyContentItemId = context.TagsTaxonomyContentItemId, - }); + blogFields.Weld("Tags", new TaxonomyField { TaxonomyContentItemId = context.TagsTaxonomyContentItemId, }); - contentItem - .Weld("BlogPost", blogFields); + contentItem.Weld("BlogPost", blogFields); // Act var result = await context.Client.PostAsJsonAsync("api/content", contentItem); @@ -243,8 +196,7 @@ public async Task ShouldFailValidationWhenAutoroutePathIsNotUnique() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPosts = await session.Query(x => - x.ContentType == "BlogPost").ListAsync(); + var blogPosts = await session.Query(x => x.ContentType == "BlogPost").ListAsync(); Assert.Single(blogPosts); }); @@ -266,38 +218,21 @@ public async Task ShouldGenerateUniqueAutoroutePath() Published = false, // Deliberately set these values incorrectly. }; - contentItem - .Weld(new ContainedPart - { - ListContentItemId = context.BlogContentItemId, - }); + contentItem.Weld(new ContainedPart { ListContentItemId = context.BlogContentItemId, }); var blogFields = new ContentPart(); - blogFields - .Weld("Categories", new TaxonomyField - { - TaxonomyContentItemId = context.CategoriesTaxonomyContentItemId, - }); + blogFields.Weld("Categories", new TaxonomyField { TaxonomyContentItemId = context.CategoriesTaxonomyContentItemId, }); - blogFields - .Weld("Tags", new TaxonomyField - { - TaxonomyContentItemId = context.TagsTaxonomyContentItemId, - }); + blogFields.Weld("Tags", new TaxonomyField { TaxonomyContentItemId = context.TagsTaxonomyContentItemId, }); - contentItem - .Weld("BlogPost", blogFields); + contentItem.Weld("BlogPost", blogFields); // Act var content = await context.Client.PostAsJsonAsync("api/content", contentItem); var publishedContentItem = await content.Content.ReadAsAsync(); // Test - var blogPostContentItemIds = new List - { - context.BlogPost.ContentItemId, - publishedContentItem.ContentItemId, - }; + var blogPostContentItemIds = new List { context.BlogPost.ContentItemId, publishedContentItem.ContentItemId, }; await context.UsingTenantScopeAsync(async scope => { diff --git a/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostContentStepIdempotentTests.cs b/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostContentStepIdempotentTests.cs index 9e464944ad5..aa8cb9426cd 100644 --- a/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostContentStepIdempotentTests.cs +++ b/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostContentStepIdempotentTests.cs @@ -16,11 +16,14 @@ public async Task ShouldProduceSameOutcomeForNewContentOnMultipleExecutions() await context.InitializeAsync(); // Act - var recipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => - { - jItem[nameof(ContentItem.ContentItemVersionId)] = "newversion"; - jItem[nameof(ContentItem.DisplayText)] = "new version"; - }); + var recipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => + { + jItem[nameof(ContentItem.ContentItemVersionId)] = "newversion"; + jItem[nameof(ContentItem.DisplayText)] = "new version"; + } + ); for (var i = 0; i < 2; i++) { @@ -30,8 +33,7 @@ public async Task ShouldProduceSameOutcomeForNewContentOnMultipleExecutions() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPosts = await session.Query(x => - x.ContentType == "BlogPost").ListAsync(); + var blogPosts = await session.Query(x => x.ContentType == "BlogPost").ListAsync(); Assert.Equal(2, blogPosts.Count()); @@ -56,10 +58,13 @@ public async Task ShouldProduceSameOutcomeForExistingContentItemVersionOnMultipl await context.InitializeAsync(); // Act - var recipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => - { - jItem[nameof(ContentItem.DisplayText)] = "existing version mutated"; - }); + var recipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => + { + jItem[nameof(ContentItem.DisplayText)] = "existing version mutated"; + } + ); for (var i = 0; i < 2; i++) { @@ -69,8 +74,7 @@ public async Task ShouldProduceSameOutcomeForExistingContentItemVersionOnMultipl await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPosts = await session.Query(x => - x.ContentType == "BlogPost").ListAsync(); + var blogPosts = await session.Query(x => x.ContentType == "BlogPost").ListAsync(); Assert.Single(blogPosts); var mutatedVersion = blogPosts.FirstOrDefault(x => x.ContentItemVersionId == context.OriginalBlogPostVersionId); @@ -78,6 +82,5 @@ await context.UsingTenantScopeAsync(async scope => }); } } - } } diff --git a/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostCreateDeploymentPlanTests.cs b/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostCreateDeploymentPlanTests.cs index 7fc2d37872f..0f7b4b3b105 100644 --- a/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostCreateDeploymentPlanTests.cs +++ b/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostCreateDeploymentPlanTests.cs @@ -18,11 +18,14 @@ public async Task ShouldCreateNewPublishedContentItemVersion() await context.InitializeAsync(); // Act - var recipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => - { - jItem[nameof(ContentItem.ContentItemVersionId)] = "newversion"; - jItem[nameof(ContentItem.DisplayText)] = "new version"; - }); + var recipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => + { + jItem[nameof(ContentItem.ContentItemVersionId)] = "newversion"; + jItem[nameof(ContentItem.DisplayText)] = "new version"; + } + ); await context.PostRecipeAsync(recipe); @@ -30,8 +33,7 @@ public async Task ShouldCreateNewPublishedContentItemVersion() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPosts = await session.Query(x => - x.ContentType == "BlogPost").ListAsync(); + var blogPosts = await session.Query(x => x.ContentType == "BlogPost").ListAsync(); Assert.Equal(2, blogPosts.Count()); @@ -58,11 +60,14 @@ public async Task ShouldDiscardDraftThenCreateNewPublishedContentItemVersion() var draftContentItemVersionId = (await content.Content.ReadAsAsync()).ContentItemVersionId; // Act - var recipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => + var recipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => { jItem[nameof(ContentItem.ContentItemVersionId)] = "newversion"; jItem[nameof(ContentItem.DisplayText)] = "new version"; - }); + } + ); await context.PostRecipeAsync(recipe); @@ -70,8 +75,7 @@ public async Task ShouldDiscardDraftThenCreateNewPublishedContentItemVersion() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPosts = await session.Query(x => - x.ContentType == "BlogPost").ListAsync(); + var blogPosts = await session.Query(x => x.ContentType == "BlogPost").ListAsync(); Assert.Equal(3, blogPosts.Count()); var originalVersion = blogPosts.FirstOrDefault(x => x.ContentItemVersionId == context.OriginalBlogPostVersionId); @@ -101,12 +105,15 @@ public async Task ShouldDiscardDraftThenCreateNewDraftContentItemVersion() var draftContentItemVersionId = (await content.Content.ReadAsAsync()).ContentItemVersionId; // Act - var recipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => - { - jItem[nameof(ContentItem.ContentItemVersionId)] = "newdraftversion"; - jItem[nameof(ContentItem.DisplayText)] = "new draft version"; - jItem[nameof(ContentItem.Published)] = false; - }); + var recipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => + { + jItem[nameof(ContentItem.ContentItemVersionId)] = "newdraftversion"; + jItem[nameof(ContentItem.DisplayText)] = "new draft version"; + jItem[nameof(ContentItem.Published)] = false; + } + ); await context.PostRecipeAsync(recipe); @@ -114,8 +121,7 @@ public async Task ShouldDiscardDraftThenCreateNewDraftContentItemVersion() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPosts = await session.Query(x => - x.ContentType == "BlogPost").ListAsync(); + var blogPosts = await session.Query(x => x.ContentType == "BlogPost").ListAsync(); Assert.Equal(3, blogPosts.Count()); @@ -143,13 +149,16 @@ public async Task ShouldCreateNewPublishedContentItem() await context.InitializeAsync(); // Act - var recipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => - { - jItem[nameof(ContentItem.ContentItemId)] = "newcontentitemid"; - jItem[nameof(ContentItem.ContentItemVersionId)] = "newversion"; - jItem[nameof(ContentItem.DisplayText)] = "new version"; - jItem[nameof(AutoroutePart)][nameof(AutoroutePart.Path)] = "blog/another"; - }); + var recipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => + { + jItem[nameof(ContentItem.ContentItemId)] = "newcontentitemid"; + jItem[nameof(ContentItem.ContentItemVersionId)] = "newversion"; + jItem[nameof(ContentItem.DisplayText)] = "new version"; + jItem[nameof(AutoroutePart)][nameof(AutoroutePart.Path)] = "blog/another"; + } + ); await context.PostRecipeAsync(recipe); @@ -157,8 +166,7 @@ public async Task ShouldCreateNewPublishedContentItem() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPostsCount = await session.Query(x => - x.ContentType == "BlogPost").CountAsync(); + var blogPostsCount = await session.Query(x => x.ContentType == "BlogPost").CountAsync(); Assert.Equal(2, blogPostsCount); }); @@ -173,21 +181,27 @@ public async Task ShouldIgnoreDuplicateContentItems() await context.InitializeAsync(); // Create a recipe with two content items and the same version id. - var firstRecipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => - { - jItem[nameof(ContentItem.ContentItemId)] = "newcontentitemid"; - jItem[nameof(ContentItem.ContentItemVersionId)] = "dupversion"; - jItem[nameof(ContentItem.DisplayText)] = "duplicate version"; - jItem[nameof(AutoroutePart)][nameof(AutoroutePart.Path)] = "blog/another"; - }); - - var secondRecipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => - { - jItem[nameof(ContentItem.ContentItemId)] = "newcontentitemid"; - jItem[nameof(ContentItem.ContentItemVersionId)] = "dupversion"; - jItem[nameof(ContentItem.DisplayText)] = "duplicate version"; - jItem[nameof(AutoroutePart)][nameof(AutoroutePart.Path)] = "blog/another"; - }); + var firstRecipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => + { + jItem[nameof(ContentItem.ContentItemId)] = "newcontentitemid"; + jItem[nameof(ContentItem.ContentItemVersionId)] = "dupversion"; + jItem[nameof(ContentItem.DisplayText)] = "duplicate version"; + jItem[nameof(AutoroutePart)][nameof(AutoroutePart.Path)] = "blog/another"; + } + ); + + var secondRecipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => + { + jItem[nameof(ContentItem.ContentItemId)] = "newcontentitemid"; + jItem[nameof(ContentItem.ContentItemVersionId)] = "dupversion"; + jItem[nameof(ContentItem.DisplayText)] = "duplicate version"; + jItem[nameof(AutoroutePart)][nameof(AutoroutePart.Path)] = "blog/another"; + } + ); var firstRecipeData = firstRecipe.SelectNode("steps[0].Data").AsArray(); @@ -201,8 +215,7 @@ public async Task ShouldIgnoreDuplicateContentItems() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPostsCount = await session.Query(x => - x.ContentType == "BlogPost" && x.ContentItemVersionId == "dupversion").CountAsync(); + var blogPostsCount = await session.Query(x => x.ContentType == "BlogPost" && x.ContentItemVersionId == "dupversion").CountAsync(); Assert.Equal(1, blogPostsCount); }); diff --git a/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostUpdateDeploymentPlanTests.cs b/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostUpdateDeploymentPlanTests.cs index 81c8c979f69..cfe00ec52ea 100644 --- a/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostUpdateDeploymentPlanTests.cs +++ b/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/BlogPostUpdateDeploymentPlanTests.cs @@ -16,10 +16,13 @@ public async Task ShouldUpdateExistingContentItemVersion() await context.InitializeAsync(); // Act - var recipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => - { - jItem[nameof(ContentItem.DisplayText)] = "existing version mutated"; - }); + var recipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => + { + jItem[nameof(ContentItem.DisplayText)] = "existing version mutated"; + } + ); await context.PostRecipeAsync(recipe); @@ -27,8 +30,7 @@ public async Task ShouldUpdateExistingContentItemVersion() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPosts = await session.Query(x => - x.ContentType == "BlogPost").ListAsync(); + var blogPosts = await session.Query(x => x.ContentType == "BlogPost").ListAsync(); Assert.Single(blogPosts); var mutatedVersion = blogPosts.FirstOrDefault(x => x.ContentItemVersionId == context.OriginalBlogPostVersionId); @@ -48,10 +50,13 @@ public async Task ShouldDiscardDraftThenUpdateExistingContentItemVersion() var draftContentItemVersionId = (await content.Content.ReadAsAsync()).ContentItemVersionId; // Act - var recipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => - { - jItem[nameof(ContentItem.DisplayText)] = "existing version mutated"; - }); + var recipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => + { + jItem[nameof(ContentItem.DisplayText)] = "existing version mutated"; + } + ); await context.PostRecipeAsync(recipe); @@ -59,8 +64,7 @@ public async Task ShouldDiscardDraftThenUpdateExistingContentItemVersion() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPosts = await session.Query(x => - x.ContentType == "BlogPost").ListAsync(); + var blogPosts = await session.Query(x => x.ContentType == "BlogPost").ListAsync(); Assert.Equal(2, blogPosts.Count()); @@ -86,12 +90,15 @@ public async Task ShouldUpdateDraftThenPublishExistingContentItemVersion() var draftContentItem = (await content.Content.ReadAsAsync()); // Act - var recipe = BlogPostDeploymentContext.GetContentStepRecipe(draftContentItem, jItem => - { - jItem[nameof(ContentItem.DisplayText)] = "draft version mutated"; - jItem[nameof(ContentItem.Published)] = true; - jItem[nameof(ContentItem.Latest)] = true; - }); + var recipe = BlogPostDeploymentContext.GetContentStepRecipe( + draftContentItem, + jItem => + { + jItem[nameof(ContentItem.DisplayText)] = "draft version mutated"; + jItem[nameof(ContentItem.Published)] = true; + jItem[nameof(ContentItem.Latest)] = true; + } + ); await context.PostRecipeAsync(recipe); @@ -99,8 +106,7 @@ public async Task ShouldUpdateDraftThenPublishExistingContentItemVersion() await context.UsingTenantScopeAsync(async scope => { var session = scope.ServiceProvider.GetRequiredService(); - var blogPosts = await session.Query(x => - x.ContentType == "BlogPost").ListAsync(); + var blogPosts = await session.Query(x => x.ContentType == "BlogPost").ListAsync(); Assert.Equal(2, blogPosts.Count()); diff --git a/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/ContentStepLuceneQueryTests.cs b/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/ContentStepLuceneQueryTests.cs index c07bdebe3df..35b0f2f3659 100644 --- a/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/ContentStepLuceneQueryTests.cs +++ b/test/OrchardCore.Tests/Apis/ContentManagement/DeploymentPlans/ContentStepLuceneQueryTests.cs @@ -16,11 +16,14 @@ public async Task ShouldUpdateLuceneIndexesOnImport() await context.InitializeAsync(); // Act - var recipe = BlogPostDeploymentContext.GetContentStepRecipe(context.OriginalBlogPost, jItem => - { - jItem[nameof(ContentItem.ContentItemVersionId)] = "newVersion"; - jItem[nameof(ContentItem.DisplayText)] = "new version"; - }); + var recipe = BlogPostDeploymentContext.GetContentStepRecipe( + context.OriginalBlogPost, + jItem => + { + jItem[nameof(ContentItem.ContentItemVersionId)] = "newVersion"; + jItem[nameof(ContentItem.DisplayText)] = "new version"; + } + ); // Create a second content item in the recipe data so we can confirm the behaviour // of the LuceneIndexingContentHandler. @@ -35,14 +38,13 @@ public async Task ShouldUpdateLuceneIndexesOnImport() await context.PostRecipeAsync(recipe); // Test - var result = await context - .GraphQLClient - .Content - .Query("RecentBlogPosts", builder => + var result = await context.GraphQLClient.Content.Query( + "RecentBlogPosts", + builder => { - builder - .WithField("displayText"); - }); + builder.WithField("displayText"); + } + ); var nodes = result["data"]["recentBlogPosts"]; diff --git a/test/OrchardCore.Tests/Apis/Context/AgencyContext.cs b/test/OrchardCore.Tests/Apis/Context/AgencyContext.cs index e0bf460b3f8..ea4d16137d3 100644 --- a/test/OrchardCore.Tests/Apis/Context/AgencyContext.cs +++ b/test/OrchardCore.Tests/Apis/Context/AgencyContext.cs @@ -2,9 +2,7 @@ namespace OrchardCore.Tests.Apis.Context { public class AgencyContext : SiteContext { - static AgencyContext() - { - } + static AgencyContext() { } public AgencyContext() { diff --git a/test/OrchardCore.Tests/Apis/Context/AuthenticationContext.cs b/test/OrchardCore.Tests/Apis/Context/AuthenticationContext.cs index a28a2e71204..feac4e0efc6 100644 --- a/test/OrchardCore.Tests/Apis/Context/AuthenticationContext.cs +++ b/test/OrchardCore.Tests/Apis/Context/AuthenticationContext.cs @@ -19,8 +19,10 @@ public PermissionContextAuthorizationHandler(IHttpContextAccessor httpContextAcc var requestContext = httpContextAccessor.HttpContext.Request; - if (requestContext?.Headers.ContainsKey("PermissionsContext") == true && - permissionsContexts.TryGetValue(requestContext.Headers["PermissionsContext"], out var permissionsContext)) + if ( + requestContext?.Headers.ContainsKey("PermissionsContext") == true + && permissionsContexts.TryGetValue(requestContext.Headers["PermissionsContext"], out var permissionsContext) + ) { _permissionsContext = permissionsContext; } diff --git a/test/OrchardCore.Tests/Apis/Context/BlogContext.cs b/test/OrchardCore.Tests/Apis/Context/BlogContext.cs index f93dcc10314..f1ec5e65f6f 100644 --- a/test/OrchardCore.Tests/Apis/Context/BlogContext.cs +++ b/test/OrchardCore.Tests/Apis/Context/BlogContext.cs @@ -10,9 +10,7 @@ public class BlogContext : SiteContext public string BlogContentItemId { get; private set; } - static BlogContext() - { - } + static BlogContext() { } public override async Task InitializeAsync() { @@ -20,13 +18,13 @@ public override async Task InitializeAsync() await RunRecipeAsync(luceneRecipeName, luceneRecipePath); await ResetLuceneIndiciesAsync(luceneIndexName); - var result = await GraphQLClient - .Content - .Query("blog", builder => + var result = await GraphQLClient.Content.Query( + "blog", + builder => { - builder - .WithField("contentItemId"); - }); + builder.WithField("contentItemId"); + } + ); BlogContentItemId = result["data"]["blog"][0]["contentItemId"].ToString(); } diff --git a/test/OrchardCore.Tests/Apis/Context/BlogPostApiControllerContext.cs b/test/OrchardCore.Tests/Apis/Context/BlogPostApiControllerContext.cs index 45e4e1d6c57..cafcd8c212d 100644 --- a/test/OrchardCore.Tests/Apis/Context/BlogPostApiControllerContext.cs +++ b/test/OrchardCore.Tests/Apis/Context/BlogPostApiControllerContext.cs @@ -10,20 +10,16 @@ public class BlogPostApiControllerContext : SiteContext public string CategoriesTaxonomyContentItemId { get; private set; } public string TagsTaxonomyContentItemId { get; private set; } - static BlogPostApiControllerContext() - { - } + static BlogPostApiControllerContext() { } public override async Task InitializeAsync() { await base.InitializeAsync(); - var body = new ContentTypeQueryResourceBuilder("blogPost") - .WithField("contentItemId").Build() + - new ContentTypeQueryResourceBuilder("blog") - .WithField("contentItemId").Build() + - new ContentTypeQueryResourceBuilder("taxonomy") - .WithField("contentItemId").Build(); + var body = + new ContentTypeQueryResourceBuilder("blogPost").WithField("contentItemId").Build() + + new ContentTypeQueryResourceBuilder("blog").WithField("contentItemId").Build() + + new ContentTypeQueryResourceBuilder("taxonomy").WithField("contentItemId").Build(); var result = await GraphQLClient.Content.Query(body); diff --git a/test/OrchardCore.Tests/Apis/Context/BlogPostDeploymentContext.cs b/test/OrchardCore.Tests/Apis/Context/BlogPostDeploymentContext.cs index a70f524020f..32d30ec7c15 100644 --- a/test/OrchardCore.Tests/Apis/Context/BlogPostDeploymentContext.cs +++ b/test/OrchardCore.Tests/Apis/Context/BlogPostDeploymentContext.cs @@ -14,22 +14,20 @@ public class BlogPostDeploymentContext : SiteContext public ContentItem OriginalBlogPost { get; private set; } public string OriginalBlogPostVersionId { get; private set; } - static BlogPostDeploymentContext() - { - } + static BlogPostDeploymentContext() { } public override async Task InitializeAsync() { await base.InitializeAsync(); await RunRecipeAsync(BlogContext.luceneRecipeName, BlogContext.luceneRecipePath); - var result = await GraphQLClient - .Content - .Query("blogPost", builder => + var result = await GraphQLClient.Content.Query( + "blogPost", + builder => { - builder - .WithField("contentItemId"); - }); + builder.WithField("contentItemId"); + } + ); BlogPostContentItemId = result["data"]["blogPost"][0]["contentItemId"].ToString(); diff --git a/test/OrchardCore.Tests/Apis/Context/Extensions/HttpContentExtensions.cs b/test/OrchardCore.Tests/Apis/Context/Extensions/HttpContentExtensions.cs index 9db2c945bf6..3fcdc866dee 100644 --- a/test/OrchardCore.Tests/Apis/Context/Extensions/HttpContentExtensions.cs +++ b/test/OrchardCore.Tests/Apis/Context/Extensions/HttpContentExtensions.cs @@ -10,7 +10,6 @@ public static async Task ReadAsAsync(this HttpContent content) return await data.ReadAsAsync(); } - public static ValueTask ReadAsAsync(this Stream stream) => - JsonSerializer.DeserializeAsync(stream, JOptions.Default); + public static ValueTask ReadAsAsync(this Stream stream) => JsonSerializer.DeserializeAsync(stream, JOptions.Default); } } diff --git a/test/OrchardCore.Tests/Apis/Context/Extensions/HttpRequestExtensions.cs b/test/OrchardCore.Tests/Apis/Context/Extensions/HttpRequestExtensions.cs index b8af0735c68..165c1498b12 100644 --- a/test/OrchardCore.Tests/Apis/Context/Extensions/HttpRequestExtensions.cs +++ b/test/OrchardCore.Tests/Apis/Context/Extensions/HttpRequestExtensions.cs @@ -27,16 +27,9 @@ internal static class HttpRequestExtensions /// /// The . /// - public static Task PatchAsJsonAsync( - this HttpClient client, - string requestUri, - T value, - JsonSerializerOptions options = null) + public static Task PatchAsJsonAsync(this HttpClient client, string requestUri, T value, JsonSerializerOptions options = null) { - var content = new StringContent( - JConvert.SerializeObject(value, options), - Encoding.UTF8, - "application/json"); + var content = new StringContent(JConvert.SerializeObject(value, options), Encoding.UTF8, "application/json"); return PatchAsync(client, requestUri, content); } @@ -56,10 +49,7 @@ public static Task PatchAsJsonAsync( /// /// The . /// - public static Task PatchAsync( - this HttpClient client, - string requestUri, - HttpContent content) + public static Task PatchAsync(this HttpClient client, string requestUri, HttpContent content) { var request = new HttpRequestMessage { @@ -92,16 +82,9 @@ public static Task PatchAsync( /// /// The . /// - public static Task PutAsJsonAsync( - this HttpClient client, - string requestUri, - T value, - JsonSerializerOptions options = null) + public static Task PutAsJsonAsync(this HttpClient client, string requestUri, T value, JsonSerializerOptions options = null) { - var content = new StringContent( - JConvert.SerializeObject(value, options), - Encoding.UTF8, - "application/json"); + var content = new StringContent(JConvert.SerializeObject(value, options), Encoding.UTF8, "application/json"); return client.PutAsync(requestUri, content); } @@ -126,69 +109,35 @@ public static Task PutAsJsonAsync( /// /// The . /// - public static Task PostAsJsonAsync( - this HttpClient client, - string requestUri, - T value, - JsonSerializerOptions options = null) + public static Task PostAsJsonAsync(this HttpClient client, string requestUri, T value, JsonSerializerOptions options = null) { - var content = new StringContent( - JConvert.SerializeObject(value, options), - Encoding.UTF8, - "application/json"); + var content = new StringContent(JConvert.SerializeObject(value, options), Encoding.UTF8, "application/json"); - var request = new HttpRequestMessage(HttpMethod.Post, requestUri) - { - Content = content, - }; + var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content, }; - request.Headers - .Accept - .Add(new MediaTypeWithQualityHeaderValue("application/json")); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client.SendAsync(request); } - public static Task PostJsonAsync( - this HttpClient client, - string requestUri, - string json) + public static Task PostJsonAsync(this HttpClient client, string requestUri, string json) { - var content = new StringContent( - json, - Encoding.UTF8, - "application/json"); + var content = new StringContent(json, Encoding.UTF8, "application/json"); - var request = new HttpRequestMessage(HttpMethod.Post, requestUri) - { - Content = content, - }; + var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content, }; - request.Headers - .Accept - .Add(new MediaTypeWithQualityHeaderValue("application/json")); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client.SendAsync(request); } - public static Task PostJsonApiAsync( - this HttpClient client, - string requestUri, - string json) + public static Task PostJsonApiAsync(this HttpClient client, string requestUri, string json) { - var content = new StringContent( - json, - Encoding.UTF8, - "application/vnd.api+json"); + var content = new StringContent(json, Encoding.UTF8, "application/vnd.api+json"); - var request = new HttpRequestMessage(HttpMethod.Post, requestUri) - { - Content = content, - }; + var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content, }; - request.Headers - .Accept - .Add(new MediaTypeWithQualityHeaderValue("application/vnd.api+json")); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.api+json")); return client.SendAsync(request); } diff --git a/test/OrchardCore.Tests/Apis/Context/MvcTestFixture.cs b/test/OrchardCore.Tests/Apis/Context/MvcTestFixture.cs index 39344a8b46c..a3377298d4d 100644 --- a/test/OrchardCore.Tests/Apis/Context/MvcTestFixture.cs +++ b/test/OrchardCore.Tests/Apis/Context/MvcTestFixture.cs @@ -17,13 +17,9 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) protected override IWebHostBuilder CreateWebHostBuilder() { - return WebHostBuilderFactory.CreateFromAssemblyEntryPoint( - typeof(Program).Assembly, []); + return WebHostBuilderFactory.CreateFromAssemblyEntryPoint(typeof(Program).Assembly, []); } - protected override IHostBuilder CreateHostBuilder() - => Host.CreateDefaultBuilder() - .ConfigureWebHostDefaults(webBuilder => - webBuilder.UseStartup()); + protected override IHostBuilder CreateHostBuilder() => Host.CreateDefaultBuilder().ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()); } } diff --git a/test/OrchardCore.Tests/Apis/Context/SiteContext.cs b/test/OrchardCore.Tests/Apis/Context/SiteContext.cs index 845c410170d..25f321d8434 100644 --- a/test/OrchardCore.Tests/Apis/Context/SiteContext.cs +++ b/test/OrchardCore.Tests/Apis/Context/SiteContext.cs @@ -107,20 +107,14 @@ await UsingTenantScopeAsync(async scope => var recipeHarvesters = scope.ServiceProvider.GetRequiredService>(); var recipeExecutor = scope.ServiceProvider.GetRequiredService(); - var recipeCollections = await Task.WhenAll( - recipeHarvesters.Select(recipe => recipe.HarvestRecipesAsync())); + var recipeCollections = await Task.WhenAll(recipeHarvesters.Select(recipe => recipe.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(recipeCollection => recipeCollection); - var recipe = recipes - .FirstOrDefault(recipe => recipe.RecipeFileInfo.Name == recipeName && recipe.BasePath == recipePath); + var recipe = recipes.FirstOrDefault(recipe => recipe.RecipeFileInfo.Name == recipeName && recipe.BasePath == recipePath); var executionId = Guid.NewGuid().ToString("n"); - await recipeExecutor.ExecuteAsync( - executionId, - recipe, - new Dictionary(), - CancellationToken.None); + await recipeExecutor.ExecuteAsync(executionId, recipe, new Dictionary(), CancellationToken.None); }); } @@ -143,10 +137,7 @@ public async Task CreateContentItem(string contentType, Action(this T siteContext, string databaseProvider) where T : SiteContext + public static T WithDatabaseProvider(this T siteContext, string databaseProvider) + where T : SiteContext { siteContext.DatabaseProvider = databaseProvider; return siteContext; } - public static T WithConnectionString(this T siteContext, string connectionString) where T : SiteContext + public static T WithConnectionString(this T siteContext, string connectionString) + where T : SiteContext { siteContext.ConnectionString = connectionString; return siteContext; } - public static T WithPermissionsContext(this T siteContext, PermissionsContext permissionsContext) where T : SiteContext + public static T WithPermissionsContext(this T siteContext, PermissionsContext permissionsContext) + where T : SiteContext { siteContext.PermissionsContext = permissionsContext; return siteContext; } - public static T WithRecipe(this T siteContext, string recipeName) where T : SiteContext + public static T WithRecipe(this T siteContext, string recipeName) + where T : SiteContext { siteContext.RecipeName = recipeName; return siteContext; diff --git a/test/OrchardCore.Tests/Apis/Context/SiteStartup.cs b/test/OrchardCore.Tests/Apis/Context/SiteStartup.cs index e021dea84ae..eb452523120 100644 --- a/test/OrchardCore.Tests/Apis/Context/SiteStartup.cs +++ b/test/OrchardCore.Tests/Apis/Context/SiteStartup.cs @@ -18,22 +18,20 @@ public void ConfigureServices(IServiceCollection services) #pragma warning restore CA1822 // Mark members as static { services.AddOrchardCms(builder => - builder.AddSetupFeatures( - "OrchardCore.Tenants" - ) - .AddTenantFeatures( - "OrchardCore.Apis.GraphQL" - ) - .ConfigureServices(collection => - { - collection.AddScoped(); - - collection.AddScoped(sp => + builder + .AddSetupFeatures("OrchardCore.Tenants") + .AddTenantFeatures("OrchardCore.Apis.GraphQL") + .ConfigureServices(collection => { - return new PermissionContextAuthorizationHandler(sp.GetRequiredService(), PermissionsContexts); - }); - }) - .Configure(appBuilder => appBuilder.UseAuthorization())); + collection.AddScoped(); + + collection.AddScoped(sp => + { + return new PermissionContextAuthorizationHandler(sp.GetRequiredService(), PermissionsContexts); + }); + }) + .Configure(appBuilder => appBuilder.UseAuthorization()) + ); services.AddSingleton(); } diff --git a/test/OrchardCore.Tests/Apis/Context/TestRecipeHarvester.cs b/test/OrchardCore.Tests/Apis/Context/TestRecipeHarvester.cs index c8c63faeced..87fc3a04220 100644 --- a/test/OrchardCore.Tests/Apis/Context/TestRecipeHarvester.cs +++ b/test/OrchardCore.Tests/Apis/Context/TestRecipeHarvester.cs @@ -12,11 +12,7 @@ public TestRecipeHarvester(IRecipeReader recipeReader) _recipeReader = recipeReader; } - public Task> HarvestRecipesAsync() - => HarvestRecipesAsync( - [ - "Apis/Lucene/Recipes/luceneQueryTest.json" - ]); + public Task> HarvestRecipesAsync() => HarvestRecipesAsync(["Apis/Lucene/Recipes/luceneQueryTest.json"]); private async Task> HarvestRecipesAsync(string[] paths) { diff --git a/test/OrchardCore.Tests/Apis/GraphQL/Blog/BlogPostTests.cs b/test/OrchardCore.Tests/Apis/GraphQL/Blog/BlogPostTests.cs index 26afec46568..2e14ec614fe 100644 --- a/test/OrchardCore.Tests/Apis/GraphQL/Blog/BlogPostTests.cs +++ b/test/OrchardCore.Tests/Apis/GraphQL/Blog/BlogPostTests.cs @@ -11,23 +11,20 @@ namespace OrchardCore.Tests.Apis.GraphQL public class BlogPostTests { [Fact] - public async Task ShouldListAllBlogs() { using var context = new BlogContext(); await context.InitializeAsync(); - var result = await context - .GraphQLClient - .Content - .Query("Blog", builder => + var result = await context.GraphQLClient.Content.Query( + "Blog", + builder => { - builder - .WithField("contentItemId"); - }); + builder.WithField("contentItemId"); + } + ); - Assert.Single( - result["data"]["blog"].AsArray().Where(node => node["contentItemId"].ToString() == context.BlogContentItemId)); + Assert.Single(result["data"]["blog"].AsArray().Where(node => node["contentItemId"].ToString() == context.BlogContentItemId)); } [Fact] @@ -36,59 +33,41 @@ public async Task ShouldQueryByBlogPostAutoroutePart() using var context = new BlogContext(); await context.InitializeAsync(); - var blogPostContentItemId1 = await context - .CreateContentItem("BlogPost", builder => + var blogPostContentItemId1 = await context.CreateContentItem( + "BlogPost", + builder => { - builder - .DisplayText = "Some sorta blogpost!"; + builder.DisplayText = "Some sorta blogpost!"; - builder - .Weld(new AutoroutePart - { - Path = "Path1", - }); + builder.Weld(new AutoroutePart { Path = "Path1", }); - builder - .Weld(new ContainedPart - { - ListContentItemId = context.BlogContentItemId, - }); - }); + builder.Weld(new ContainedPart { ListContentItemId = context.BlogContentItemId, }); + } + ); - var blogPostContentItemId2 = await context - .CreateContentItem("BlogPost", builder => + var blogPostContentItemId2 = await context.CreateContentItem( + "BlogPost", + builder => { - builder - .DisplayText = "Some sorta other blogpost!"; + builder.DisplayText = "Some sorta other blogpost!"; - builder - .Weld(new AutoroutePart - { - Path = "Path2", - }); + builder.Weld(new AutoroutePart { Path = "Path2", }); - builder - .Weld(new ContainedPart - { - ListContentItemId = context.BlogContentItemId, - }); - }); - - var result = await context - .GraphQLClient - .Content - .Query("BlogPost", builder => + builder.Weld(new ContainedPart { ListContentItemId = context.BlogContentItemId, }); + } + ); + + var result = await context.GraphQLClient.Content.Query( + "BlogPost", + builder => { - builder - .WithQueryStringArgument("where", "path", "Path1"); + builder.WithQueryStringArgument("where", "path", "Path1"); - builder - .WithField("DisplayText"); - }); + builder.WithField("DisplayText"); + } + ); - Assert.Equal( - "Some sorta blogpost!", - result["data"]["blogPost"][0]["displayText"].ToString()); + Assert.Equal("Some sorta blogpost!", result["data"]["blogPost"][0]["displayText"].ToString()); } [Fact] @@ -97,17 +76,15 @@ public async Task WhenThePartHasTheSameNameAsTheContentTypeShouldCollapseFieldsT using var context = new BlogContext(); await context.InitializeAsync(); - var result = await context - .GraphQLClient - .Content - .Query("BlogPost", builder => + var result = await context.GraphQLClient.Content.Query( + "BlogPost", + builder => { builder.WithField("Subtitle"); - }); + } + ); - Assert.Equal( - "Problems look mighty small from 150 miles up", - result["data"]["blogPost"][0]["subtitle"].ToString()); + Assert.Equal("Problems look mighty small from 150 miles up", result["data"]["blogPost"][0]["subtitle"].ToString()); } [Fact] @@ -116,48 +93,45 @@ public async Task WhenCreatingABlogPostShouldBeAbleToPopulateField() using var context = new BlogContext(); await context.InitializeAsync(); - var blogPostContentItemId = await context - .CreateContentItem("BlogPost", builder => + var blogPostContentItemId = await context.CreateContentItem( + "BlogPost", + builder => { - builder - .DisplayText = "Some sorta blogpost!"; + builder.DisplayText = "Some sorta blogpost!"; - builder - .Weld("BlogPost", new ContentPart()); + builder.Weld("BlogPost", new ContentPart()); - builder - .Alter("BlogPost", (cp) => + builder.Alter( + "BlogPost", + (cp) => { cp.Weld("Subtitle", new TextField()); - cp.Alter("Subtitle", tf => - { - tf.Text = "Hey - Is this working!?!?!?!?"; - }); - }); - - builder - .Weld(new ContainedPart - { - ListContentItemId = context.BlogContentItemId, - }); - }); - - var result = await context - .GraphQLClient - .Content - .Query("BlogPost", builder => + cp.Alter( + "Subtitle", + tf => + { + tf.Text = "Hey - Is this working!?!?!?!?"; + } + ); + } + ); + + builder.Weld(new ContainedPart { ListContentItemId = context.BlogContentItemId, }); + } + ); + + var result = await context.GraphQLClient.Content.Query( + "BlogPost", + builder => { - builder - .WithQueryStringArgument("where", "ContentItemId", blogPostContentItemId); + builder.WithQueryStringArgument("where", "ContentItemId", blogPostContentItemId); - builder - .WithField("Subtitle"); - }); + builder.WithField("Subtitle"); + } + ); - Assert.Equal( - "Hey - Is this working!?!?!?!?", - result["data"]["blogPost"][0]["subtitle"].ToString()); + Assert.Equal("Hey - Is this working!?!?!?!?", result["data"]["blogPost"][0]["subtitle"].ToString()); } [Fact] @@ -166,34 +140,30 @@ public async Task ShouldQueryByStatus() using var context = new BlogContext(); await context.InitializeAsync(); - var draft = await context - .CreateContentItem("BlogPost", builder => + var draft = await context.CreateContentItem( + "BlogPost", + builder => { builder.DisplayText = "Draft blog post"; builder.Published = false; builder.Latest = true; - builder - .Weld(new ContainedPart - { - ListContentItemId = context.BlogContentItemId, - }); - }, draft: true); + builder.Weld(new ContainedPart { ListContentItemId = context.BlogContentItemId, }); + }, + draft: true + ); - var result = await context.GraphQLClient.Content - .Query("blogPost(status: PUBLISHED) { displayText, published }"); + var result = await context.GraphQLClient.Content.Query("blogPost(status: PUBLISHED) { displayText, published }"); Assert.Single(result["data"]["blogPost"].AsArray()); Assert.True(result["data"]["blogPost"][0]["published"].Value()); - result = await context.GraphQLClient.Content - .Query("blogPost(status: DRAFT) { displayText, published }"); + result = await context.GraphQLClient.Content.Query("blogPost(status: DRAFT) { displayText, published }"); Assert.Single(result["data"]["blogPost"].AsArray()); Assert.False(result["data"]["blogPost"][0]["published"].Value()); - result = await context.GraphQLClient.Content - .Query("blogPost(status: LATEST) { displayText, published }"); + result = await context.GraphQLClient.Content.Query("blogPost(status: LATEST) { displayText, published }"); Assert.Equal(2, result["data"]["blogPost"].AsArray().Count()); } @@ -201,8 +171,7 @@ public async Task ShouldQueryByStatus() [Fact] public async Task ShouldNotBeAbleToExecuteAnyQueriesWithoutPermission() { - using var context = new SiteContext() - .WithPermissionsContext(new PermissionsContext { UsePermissionsContext = true }); + using var context = new SiteContext().WithPermissionsContext(new PermissionsContext { UsePermissionsContext = true }); await context.InitializeAsync(); @@ -213,24 +182,19 @@ public async Task ShouldNotBeAbleToExecuteAnyQueriesWithoutPermission() [Fact] public async Task ShouldReturnBlogsWithViewBlogContentPermission() { - using var context = new SiteContext() - .WithPermissionsContext(new PermissionsContext - { - UsePermissionsContext = true, - AuthorizedPermissions = new[] - { - GraphQLApi.Permissions.ExecuteGraphQL, - Contents.Permissions.ViewContent, - }, - }); + using var context = new SiteContext().WithPermissionsContext( + new PermissionsContext { UsePermissionsContext = true, AuthorizedPermissions = new[] { GraphQLApi.Permissions.ExecuteGraphQL, Contents.Permissions.ViewContent, }, } + ); await context.InitializeAsync(); - var result = await context.GraphQLClient.Content - .Query("blog", builder => + var result = await context.GraphQLClient.Content.Query( + "blog", + builder => { builder.WithField("contentItemId"); - }); + } + ); Assert.NotEmpty(result["data"]["blog"].AsArray()); } @@ -238,24 +202,23 @@ public async Task ShouldReturnBlogsWithViewBlogContentPermission() [Fact] public async Task ShouldNotReturnBlogsWithViewOwnBlogContentPermission() { - using var context = new SiteContext() - .WithPermissionsContext(new PermissionsContext + using var context = new SiteContext().WithPermissionsContext( + new PermissionsContext { UsePermissionsContext = true, - AuthorizedPermissions = new[] - { - GraphQLApi.Permissions.ExecuteGraphQL, - Contents.Permissions.ViewOwnContent, - }, - }); + AuthorizedPermissions = new[] { GraphQLApi.Permissions.ExecuteGraphQL, Contents.Permissions.ViewOwnContent, }, + } + ); await context.InitializeAsync(); - var result = await context.GraphQLClient.Content - .Query("blog", builder => + var result = await context.GraphQLClient.Content.Query( + "blog", + builder => { builder.WithField("contentItemId"); - }); + } + ); Assert.Empty(result["data"]["blog"].AsArray()); } @@ -263,23 +226,19 @@ public async Task ShouldNotReturnBlogsWithViewOwnBlogContentPermission() [Fact] public async Task ShouldNotReturnBlogsWithoutViewBlogContentPermission() { - using var context = new SiteContext() - .WithPermissionsContext(new PermissionsContext - { - UsePermissionsContext = true, - AuthorizedPermissions = new[] - { - GraphQLApi.Permissions.ExecuteGraphQL, - }, - }); + using var context = new SiteContext().WithPermissionsContext( + new PermissionsContext { UsePermissionsContext = true, AuthorizedPermissions = new[] { GraphQLApi.Permissions.ExecuteGraphQL, }, } + ); await context.InitializeAsync(); - var result = await context.GraphQLClient.Content - .Query("blog", builder => + var result = await context.GraphQLClient.Content.Query( + "blog", + builder => { builder.WithField("contentItemId"); - }); + } + ); Assert.Equal(GraphQLApi.ValidationRules.RequiresPermissionValidationRule.ErrorCode, result["errors"][0]["extensions"]["number"].ToString()); } diff --git a/test/OrchardCore.Tests/Apis/GraphQL/Client/ContentTypeQueryResourceBuilderTests.cs b/test/OrchardCore.Tests/Apis/GraphQL/Client/ContentTypeQueryResourceBuilderTests.cs index 0aab6c9ee33..91c943742e7 100644 --- a/test/OrchardCore.Tests/Apis/GraphQL/Client/ContentTypeQueryResourceBuilderTests.cs +++ b/test/OrchardCore.Tests/Apis/GraphQL/Client/ContentTypeQueryResourceBuilderTests.cs @@ -9,8 +9,7 @@ public class ContentTypeQueryResourceBuilderTests [InlineData("SomeContentType")] public void ShouldReturnContentTypeNameAsPascalCase(string contentType) { - var result = new ContentTypeQueryResourceBuilder(contentType) - .Build(); + var result = new ContentTypeQueryResourceBuilder(contentType).Build(); Assert.Equal("someContentType {}", result); } diff --git a/test/OrchardCore.Tests/Apis/GraphQL/ContentItemsFieldTypeTests.cs b/test/OrchardCore.Tests/Apis/GraphQL/ContentItemsFieldTypeTests.cs index 626640b937c..56b7e646fd1 100644 --- a/test/OrchardCore.Tests/Apis/GraphQL/ContentItemsFieldTypeTests.cs +++ b/test/OrchardCore.Tests/Apis/GraphQL/ContentItemsFieldTypeTests.cs @@ -34,7 +34,9 @@ public async Task InitializeAsync() _store = await StoreFactory.CreateAndInitializeAsync(new Configuration().UseSqLite(string.Format(connectionStringTemplate, _tempFilename))); _prefix = "tp"; - _prefixedStore = await StoreFactory.CreateAndInitializeAsync(new Configuration().UseSqLite(string.Format(connectionStringTemplate, _tempFilename + _prefix)).SetTablePrefix(_prefix + "_")); + _prefixedStore = await StoreFactory.CreateAndInitializeAsync( + new Configuration().UseSqLite(string.Format(connectionStringTemplate, _tempFilename + _prefix)).SetTablePrefix(_prefix + "_") + ); _store.Configuration.ContentSerializer = new DefaultJsonContentSerializer(); _prefixedStore.Configuration.ContentSerializer = new DefaultJsonContentSerializer(); @@ -57,10 +59,7 @@ public Task DisposeAsync() { File.Delete(_tempFilename); } - catch - { - - } + catch { } } var prefixFilename = _tempFilename + _prefix; @@ -71,10 +70,7 @@ public Task DisposeAsync() { File.Delete(prefixFilename); } - catch - { - - } + catch { } } return Task.CompletedTask; @@ -86,27 +82,25 @@ private static async Task CreateTablesAsync(IStore store) { var builder = new SchemaBuilder(store.Configuration, await session.BeginTransactionAsync()); - await builder.CreateMapIndexTableAsync(table => table - .Column("ContentItemId", c => c.WithLength(26)) - .Column("ContentItemVersionId", c => c.WithLength(26)) - .Column("Latest") - .Column("Published") - .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) - .Column("ModifiedUtc", column => column.Nullable()) - .Column("PublishedUtc", column => column.Nullable()) - .Column("CreatedUtc", column => column.Nullable()) - .Column("Owner", column => column.Nullable().WithLength(ContentItemIndex.MaxOwnerSize)) - .Column("Author", column => column.Nullable().WithLength(ContentItemIndex.MaxAuthorSize)) - .Column("DisplayText", column => column.Nullable().WithLength(ContentItemIndex.MaxDisplayTextSize)) + await builder.CreateMapIndexTableAsync(table => + table + .Column("ContentItemId", c => c.WithLength(26)) + .Column("ContentItemVersionId", c => c.WithLength(26)) + .Column("Latest") + .Column("Published") + .Column("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize)) + .Column("ModifiedUtc", column => column.Nullable()) + .Column("PublishedUtc", column => column.Nullable()) + .Column("CreatedUtc", column => column.Nullable()) + .Column("Owner", column => column.Nullable().WithLength(ContentItemIndex.MaxOwnerSize)) + .Column("Author", column => column.Nullable().WithLength(ContentItemIndex.MaxAuthorSize)) + .Column("DisplayText", column => column.Nullable().WithLength(ContentItemIndex.MaxDisplayTextSize)) ); - await builder.CreateMapIndexTableAsync(table => table - .Column(nameof(AnimalIndex.Name)) - ); + await builder.CreateMapIndexTableAsync(table => table.Column(nameof(AnimalIndex.Name))); - await builder.CreateMapIndexTableAsync(table => table - .Column(nameof(AnimalTraitsIndex.IsHappy)) - .Column(nameof(AnimalTraitsIndex.IsScary)) + await builder.CreateMapIndexTableAsync(table => + table.Column(nameof(AnimalTraitsIndex.IsHappy)).Column(nameof(AnimalTraitsIndex.IsScary)) ); await session.SaveChangesAsync(); @@ -130,18 +124,28 @@ public async Task ShouldFilterByContentItemIndex() var context = CreateAnimalFieldContext(services); - var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; + var ci = new ContentItem + { + ContentType = "Animal", + Published = true, + ContentItemId = "1", + ContentItemVersionId = "1" + }; ci.Weld(new AnimalPart { Name = "doug" }); var session = context.RequestServices.GetService(); await session.SaveAsync(ci); await session.SaveChangesAsync(); - var type = new ContentItemsFieldType("Animal", new Schema(services), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); + var type = new ContentItemsFieldType( + "Animal", + new Schema(services), + Options.Create(new GraphQLContentOptions()), + Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 }) + ); context.Arguments["where"] = new ArgumentValue(JObject.Parse("{ \"contentItemId\": \"1\" }"), ArgumentSource.Variable); - var dogs = await ((LockedAsyncFieldResolver>)type.Resolver) - .ResolveAsync(context) as IEnumerable; + var dogs = await ((LockedAsyncFieldResolver>)type.Resolver).ResolveAsync(context) as IEnumerable; Assert.Single(dogs); Assert.Equal("doug", dogs.First().As().Name); @@ -167,14 +171,25 @@ public async Task ShouldFilterByContentItemIndexWhenSqlTablePrefixIsUsed() var context = CreateAnimalFieldContext(services); - var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; + var ci = new ContentItem + { + ContentType = "Animal", + Published = true, + ContentItemId = "1", + ContentItemVersionId = "1" + }; ci.Weld(new AnimalPart { Name = "doug" }); var session = context.RequestServices.GetService(); await session.SaveAsync(ci); await session.SaveChangesAsync(); - var type = new ContentItemsFieldType("Animal", new Schema(services), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); + var type = new ContentItemsFieldType( + "Animal", + new Schema(services), + Options.Create(new GraphQLContentOptions()), + Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 }) + ); context.Arguments["where"] = new ArgumentValue(JObject.Parse("{ \"contentItemId\": \"1\" }"), ArgumentSource.Variable); var dogs = await ResolveContentItems(type, context); @@ -202,17 +217,25 @@ public async Task ShouldFilterByAliasIndexRegardlessOfInputFieldCase(string fiel var context = CreateAnimalFieldContext(services, fieldName); - var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; + var ci = new ContentItem + { + ContentType = "Animal", + Published = true, + ContentItemId = "1", + ContentItemVersionId = "1" + }; ci.Weld(new AnimalPart { Name = "doug" }); var session = context.RequestServices.GetService(); await session.SaveAsync(ci); await session.SaveChangesAsync(); - var type = new ContentItemsFieldType("Animal", + var type = new ContentItemsFieldType( + "Animal", new Schema(services), Options.Create(new GraphQLContentOptions()), - Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); + Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 }) + ); context.Arguments["where"] = new ArgumentValue(JObject.Parse($"{{\"{fieldName}\" : {{ \"name\": \"doug\" }} }}"), ArgumentSource.Variable); var dogs = await ResolveContentItems(type, context); @@ -238,14 +261,25 @@ public async Task ShouldBeAbleToUseTheSameIndexForMultipleAliases() services.Build(); var context = CreateAnimalFieldContext(services); - var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; + var ci = new ContentItem + { + ContentType = "Animal", + Published = true, + ContentItemId = "1", + ContentItemVersionId = "1" + }; ci.Weld(new Animal { Name = "doug" }); var session = context.RequestServices.GetService(); await session.SaveAsync(ci); await session.SaveChangesAsync(); - var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); + var type = new ContentItemsFieldType( + "Animal", + new Schema(), + Options.Create(new GraphQLContentOptions()), + Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 }) + ); context.Arguments["where"] = new ArgumentValue(JObject.Parse("{ \"cats\": { \"name\": \"doug\" } }"), ArgumentSource.Variable); var cats = await ResolveContentItems(type, context); @@ -281,14 +315,53 @@ public async Task ShouldFilterOnMultipleIndexesOnSameAlias() var context = CreateAnimalFieldContext(services); - var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; - ci.Weld(new Animal { Name = "doug", IsHappy = true, IsScary = false }); + var ci = new ContentItem + { + ContentType = "Animal", + Published = true, + ContentItemId = "1", + ContentItemVersionId = "1" + }; + ci.Weld( + new Animal + { + Name = "doug", + IsHappy = true, + IsScary = false + } + ); - var ci1 = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "2", ContentItemVersionId = "2" }; - ci1.Weld(new Animal { Name = "doug", IsHappy = false, IsScary = true }); + var ci1 = new ContentItem + { + ContentType = "Animal", + Published = true, + ContentItemId = "2", + ContentItemVersionId = "2" + }; + ci1.Weld( + new Animal + { + Name = "doug", + IsHappy = false, + IsScary = true + } + ); - var ci2 = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "3", ContentItemVersionId = "3" }; - ci2.Weld(new Animal { Name = "tommy", IsHappy = false, IsScary = true }); + var ci2 = new ContentItem + { + ContentType = "Animal", + Published = true, + ContentItemId = "3", + ContentItemVersionId = "3" + }; + ci2.Weld( + new Animal + { + Name = "tommy", + IsHappy = false, + IsScary = true + } + ); var session = context.RequestServices.GetService(); await session.SaveAsync(ci); @@ -296,7 +369,12 @@ public async Task ShouldFilterOnMultipleIndexesOnSameAlias() await session.SaveAsync(ci2); await session.SaveChangesAsync(); - var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); + var type = new ContentItemsFieldType( + "Animal", + new Schema(), + Options.Create(new GraphQLContentOptions()), + Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 }) + ); context.Arguments["where"] = new ArgumentValue(JObject.Parse("{ \"animals\": { \"name\": \"doug\", \"isScary\": true } }"), ArgumentSource.Variable); var animals = await ResolveContentItems(type, context); @@ -324,14 +402,25 @@ public async Task ShouldFilterPartsWithoutAPrefixWhenThePartHasNoPrefix() var context = CreateAnimalFieldContext(services); - var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; + var ci = new ContentItem + { + ContentType = "Animal", + Published = true, + ContentItemId = "1", + ContentItemVersionId = "1" + }; ci.Weld(new AnimalPart { Name = "doug" }); var session = context.RequestServices.GetService(); await session.SaveAsync(ci); await session.SaveChangesAsync(); - var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); + var type = new ContentItemsFieldType( + "Animal", + new Schema(), + Options.Create(new GraphQLContentOptions()), + Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 }) + ); context.Arguments["where"] = new ArgumentValue(JObject.Parse("{ \"animal\": { \"name\": \"doug\" } }"), ArgumentSource.Variable); var dogs = await ResolveContentItems(type, context); @@ -357,14 +446,25 @@ public async Task ShouldFilterByCollapsedWhereInputForCollapsedParts() var context = CreateAnimalFieldContext(services, collapsed: true); - var ci = new ContentItem { ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1" }; + var ci = new ContentItem + { + ContentType = "Animal", + Published = true, + ContentItemId = "1", + ContentItemVersionId = "1" + }; ci.Weld(new AnimalPart { Name = "doug" }); var session = context.RequestServices.GetService(); await session.SaveAsync(ci); await session.SaveChangesAsync(); - var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 })); + var type = new ContentItemsFieldType( + "Animal", + new Schema(), + Options.Create(new GraphQLContentOptions()), + Options.Create(new GraphQLSettings { DefaultNumberOfResults = 10 }) + ); context.Arguments["where"] = new ArgumentValue(JObject.Parse("{ \"name\": \"doug\" }"), ArgumentSource.Variable); var dogs = await ResolveContentItems(type, context); @@ -377,6 +477,7 @@ private static async Task> ResolveContentItems(ContentI { return (await ((LockedAsyncFieldResolver>)type.Resolver).ResolveAsync(context)) as IEnumerable; } + private static ResolveFieldContext CreateAnimalFieldContext(IServiceProvider services, string fieldName = null, bool collapsed = false) { IGraphType where; @@ -398,14 +499,15 @@ private static ResolveFieldContext CreateAnimalFieldContext(IServiceProvider ser { Name = "Inputs", ResolvedType = new ListGraphType(new StringGraphType() { Name = "Animal" }), - Arguments = [ - new QueryArgument - { - Name = "where", - Description = "filters the animals", - ResolvedType = where - } - ] + Arguments = + [ + new QueryArgument + { + Name = "where", + Description = "filters the animals", + ResolvedType = where + } + ] }, RequestServices = services }; @@ -455,15 +557,11 @@ public class AnimalIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(contentItem => { - return new AnimalIndex - { - Name = contentItem.As() != null - ? contentItem.As().Name - : contentItem.As().Name - }; + return new AnimalIndex { Name = contentItem.As() != null ? contentItem.As().Name : contentItem.As().Name }; }); } } @@ -478,27 +576,20 @@ public class AnimalTraitsIndexProvider : IndexProvider { public override void Describe(DescribeContext context) { - context.For() + context + .For() .Map(contentItem => { var animal = contentItem.As(); if (animal != null) { - return new AnimalTraitsIndex - { - IsHappy = contentItem.As().IsHappy, - IsScary = contentItem.As().IsScary - }; + return new AnimalTraitsIndex { IsHappy = contentItem.As().IsHappy, IsScary = contentItem.As().IsScary }; } var animalPartSuffix = contentItem.As(); - return new AnimalTraitsIndex - { - IsHappy = animalPartSuffix.IsHappy, - IsScary = animalPartSuffix.IsScary - }; + return new AnimalTraitsIndex { IsHappy = animalPartSuffix.IsHappy, IsScary = animalPartSuffix.IsScary }; }); } } diff --git a/test/OrchardCore.Tests/Apis/GraphQL/Queries/RecentBlogPostsQueryTests.cs b/test/OrchardCore.Tests/Apis/GraphQL/Queries/RecentBlogPostsQueryTests.cs index cce316c6e55..8610c3d1e63 100644 --- a/test/OrchardCore.Tests/Apis/GraphQL/Queries/RecentBlogPostsQueryTests.cs +++ b/test/OrchardCore.Tests/Apis/GraphQL/Queries/RecentBlogPostsQueryTests.cs @@ -12,28 +12,25 @@ public async Task ShouldListBlogPostWhenCallingAQuery() using var context = new BlogContext(); await context.InitializeAsync(); - var blogPostContentItemId = await context - .CreateContentItem("BlogPost", builder => + var blogPostContentItemId = await context.CreateContentItem( + "BlogPost", + builder => { builder.Published = true; builder.Latest = true; builder.DisplayText = "Some sorta blogpost in a Query!"; - builder - .Weld(new ContainedPart - { - ListContentItemId = context.BlogContentItemId - }); - }); + builder.Weld(new ContainedPart { ListContentItemId = context.BlogContentItemId }); + } + ); - var result = await context - .GraphQLClient - .Content - .Query("RecentBlogPosts", builder => + var result = await context.GraphQLClient.Content.Query( + "RecentBlogPosts", + builder => { - builder - .WithField("displayText"); - }); + builder.WithField("displayText"); + } + ); var nodes = result["data"]["recentBlogPosts"]; diff --git a/test/OrchardCore.Tests/Apis/GraphQL/ValidationRules/RequiresPermissionValidationRuleTests.cs b/test/OrchardCore.Tests/Apis/GraphQL/ValidationRules/RequiresPermissionValidationRuleTests.cs index bbd24fb2a83..005f516386f 100644 --- a/test/OrchardCore.Tests/Apis/GraphQL/ValidationRules/RequiresPermissionValidationRuleTests.cs +++ b/test/OrchardCore.Tests/Apis/GraphQL/ValidationRules/RequiresPermissionValidationRuleTests.cs @@ -13,20 +13,13 @@ namespace OrchardCore.Tests.Apis.GraphQL.ValidationRules { public class RequiresPermissionValidationRuleTests { - internal readonly static Dictionary _permissions = new() - { - { "permissionOne", new Permission("TestPermissionOne", "TestPermissionOne") }, - { "permissionTwo", new Permission("TestPermissionTwo", "TestPermissionTwo") } - }; + internal static readonly Dictionary _permissions = + new() { { "permissionOne", new Permission("TestPermissionOne", "TestPermissionOne") }, { "permissionTwo", new Permission("TestPermissionTwo", "TestPermissionTwo") } }; [Fact] public async Task FieldsWithNoRequirePermissionsShouldResolve() { - var options = BuildExecutionOptions("query { test { noPermissions } }", - new PermissionsContext - { - UsePermissionsContext = true - }); + var options = BuildExecutionOptions("query { test { noPermissions } }", new PermissionsContext { UsePermissionsContext = true }); var executer = new DocumentExecuter(); @@ -45,12 +38,10 @@ public async Task FieldsWithNoRequirePermissionsShouldResolve() [InlineData("permissionTwo", "Fantastic Fox Loves Permission Two")] public async Task FieldsWithRequirePermissionsShouldResolveWhenUserHasPermissions(string fieldName, string expectedFieldValue) { - var options = BuildExecutionOptions($"query {{ test {{{fieldName}}} }}", - new PermissionsContext - { - UsePermissionsContext = true, - AuthorizedPermissions = new[] { _permissions[fieldName] } - }); + var options = BuildExecutionOptions( + $"query {{ test {{{fieldName}}} }}", + new PermissionsContext { UsePermissionsContext = true, AuthorizedPermissions = new[] { _permissions[fieldName] } } + ); var executer = new DocumentExecuter(); @@ -67,11 +58,7 @@ public async Task FieldsWithRequirePermissionsShouldResolveWhenUserHasPermission [Fact] public async Task FieldsWithRequirePermissionsShouldNotResolveWhenUserDoesntHavePermissions() { - var options = BuildExecutionOptions("query { test { permissionOne } }", - new PermissionsContext - { - UsePermissionsContext = true - }); + var options = BuildExecutionOptions("query { test { permissionOne } }", new PermissionsContext { UsePermissionsContext = true }); var executer = new DocumentExecuter(); @@ -83,12 +70,10 @@ public async Task FieldsWithRequirePermissionsShouldNotResolveWhenUserDoesntHave [Fact] public async Task FieldsWithMultipleRequirePermissionsShouldResolveWhenUserHasAllPermissions() { - var options = BuildExecutionOptions("query { test { permissionMultiple } }", - new PermissionsContext - { - UsePermissionsContext = true, - AuthorizedPermissions = _permissions.Values - }); + var options = BuildExecutionOptions( + "query { test { permissionMultiple } }", + new PermissionsContext { UsePermissionsContext = true, AuthorizedPermissions = _permissions.Values } + ); var executer = new DocumentExecuter(); @@ -123,10 +108,7 @@ private static ExecutionOptions BuildExecutionOptions(string query, PermissionsC { Query = query, Schema = new ValidationSchema(), - UserContext = new GraphQLUserContext - { - User = new ClaimsPrincipal(new StubIdentity()) - }, + UserContext = new GraphQLUserContext { User = new ClaimsPrincipal(new StubIdentity()) }, ValidationRules = DocumentValidator.CoreRules.Concat(serviceProvider.GetServices()) }; } @@ -145,9 +127,7 @@ private class ValidationQueryRoot : ObjectGraphType { public ValidationQueryRoot() { - Field("test") - .Returns() - .Resolve(_ => new object()); + Field("test").Returns().Resolve(_ => new object()); } } @@ -155,25 +135,17 @@ private class TestField : ObjectGraphType { public TestField() { - Field("NoPermissions") - .Returns() - .Resolve(_ => "Fantastic Fox Hates Permissions"); + Field("NoPermissions").Returns().Resolve(_ => "Fantastic Fox Hates Permissions"); - Field("PermissionOne") - .Returns() - .RequirePermission(_permissions["permissionOne"]) - .Resolve(_ => "Fantastic Fox Loves Permission One"); + Field("PermissionOne").Returns().RequirePermission(_permissions["permissionOne"]).Resolve(_ => "Fantastic Fox Loves Permission One"); - Field("PermissionTwo") - .Returns() - .RequirePermission(_permissions["permissionTwo"]) - .Resolve(_ => "Fantastic Fox Loves Permission Two"); + Field("PermissionTwo").Returns().RequirePermission(_permissions["permissionTwo"]).Resolve(_ => "Fantastic Fox Loves Permission Two"); Field("PermissionMultiple") - .Returns() - .RequirePermission(_permissions["permissionOne"]) - .RequirePermission(_permissions["permissionTwo"]) - .Resolve(_ => "Fantastic Fox Loves Multiple Permissions"); + .Returns() + .RequirePermission(_permissions["permissionOne"]) + .RequirePermission(_permissions["permissionTwo"]) + .Resolve(_ => "Fantastic Fox Loves Multiple Permissions"); } } } diff --git a/test/OrchardCore.Tests/Apis/Lucene/LuceneContext.cs b/test/OrchardCore.Tests/Apis/Lucene/LuceneContext.cs index 534713bc0c5..3624354e17e 100644 --- a/test/OrchardCore.Tests/Apis/Lucene/LuceneContext.cs +++ b/test/OrchardCore.Tests/Apis/Lucene/LuceneContext.cs @@ -4,9 +4,7 @@ namespace OrchardCore.Tests.Apis.Lucene { public class LuceneContext : SiteContext { - static LuceneContext() - { - } + static LuceneContext() { } public LuceneContext() { diff --git a/test/OrchardCore.Tests/Apis/Lucene/LuceneQueryTests.cs b/test/OrchardCore.Tests/Apis/Lucene/LuceneQueryTests.cs index f21781cae36..bdad93d4e70 100644 --- a/test/OrchardCore.Tests/Apis/Lucene/LuceneQueryTests.cs +++ b/test/OrchardCore.Tests/Apis/Lucene/LuceneQueryTests.cs @@ -132,11 +132,11 @@ public async Task TwoWildcardQueriesWithBoostHasResults() // { "from": 0, "size": 10, "query":{ "bool": { "should": [ { "wildcard": { "Content.ContentItem.DisplayText.Normalized": { "value": "orch*", "boost": 2 } } },{ "wildcard": { "Content.BodyAspect.Body": { "value": "orchar*", "boost": 5 } } } ] } } } var query = - "{ \"from\": 0, \"size\": 10, \"query\":" + - "{ \"bool\": { \"should\": [ " + - "{ \"wildcard\": { \"Content.ContentItem.DisplayText.Normalized\": { \"value\": \"orch*\", \"boost\": 2 } } }," + - "{ \"wildcard\": { \"Content.BodyAspect.Body\": { \"value\": \"orchar*\", \"boost\": 5 } } }" + - "] } } }"; + "{ \"from\": 0, \"size\": 10, \"query\":" + + "{ \"bool\": { \"should\": [ " + + "{ \"wildcard\": { \"Content.ContentItem.DisplayText.Normalized\": { \"value\": \"orch*\", \"boost\": 2 } } }," + + "{ \"wildcard\": { \"Content.BodyAspect.Body\": { \"value\": \"orchar*\", \"boost\": 5 } } }" + + "] } } }"; var content = await context.Client.GetAsync($"api/lucene/content?indexName={index}&query={query}"); var queryResults = await content.Content.ReadAsAsync(); @@ -150,7 +150,8 @@ public async Task TwoWildcardQueriesWithBoostHasResults() Assert.Contains("Orchard", contentItems.ElementAt(1).As().Html, StringComparison.OrdinalIgnoreCase); Assert.Contains("Orchard", contentItems.ElementAt(2).DisplayText, StringComparison.OrdinalIgnoreCase); Assert.Contains("Orchard", contentItems.ElementAt(3).DisplayText, StringComparison.OrdinalIgnoreCase); - }; + } + ; } } } diff --git a/test/OrchardCore.Tests/Commands/CommandHandlerDescriptorBuilderTests.cs b/test/OrchardCore.Tests/Commands/CommandHandlerDescriptorBuilderTests.cs index a795bd865e1..4af16267c56 100644 --- a/test/OrchardCore.Tests/Commands/CommandHandlerDescriptorBuilderTests.cs +++ b/test/OrchardCore.Tests/Commands/CommandHandlerDescriptorBuilderTests.cs @@ -23,29 +23,20 @@ public void BuilderShouldCreateDescriptor() public class MyCommand : DefaultCommandHandler { - public MyCommand() : base(null) - { - } + public MyCommand() + : base(null) { } #pragma warning disable CA1822 // Mark members as static - public void FooBar() - { - } + public void FooBar() { } [CommandName("MyCommand")] - public void FooBar2() - { - } + public void FooBar2() { } [CommandName("Foo Bar")] - public void Foo_Bar() - { - } + public void Foo_Bar() { } [CommandName("Foo_Bar")] - public void Foo_Bar3() - { - } + public void Foo_Bar3() { } #pragma warning restore CA1822 // Mark members as static } @@ -63,8 +54,8 @@ public void BuilderShouldReturnPublicMethodsOnly() public class PublicMethodsOnly { #pragma warning restore 660,661 - public bool Bar { get; set; } // No accessors. - public bool Field = true; // No field. + public bool Bar { get; set; } // No accessors. + public bool Field = true; // No field. // No private method. #pragma warning disable CA1822 // Mark members as static @@ -72,13 +63,10 @@ public class PublicMethodsOnly private void Blah() #pragma warning restore IDE0051 // Remove unused private members #pragma warning restore CA1822 // Mark members as static - { - } + { } // No private method. - public static void Foo() - { - } + public static void Foo() { } // No operator. public static bool operator ==(PublicMethodsOnly _1, PublicMethodsOnly _2) @@ -94,8 +82,7 @@ public static void Foo() #pragma warning disable CA1822 // Mark members as static public void Method() #pragma warning restore CA1822 // Mark members as static - { - } + { } } } } diff --git a/test/OrchardCore.Tests/Commands/CommandHandlerTests.cs b/test/OrchardCore.Tests/Commands/CommandHandlerTests.cs index db8a9328b40..a989e64ddec 100644 --- a/test/OrchardCore.Tests/Commands/CommandHandlerTests.cs +++ b/test/OrchardCore.Tests/Commands/CommandHandlerTests.cs @@ -164,9 +164,7 @@ public async Task TestCommandArgumentsArePassedCorrectlyWithAParamsParameterAndN [Fact] public async Task TestCommandArgumentsArePassedCorrectlyWithNormalParametersAndAParamsParameters() { - var commandContext = CreateCommandContext("ConcatAllParams", - new Dictionary(), - ["left-", "center-", "right"]); + var commandContext = CreateCommandContext("ConcatAllParams", new Dictionary(), ["left-", "center-", "right"]); await _handler.ExecuteAsync(commandContext); Assert.Equal("left-center-right", commandContext.Output.ToString()); } @@ -195,9 +193,8 @@ public async Task TestCommandParamsMismatchWithParamsButNotEnoughArguments() public class StubCommandHandler : DefaultCommandHandler { - public StubCommandHandler() : base(new NullStringLocalizerFactory().Create(typeof(object))) - { - } + public StubCommandHandler() + : base(new NullStringLocalizerFactory().Create(typeof(object))) { } [OrchardSwitch] public bool Verbose { get; set; } diff --git a/test/OrchardCore.Tests/Commands/CommandManagerTests.cs b/test/OrchardCore.Tests/Commands/CommandManagerTests.cs index 1c8956ea0d6..51b4d5f7968 100644 --- a/test/OrchardCore.Tests/Commands/CommandManagerTests.cs +++ b/test/OrchardCore.Tests/Commands/CommandManagerTests.cs @@ -37,9 +37,8 @@ public async Task ManagerCanRunACompositeCommand() public class MyCommand : DefaultCommandHandler { - public MyCommand() : base(null) - { - } + public MyCommand() + : base(null) { } #pragma warning disable CA1822 // Mark members as static public string FooBar() diff --git a/test/OrchardCore.Tests/Data/ContentItemExtensions.cs b/test/OrchardCore.Tests/Data/ContentItemExtensions.cs index a9289997014..303bddf743a 100644 --- a/test/OrchardCore.Tests/Data/ContentItemExtensions.cs +++ b/test/OrchardCore.Tests/Data/ContentItemExtensions.cs @@ -46,15 +46,9 @@ public void GetReflectsChangesToFieldMadeByApply() public void MergeReflectsChangesToWellKnownProperties() { // Setup - var contentItem = new ContentItem - { - DisplayText = "original value" - }; + var contentItem = new ContentItem { DisplayText = "original value" }; - var newContentItem = new ContentItem - { - DisplayText = "merged value" - }; + var newContentItem = new ContentItem { DisplayText = "merged value" }; // Act contentItem.Merge(newContentItem); @@ -67,15 +61,9 @@ public void MergeReflectsChangesToWellKnownProperties() public void MergeRemovesWellKnownPropertiesFromData() { // Setup - var contentItem = new ContentItem - { - DisplayText = "original value" - }; + var contentItem = new ContentItem { DisplayText = "original value" }; - var newContentItem = new ContentItem - { - DisplayText = "merged value" - }; + var newContentItem = new ContentItem { DisplayText = "merged value" }; // Act contentItem.Merge(newContentItem); @@ -88,15 +76,9 @@ public void MergeRemovesWellKnownPropertiesFromData() public void MergeMaintainsDocumentId() { // Setup - var contentItem = new ContentItem - { - Id = 1, - }; - - var newContentItem = new ContentItem - { - Id = 2 - }; + var contentItem = new ContentItem { Id = 1, }; + + var newContentItem = new ContentItem { Id = 2 }; // Act contentItem.Merge(newContentItem); diff --git a/test/OrchardCore.Tests/DisplayManagement/ArgsUtility.cs b/test/OrchardCore.Tests/DisplayManagement/ArgsUtility.cs index 8a5eae5f815..e895464a358 100644 --- a/test/OrchardCore.Tests/DisplayManagement/ArgsUtility.cs +++ b/test/OrchardCore.Tests/DisplayManagement/ArgsUtility.cs @@ -14,10 +14,12 @@ public static INamedEnumerable Named(object args) { return FromDictionary(new RouteValueDictionary(args)); } + public static INamedEnumerable Empty() { return Arguments.FromT(Array.Empty(), []); } + public static INamedEnumerable Empty() { return Empty(); diff --git a/test/OrchardCore.Tests/DisplayManagement/Decriptors/DefaultShapeTableManagerTests.cs b/test/OrchardCore.Tests/DisplayManagement/Decriptors/DefaultShapeTableManagerTests.cs index a0f09291c87..04f354be8e3 100644 --- a/test/OrchardCore.Tests/DisplayManagement/Decriptors/DefaultShapeTableManagerTests.cs +++ b/test/OrchardCore.Tests/DisplayManagement/Decriptors/DefaultShapeTableManagerTests.cs @@ -21,9 +21,9 @@ public TestModuleExtensionInfo(string name) { var dic1 = new Dictionary() { - {"name", name}, - {"description", name}, - {"type", "module"}, + { "name", name }, + { "description", name }, + { "type", "module" }, }; var memConfigSrc1 = new MemoryConfigurationSource { InitialData = dic1 }; @@ -32,11 +32,7 @@ public TestModuleExtensionInfo(string name) Manifest = new ManifestInfo(new ModuleAttribute()); - var features = - new List() - { - { new FeatureInfo(name, name, 0, string.Empty, string.Empty, this, [], false, false, false) } - }; + var features = new List() { { new FeatureInfo(name, name, 0, string.Empty, string.Empty, this, [], false, false, false) } }; Features = features; } @@ -55,9 +51,9 @@ public TestThemeExtensionInfo(string name) { var dic1 = new Dictionary() { - {"name", name}, - {"description", name}, - {"type", "theme"}, + { "name", name }, + { "description", name }, + { "type", "theme" }, }; var memConfigSrc1 = new MemoryConfigurationSource { InitialData = dic1 }; @@ -66,11 +62,7 @@ public TestThemeExtensionInfo(string name) Manifest = new ManifestInfo(new ThemeAttribute()); - var features = - new List() - { - { new FeatureInfo(name, name, 0, string.Empty, string.Empty, this, [], false, false, false) } - }; + var features = new List() { { new FeatureInfo(name, name, 0, string.Empty, string.Empty, this, [], false, false, false) } }; Features = features; @@ -81,10 +73,10 @@ public TestThemeExtensionInfo(string name, IFeatureInfo baseTheme) { var dic1 = new Dictionary() { - {"name", name}, - {"description", name}, - {"type", "theme"}, - {"basetheme", baseTheme.Id } + { "name", name }, + { "description", name }, + { "type", "theme" }, + { "basetheme", baseTheme.Id } }; var memConfigSrc1 = new MemoryConfigurationSource { InitialData = dic1 }; @@ -93,11 +85,7 @@ public TestThemeExtensionInfo(string name, IFeatureInfo baseTheme) Manifest = new ManifestInfo(new ThemeAttribute()); - Features = - new List() - { - { new FeatureInfo(name, name, 0, string.Empty, string.Empty, this, [baseTheme.Id], false, false, false) } - }; + Features = new List() { { new FeatureInfo(name, name, 0, string.Empty, string.Empty, this, [baseTheme.Id], false, false, false) } }; Id = name; } @@ -126,7 +114,8 @@ public DefaultShapeTableManagerTests() var baseThemeFeatureExtensionInfo = new TestThemeExtensionInfo("BaseTheme"); var derivedThemeFeatureExtensionInfo = new TestThemeExtensionInfo("DerivedTheme", baseThemeFeatureExtensionInfo.Features.First()); - var features = new[] { + var features = new[] + { testFeatureExtensionInfo.Features.First(), theme1FeatureExtensionInfo.Features.First(), baseThemeFeatureExtensionInfo.Features.First(), @@ -136,13 +125,15 @@ public DefaultShapeTableManagerTests() serviceCollection.AddSingleton(new TestExtensionManager(features)); #pragma warning disable CA1861 // Avoid constant arrays as arguments - TestShapeProvider.InitFeatureShapes(new Dictionary> - { - { TestFeature(), new[] {"Hello"} }, - { features[1], new[] {"Theme1Shape"} }, - { features[2], new[] {"DerivedShape", "OverriddenShape"} }, - { features[3], new[] {"BaseShape", "OverriddenShape"} }, - }); + TestShapeProvider.InitFeatureShapes( + new Dictionary> + { + { TestFeature(), new[] { "Hello" } }, + { features[1], new[] { "Theme1Shape" } }, + { features[2], new[] { "DerivedShape", "OverriddenShape" } }, + { features[3], new[] { "BaseShape", "OverriddenShape" } }, + } + ); #pragma warning restore CA1861 // Avoid constant arrays as arguments serviceCollection.AddScoped(); @@ -183,7 +174,11 @@ public Task> GetDisabledFeaturesAsync() throw new NotImplementedException(); } - public Task<(IEnumerable, IEnumerable)> UpdateFeaturesAsync(IEnumerable featuresToDisable, IEnumerable featuresToEnable, bool force) + public Task<(IEnumerable, IEnumerable)> UpdateFeaturesAsync( + IEnumerable featuresToDisable, + IEnumerable featuresToEnable, + bool force + ) { throw new NotImplementedException(); } @@ -207,6 +202,7 @@ public Task> GetAvailableExtensionsAsync() public class TestExtensionManager : IExtensionManager { private readonly IEnumerable _features; + public TestExtensionManager(IEnumerable features) { _features = features; @@ -285,8 +281,7 @@ public class TestShapeProvider : IShapeTableProvider public Action Discover = x => { }; - public static void InitFeatureShapes(IDictionary> featureShapes) - => _featureShapes = featureShapes; + public static void InitFeatureShapes(IDictionary> featureShapes) => _featureShapes = featureShapes; void IShapeTableProvider.Discover(ShapeTableBuilder builder) { @@ -322,17 +317,25 @@ public async Task DefaultShapeTableIsReturnedForNullOrEmpty() [Fact] public async Task CallbackAlterationsContributeToDescriptor() { - Func cb1 = x => { return Task.CompletedTask; }; - Func cb2 = x => { return Task.CompletedTask; }; - Func cb3 = x => { return Task.CompletedTask; }; - Func cb4 = x => { return Task.CompletedTask; }; - - _serviceProvider.GetService().Discover = - builder => builder.Describe("Foo").From(TestFeature()) - .OnCreating(cb1) - .OnCreated(cb2) - .OnDisplaying(cb3) - .OnDisplayed(cb4); + Func cb1 = x => + { + return Task.CompletedTask; + }; + Func cb2 = x => + { + return Task.CompletedTask; + }; + Func cb3 = x => + { + return Task.CompletedTask; + }; + Func cb4 = x => + { + return Task.CompletedTask; + }; + + _serviceProvider.GetService().Discover = builder => + builder.Describe("Foo").From(TestFeature()).OnCreating(cb1).OnCreated(cb2).OnDisplaying(cb3).OnDisplayed(cb4); var manager = _serviceProvider.GetService(); @@ -362,8 +365,10 @@ public async Task DescribedPlacementIsReturnedIfNotNull() var shapeSummary = new ShapePlacementContext("Foo", "Summary", string.Empty, null); var shapeTitle = new ShapePlacementContext("Foo", "Title", string.Empty, null); - _serviceProvider.GetService().Discover = - builder => builder.Describe("Hello1").From(TestFeature()) + _serviceProvider.GetService().Discover = builder => + builder + .Describe("Hello1") + .From(TestFeature()) .Placement(ctx => ctx.DisplayType == "Detail" ? new PlacementInfo { Location = "Main" } : null) .Placement(ctx => ctx.DisplayType == "Summary" ? new PlacementInfo { Location = string.Empty } : null); @@ -392,8 +397,10 @@ public async Task TwoArgumentVariationDoesSameThing() var shapeSummary = new ShapePlacementContext("Foo", "Summary", string.Empty, null); var shapeTitle = new ShapePlacementContext("Foo", "Title", string.Empty, null); - _serviceProvider.GetService().Discover = - builder => builder.Describe("Hello2").From(TestFeature()) + _serviceProvider.GetService().Discover = builder => + builder + .Describe("Hello2") + .From(TestFeature()) .Placement(ctx => ctx.DisplayType == "Detail", new PlacementInfo { Location = "Main" }) .Placement(ctx => ctx.DisplayType == "Summary", new PlacementInfo { Location = string.Empty }); @@ -422,10 +429,10 @@ internal async Task PathConstraintShouldMatch() // all path have a trailing / as per the current implementation // todo: (sebros) find a way to 'use' the current implementation in DefaultContentDisplay.BindPlacement instead of emulating it - var rules = new[] { + var rules = new[] + { Tuple.Create("~/my-blog", "~/my-blog/", true), Tuple.Create("~/my-blog/", "~/my-blog/", true), - // star match Tuple.Create("~/my-blog*", "~/my-blog/", true), Tuple.Create("~/my-blog*", "~/my-blog/my-post/", true), @@ -440,9 +447,8 @@ internal async Task PathConstraintShouldMatch() var context = rule.Item2; var match = rule.Item3; - _serviceProvider.GetService().Discover = - builder => builder.Describe("Hello").From(TestFeature()) - .Placement(ctx => true, new PlacementInfo { Location = "Match" }); + _serviceProvider.GetService().Discover = builder => + builder.Describe("Hello").From(TestFeature()).Placement(ctx => true, new PlacementInfo { Location = "Match" }); var manager = _serviceProvider.GetService(); var hello = (await manager.GetShapeTableAsync(null)).Descriptors["Hello"]; diff --git a/test/OrchardCore.Tests/DisplayManagement/Decriptors/LocationParserTests.cs b/test/OrchardCore.Tests/DisplayManagement/Decriptors/LocationParserTests.cs index 1ae2452d947..a94295bd23e 100644 --- a/test/OrchardCore.Tests/DisplayManagement/Decriptors/LocationParserTests.cs +++ b/test/OrchardCore.Tests/DisplayManagement/Decriptors/LocationParserTests.cs @@ -22,7 +22,12 @@ public class LocationParserTests [InlineData("/Content:5@Group1#Tab1%Card1|Col1")] public void ZoneShouldBeParsed(string location) { - Assert.Equal("Content", new PlacementInfo { Location = location }.GetZones().FirstOrDefault()); + Assert.Equal( + "Content", + new PlacementInfo { Location = location } + .GetZones() + .FirstOrDefault() + ); } [Theory] diff --git a/test/OrchardCore.Tests/DisplayManagement/DefaultDisplayManagerTests.cs b/test/OrchardCore.Tests/DisplayManagement/DefaultDisplayManagerTests.cs index b693155fdf0..31c03452941 100644 --- a/test/OrchardCore.Tests/DisplayManagement/DefaultDisplayManagerTests.cs +++ b/test/OrchardCore.Tests/DisplayManagement/DefaultDisplayManagerTests.cs @@ -17,8 +17,7 @@ public class DefaultDisplayManagerTests public DefaultDisplayManagerTests() { - _defaultShapeTable = new ShapeTable - ( + _defaultShapeTable = new ShapeTable( new Dictionary(StringComparer.OrdinalIgnoreCase), new Dictionary(StringComparer.OrdinalIgnoreCase) ); @@ -52,15 +51,20 @@ private class TestDisplayEvents : IShapeDisplayEvents Task IShapeDisplayEvents.DisplayingAsync(ShapeDisplayContext context) { - Displaying(context); return Task.CompletedTask; + Displaying(context); + return Task.CompletedTask; } + Task IShapeDisplayEvents.DisplayedAsync(ShapeDisplayContext context) { - Displayed(context); return Task.CompletedTask; + Displayed(context); + return Task.CompletedTask; } + Task IShapeDisplayEvents.DisplayingFinalizedAsync(ShapeDisplayContext context) { - Finalized(context); return Task.CompletedTask; + Finalized(context); + return Task.CompletedTask; } } @@ -75,10 +79,7 @@ private void AddShapeDescriptor(ShapeDescriptor shapeDescriptor) private static DisplayContext CreateDisplayContext(Shape shape) { - return new DisplayContext - { - Value = shape - }; + return new DisplayContext { Value = shape }; } [Fact] @@ -89,15 +90,8 @@ public async Task RenderSimpleShape() var shape = new Shape(); shape.Metadata.Type = "Foo"; - var descriptor = new ShapeDescriptor - { - ShapeType = "Foo" - }; - descriptor.Bindings["Foo"] = new ShapeBinding - { - BindingName = "Foo", - BindingAsync = ctx => Task.FromResult(new HtmlString("Hi there!")) - }; + var descriptor = new ShapeDescriptor { ShapeType = "Foo" }; + descriptor.Bindings["Foo"] = new ShapeBinding { BindingName = "Foo", BindingAsync = ctx => Task.FromResult(new HtmlString("Hi there!")) }; AddShapeDescriptor(descriptor); var result = await displayManager.ExecuteAsync(CreateDisplayContext(shape)); @@ -133,21 +127,13 @@ public async Task RenderPreCalculatedShape() var shape = new Shape(); shape.Metadata.Type = "Foo"; - shape.Metadata.OnDisplaying( - context => - { - context.ChildContent = new HtmlString("Bar"); - }); - - var descriptor = new ShapeDescriptor - { - ShapeType = "Foo" - }; - descriptor.Bindings["Foo"] = new ShapeBinding + shape.Metadata.OnDisplaying(context => { - BindingName = "Foo", - BindingAsync = ctx => Task.FromResult(new HtmlString("Hi there!")) - }; + context.ChildContent = new HtmlString("Bar"); + }); + + var descriptor = new ShapeDescriptor { ShapeType = "Foo" }; + descriptor.Bindings["Foo"] = new ShapeBinding { BindingName = "Foo", BindingAsync = ctx => Task.FromResult(new HtmlString("Hi there!")) }; AddShapeDescriptor(descriptor); var result = await displayManager.ExecuteAsync(CreateDisplayContext(shape)); @@ -165,7 +151,8 @@ public async Task IShapeBindingResolverProvidedShapesDoesNotOverrideShapeDescrip var descriptor = new ShapeDescriptor { ShapeType = "Foo", - ProcessingAsync = new Func[] { + ProcessingAsync = new Func[] + { context => { dynamic dynamicShape = context.Shape; @@ -174,11 +161,7 @@ public async Task IShapeBindingResolverProvidedShapesDoesNotOverrideShapeDescrip } } }; - descriptor.Bindings["Foo"] = new ShapeBinding - { - BindingName = "Foo", - BindingAsync = ctx => Task.FromResult(new HtmlString("Is there any data ?")) - }; + descriptor.Bindings["Foo"] = new ShapeBinding { BindingName = "Foo", BindingAsync = ctx => Task.FromResult(new HtmlString("Is there any data ?")) }; AddShapeDescriptor(descriptor); _additionalBindings["Foo"] = new ShapeBinding @@ -203,15 +186,8 @@ public async Task RenderFallbackShape() var shape = new Shape(); shape.Metadata.Type = "Foo__2"; - var descriptor = new ShapeDescriptor - { - ShapeType = "Foo" - }; - descriptor.Bindings["Foo"] = new ShapeBinding - { - BindingName = "Foo", - BindingAsync = ctx => Task.FromResult(new HtmlString("Hi there!")) - }; + var descriptor = new ShapeDescriptor { ShapeType = "Foo" }; + descriptor.Bindings["Foo"] = new ShapeBinding { BindingName = "Foo", BindingAsync = ctx => Task.FromResult(new HtmlString("Hi there!")) }; AddShapeDescriptor(descriptor); var result = await displayManager.ExecuteAsync(CreateDisplayContext(shape)); @@ -229,24 +205,17 @@ public async Task AddAlternatesOnDisplaying() var descriptor = new ShapeDescriptor { ShapeType = "Foo", - DisplayingAsync = new Func[] { + DisplayingAsync = new Func[] + { context => { - context.Shape.Metadata.Alternates.Add("Bar"); - return Task.CompletedTask; + context.Shape.Metadata.Alternates.Add("Bar"); + return Task.CompletedTask; } } }; - descriptor.Bindings["Foo"] = new ShapeBinding - { - BindingName = "Foo", - BindingAsync = ctx => Task.FromResult(new HtmlString("Foo")) - }; - descriptor.Bindings["Bar"] = new ShapeBinding - { - BindingName = "Bar", - BindingAsync = ctx => Task.FromResult(new HtmlString("Bar")) - }; + descriptor.Bindings["Foo"] = new ShapeBinding { BindingName = "Foo", BindingAsync = ctx => Task.FromResult(new HtmlString("Foo")) }; + descriptor.Bindings["Bar"] = new ShapeBinding { BindingName = "Bar", BindingAsync = ctx => Task.FromResult(new HtmlString("Bar")) }; AddShapeDescriptor(descriptor); var result = await displayManager.ExecuteAsync(CreateDisplayContext(shape)); @@ -264,24 +233,17 @@ public async Task AddAlternatesOnProcessing() var descriptor = new ShapeDescriptor { ShapeType = "Foo", - ProcessingAsync = new Func[] { + ProcessingAsync = new Func[] + { context => { - context.Shape.Metadata.Alternates.Add("Bar"); - return Task.CompletedTask; + context.Shape.Metadata.Alternates.Add("Bar"); + return Task.CompletedTask; } } }; - descriptor.Bindings["Foo"] = new ShapeBinding - { - BindingName = "Foo", - BindingAsync = ctx => Task.FromResult(new HtmlString("Foo")) - }; - descriptor.Bindings["Bar"] = new ShapeBinding - { - BindingName = "Bar", - BindingAsync = ctx => Task.FromResult(new HtmlString("Bar")) - }; + descriptor.Bindings["Foo"] = new ShapeBinding { BindingName = "Foo", BindingAsync = ctx => Task.FromResult(new HtmlString("Foo")) }; + descriptor.Bindings["Bar"] = new ShapeBinding { BindingName = "Bar", BindingAsync = ctx => Task.FromResult(new HtmlString("Bar")) }; AddShapeDescriptor(descriptor); var result = await displayManager.ExecuteAsync(CreateDisplayContext(shape)); @@ -296,20 +258,9 @@ public async Task RenderAlternateShapeExplicitly() var shape = new Shape(); shape.Metadata.Type = "Foo__2"; - var descriptor = new ShapeDescriptor - { - ShapeType = "Foo" - }; - descriptor.Bindings["Foo"] = new ShapeBinding - { - BindingName = "Foo", - BindingAsync = ctx => Task.FromResult(new HtmlString("Hi there!")) - }; - descriptor.Bindings["Foo__2"] = new ShapeBinding - { - BindingName = "Foo__2", - BindingAsync = ctx => Task.FromResult(new HtmlString("Hello again!")) - }; + var descriptor = new ShapeDescriptor { ShapeType = "Foo" }; + descriptor.Bindings["Foo"] = new ShapeBinding { BindingName = "Foo", BindingAsync = ctx => Task.FromResult(new HtmlString("Hi there!")) }; + descriptor.Bindings["Foo__2"] = new ShapeBinding { BindingName = "Foo__2", BindingAsync = ctx => Task.FromResult(new HtmlString("Hello again!")) }; AddShapeDescriptor(descriptor); var result = await displayManager.ExecuteAsync(CreateDisplayContext(shape)); @@ -327,10 +278,7 @@ public async Task RenderAlternateShapeByMostRecentlyAddedMatchingAlternate() shape.Metadata.Alternates.Add("Foo__2"); shape.Metadata.Alternates.Add("Foo__3"); - var descriptor = new ShapeDescriptor - { - ShapeType = "Foo" - }; + var descriptor = new ShapeDescriptor { ShapeType = "Foo" }; AddBinding(descriptor, "Foo", ctx => Task.FromResult(new HtmlString("Hi there!"))); AddBinding(descriptor, "Foo__1", ctx => Task.FromResult(new HtmlString("Hello (1)!"))); AddBinding(descriptor, "Foo__2", ctx => Task.FromResult(new HtmlString("Hello (2)!"))); @@ -342,11 +290,7 @@ public async Task RenderAlternateShapeByMostRecentlyAddedMatchingAlternate() private static void AddBinding(ShapeDescriptor descriptor, string bindingName, Func> binding) { - descriptor.Bindings[bindingName] = new ShapeBinding - { - BindingName = bindingName, - BindingAsync = binding - }; + descriptor.Bindings[bindingName] = new ShapeBinding { BindingName = bindingName, BindingAsync = binding }; } [Fact] @@ -357,17 +301,29 @@ public async Task ShapeDescriptorDisplayingAndDisplayedAreCalled() var shape = new Shape(); shape.Metadata.Type = "Foo"; - var descriptor = new ShapeDescriptor - { - ShapeType = "Foo" - }; + var descriptor = new ShapeDescriptor { ShapeType = "Foo" }; AddBinding(descriptor, "Foo", ctx => Task.FromResult(new HtmlString("yarg"))); AddShapeDescriptor(descriptor); var displayingEventCount = 0; var displayedEventCount = 0; - descriptor.DisplayingAsync = new Func[] { ctx => { ++displayingEventCount; return Task.CompletedTask; } }; - descriptor.DisplayedAsync = new Func[] { ctx => { ++displayedEventCount; ctx.ChildContent = new HtmlString("[" + ctx.ChildContent.ToString() + "]"); return Task.CompletedTask; } }; + descriptor.DisplayingAsync = new Func[] + { + ctx => + { + ++displayingEventCount; + return Task.CompletedTask; + } + }; + descriptor.DisplayedAsync = new Func[] + { + ctx => + { + ++displayedEventCount; + ctx.ChildContent = new HtmlString("[" + ctx.ChildContent.ToString() + "]"); + return Task.CompletedTask; + } + }; var result = await displayManager.ExecuteAsync(CreateDisplayContext(shape)); @@ -384,17 +340,11 @@ public async Task DisplayingEventFiresEarlyEnoughToAddAlternateShapeBindingNames var shapeFoo = new Shape(); shapeFoo.Metadata.Type = "Foo"; - var descriptorFoo = new ShapeDescriptor - { - ShapeType = "Foo" - }; + var descriptorFoo = new ShapeDescriptor { ShapeType = "Foo" }; AddBinding(descriptorFoo, "Foo", ctx => Task.FromResult(new HtmlString("alpha"))); AddShapeDescriptor(descriptorFoo); - var descriptorBar = new ShapeDescriptor - { - ShapeType = "Bar" - }; + var descriptorBar = new ShapeDescriptor { ShapeType = "Bar" }; AddBinding(descriptorBar, "Bar", ctx => Task.FromResult(new HtmlString("beta"))); AddShapeDescriptor(descriptorBar); @@ -402,7 +352,14 @@ public async Task DisplayingEventFiresEarlyEnoughToAddAlternateShapeBindingNames shapeFoo = new Shape(); shapeFoo.Metadata.Type = "Foo"; - descriptorFoo.DisplayingAsync = new Func[] { ctx => { ctx.Shape.Metadata.Alternates.Add("Bar"); return Task.CompletedTask; } }; + descriptorFoo.DisplayingAsync = new Func[] + { + ctx => + { + ctx.Shape.Metadata.Alternates.Add("Bar"); + return Task.CompletedTask; + } + }; var resultWithOverride = await htmlDisplay.ExecuteAsync(CreateDisplayContext(shapeFoo)); Assert.Equal("alpha", resultNormally.ToString()); @@ -417,10 +374,7 @@ public async Task ShapeTypeAndBindingNamesAreNotCaseSensitive() var shapeFoo = new Shape(); shapeFoo.Metadata.Type = "Foo"; - var descriptorFoo = new ShapeDescriptor - { - ShapeType = "Foo" - }; + var descriptorFoo = new ShapeDescriptor { ShapeType = "Foo" }; AddBinding(descriptorFoo, "Foo", ctx => Task.FromResult(new HtmlString("alpha"))); AddShapeDescriptor(descriptorFoo); diff --git a/test/OrchardCore.Tests/DisplayManagement/ShapeFactoryTests.cs b/test/OrchardCore.Tests/DisplayManagement/ShapeFactoryTests.cs index bf11366b968..2de65fbdb3a 100644 --- a/test/OrchardCore.Tests/DisplayManagement/ShapeFactoryTests.cs +++ b/test/OrchardCore.Tests/DisplayManagement/ShapeFactoryTests.cs @@ -23,8 +23,7 @@ public ShapeFactoryTests() serviceCollection.AddScoped(); serviceCollection.AddScoped(); - _shapeTable = new ShapeTable - ( + _shapeTable = new ShapeTable( new Dictionary(StringComparer.OrdinalIgnoreCase), new Dictionary(StringComparer.OrdinalIgnoreCase) ); @@ -126,8 +125,6 @@ public async Task ShapeFactoryWithCustomShapeTypeAppliesArguments() Assert.Equal("Baz", foo.Baz); } - private class SubShape : Shape - { - } + private class SubShape : Shape { } } } diff --git a/test/OrchardCore.Tests/DisplayManagement/ShapeHelperTests.cs b/test/OrchardCore.Tests/DisplayManagement/ShapeHelperTests.cs index 91ec5426fb0..8b62853c184 100644 --- a/test/OrchardCore.Tests/DisplayManagement/ShapeHelperTests.cs +++ b/test/OrchardCore.Tests/DisplayManagement/ShapeHelperTests.cs @@ -22,8 +22,7 @@ public ShapeHelperTests() serviceCollection.AddScoped(); serviceCollection.AddScoped(); - var defaultShapeTable = new ShapeTable - ( + var defaultShapeTable = new ShapeTable( new Dictionary(StringComparer.OrdinalIgnoreCase), new Dictionary(StringComparer.OrdinalIgnoreCase) ); diff --git a/test/OrchardCore.Tests/DisplayManagement/ShapeSerializerTests.cs b/test/OrchardCore.Tests/DisplayManagement/ShapeSerializerTests.cs index 7af5b74c231..f55a9ee3e92 100644 --- a/test/OrchardCore.Tests/DisplayManagement/ShapeSerializerTests.cs +++ b/test/OrchardCore.Tests/DisplayManagement/ShapeSerializerTests.cs @@ -23,8 +23,7 @@ public ShapeSerializerTests() serviceCollection.AddScoped(); serviceCollection.AddScoped(); - var defaultShapeTable = new ShapeTable - ( + var defaultShapeTable = new ShapeTable( new Dictionary(StringComparer.OrdinalIgnoreCase), new Dictionary(StringComparer.OrdinalIgnoreCase) ); @@ -52,10 +51,7 @@ public async Task ShouldSkipRecursiveShapes() var alpha = await shape.CreateAsync("Alpha"); - var beta = await shape.CreateAsync("Beta", Arguments.From(new - { - Alpha = alpha - })); + var beta = await shape.CreateAsync("Beta", Arguments.From(new { Alpha = alpha })); await alpha.AddAsync(beta); var serialized = alpha.ShapeToJson(); diff --git a/test/OrchardCore.Tests/DisplayManagement/Title/PageTitleBuilderTests.cs b/test/OrchardCore.Tests/DisplayManagement/Title/PageTitleBuilderTests.cs index 6ec26ae27b8..f8998b696c6 100644 --- a/test/OrchardCore.Tests/DisplayManagement/Title/PageTitleBuilderTests.cs +++ b/test/OrchardCore.Tests/DisplayManagement/Title/PageTitleBuilderTests.cs @@ -126,11 +126,7 @@ public void TitleAddSegments() var pageTitleBuilder = (PageTitleBuilder)_serviceProvider.GetService(); pageTitleBuilder.Clear(); - var elements = new IHtmlContent[] - { - new HtmlString(FirstPartTitle), - new HtmlString(SecondPartTitle) - }; + var elements = new IHtmlContent[] { new HtmlString(FirstPartTitle), new HtmlString(SecondPartTitle) }; pageTitleBuilder.AddSegments(elements, "after"); diff --git a/test/OrchardCore.Tests/DisplayManagement/ZoneonDemandTests.cs b/test/OrchardCore.Tests/DisplayManagement/ZoneonDemandTests.cs index c8222ac384a..5c74104fefb 100644 --- a/test/OrchardCore.Tests/DisplayManagement/ZoneonDemandTests.cs +++ b/test/OrchardCore.Tests/DisplayManagement/ZoneonDemandTests.cs @@ -67,9 +67,12 @@ public void ZoneOnDemandAsBaseTypeIsEqualToItself() { var zoneOnDemand = CreateZoneOnDemand("SomeZone"); - Shape zoneShape1 = zoneOnDemand, zoneShape2 = zoneOnDemand; - Composite zoneComposite1 = zoneOnDemand, zoneComposite2 = zoneOnDemand; - object zoneObject1 = zoneOnDemand, zoneObject2 = zoneOnDemand; + Shape zoneShape1 = zoneOnDemand, + zoneShape2 = zoneOnDemand; + Composite zoneComposite1 = zoneOnDemand, + zoneComposite2 = zoneOnDemand; + object zoneObject1 = zoneOnDemand, + zoneObject2 = zoneOnDemand; // Intended reference comparison. Assert.True(zoneShape1 == zoneShape2); @@ -80,7 +83,10 @@ public void ZoneOnDemandAsBaseTypeIsEqualToItself() [Fact] public void ZoneHoldingPropertiesMissingIndexThrows() { - Assert.Throws(() => { _ = CreateZoneHolding().Properties["SomeZone"]; }); + Assert.Throws(() => + { + _ = CreateZoneHolding().Properties["SomeZone"]; + }); } [Fact] diff --git a/test/OrchardCore.Tests/Email/EmailAddressValidatorTests.cs b/test/OrchardCore.Tests/Email/EmailAddressValidatorTests.cs index 3ea78a3080d..ca8771bed46 100644 --- a/test/OrchardCore.Tests/Email/EmailAddressValidatorTests.cs +++ b/test/OrchardCore.Tests/Email/EmailAddressValidatorTests.cs @@ -33,8 +33,7 @@ public void UseCustomEmailAddressValidator(string address, bool isValid) private class OrchardCoreEmailValidator : IEmailAddressValidator { - public bool Validate(string emailAddress) - => emailAddress.EndsWith("@orchardcore.net"); + public bool Validate(string emailAddress) => emailAddress.EndsWith("@orchardcore.net"); } } } diff --git a/test/OrchardCore.Tests/Email/EmailTests.cs b/test/OrchardCore.Tests/Email/EmailTests.cs index d54cb406982..458c41fe104 100644 --- a/test/OrchardCore.Tests/Email/EmailTests.cs +++ b/test/OrchardCore.Tests/Email/EmailTests.cs @@ -187,15 +187,8 @@ public void MailBoxAddress_ShouldParseEmail(string text, string name, string add public async Task SendEmail_WithoutToAndCcAndBccHeaders_ShouldThrowsException() { // Arrange - var message = new MailMessage - { - Subject = "Test", - Body = "Test Message" - }; - var settings = new SmtpSettings - { - DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory - }; + var message = new MailMessage { Subject = "Test", Body = "Test Message" }; + var settings = new SmtpSettings { DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory }; var smtp = CreateSmtpService(settings); @@ -216,10 +209,7 @@ public async Task SendOfflineEmailHasNoResponse() Subject = "Test", Body = "Test Message" }; - var settings = new SmtpSettings - { - DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory - }; + var settings = new SmtpSettings { DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory }; var smtp = CreateSmtpService(settings); diff --git a/test/OrchardCore.Tests/Extensions/ExtensionManagerTests.cs b/test/OrchardCore.Tests/Extensions/ExtensionManagerTests.cs index 1135d2f8872..d6c52ce2721 100644 --- a/test/OrchardCore.Tests/Extensions/ExtensionManagerTests.cs +++ b/test/OrchardCore.Tests/Extensions/ExtensionManagerTests.cs @@ -9,17 +9,13 @@ namespace OrchardCore.Tests.Extensions { public class ExtensionManagerTests { - private static readonly IHostEnvironment _hostingEnvironment - = new StubHostingEnvironment(); + private static readonly IHostEnvironment _hostingEnvironment = new StubHostingEnvironment(); - private static readonly IApplicationContext _applicationContext - = new ModularApplicationContext(_hostingEnvironment, [new ModuleNamesProvider()]); + private static readonly IApplicationContext _applicationContext = new ModularApplicationContext(_hostingEnvironment, [new ModuleNamesProvider()]); - private static readonly IFeaturesProvider _moduleFeatureProvider = - new FeaturesProvider(new[] { new ThemeFeatureBuilderEvents() }); + private static readonly IFeaturesProvider _moduleFeatureProvider = new FeaturesProvider(new[] { new ThemeFeatureBuilderEvents() }); - private static readonly IFeaturesProvider _themeFeatureProvider = - new FeaturesProvider(new[] { new ThemeFeatureBuilderEvents() }); + private static readonly IFeaturesProvider _themeFeatureProvider = new FeaturesProvider(new[] { new ThemeFeatureBuilderEvents() }); private readonly ExtensionManager _moduleScopedExtensionManager; private readonly ExtensionManager _themeScopedExtensionManager; @@ -34,7 +30,7 @@ public ExtensionManagerTests() new TypeFeatureProvider(), _moduleFeatureProvider, new NullLogger() - ); + ); _themeScopedExtensionManager = new ExtensionManager( _applicationContext, @@ -43,7 +39,7 @@ public ExtensionManagerTests() new TypeFeatureProvider(), _themeFeatureProvider, new NullLogger() - ); + ); _moduleThemeScopedExtensionManager = new ExtensionManager( _applicationContext, @@ -52,7 +48,7 @@ public ExtensionManagerTests() new TypeFeatureProvider(), _themeFeatureProvider, new NullLogger() - ); + ); } private class ModuleNamesProvider : IModuleNamesProvider @@ -61,14 +57,7 @@ private class ModuleNamesProvider : IModuleNamesProvider public ModuleNamesProvider() { - _moduleNames = - [ - "BaseThemeSample", - "BaseThemeSample2", - "DerivedThemeSample", - "DerivedThemeSample2", - "ModuleSample" - ]; + _moduleNames = ["BaseThemeSample", "BaseThemeSample2", "DerivedThemeSample", "DerivedThemeSample2", "ModuleSample"]; } public IEnumerable GetModuleNames() @@ -80,8 +69,7 @@ public IEnumerable GetModuleNames() [Fact] public void ShouldReturnExtension() { - var extensions = _moduleThemeScopedExtensionManager.GetExtensions() - .Where(e => e.Manifest.ModuleInfo.Category == "Test"); + var extensions = _moduleThemeScopedExtensionManager.GetExtensions().Where(e => e.Manifest.ModuleInfo.Category == "Test"); Assert.Equal(5, extensions.Count()); } @@ -122,8 +110,7 @@ public void GetDependentFeaturesShouldReturnAllFeaturesThatHaveADependencyOnAFea [Fact] public void GetFeaturesShouldReturnAllFeaturesOrderedByDependency() { - var features = _moduleScopedExtensionManager.GetFeatures() - .Where(f => f.Category == "Test" && !f.IsTheme()); + var features = _moduleScopedExtensionManager.GetFeatures().Where(f => f.Category == "Test" && !f.IsTheme()); Assert.Equal(4, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); @@ -181,8 +168,7 @@ public void GetFeaturesShouldReturnCorrectThemeHeirarchy() [Fact] public void GetFeaturesShouldReturnBothThemesAndModules() { - var features = _moduleThemeScopedExtensionManager.GetFeatures() - .Where(f => f.Category == "Test"); + var features = _moduleThemeScopedExtensionManager.GetFeatures().Where(f => f.Category == "Test"); Assert.Equal(8, features.Count()); } @@ -190,8 +176,7 @@ public void GetFeaturesShouldReturnBothThemesAndModules() [Fact] public void GetFeaturesShouldReturnThemesAfterModules() { - var features = _moduleThemeScopedExtensionManager.GetFeatures() - .Where(f => f.Category == "Test"); + var features = _moduleThemeScopedExtensionManager.GetFeatures().Where(f => f.Category == "Test"); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); diff --git a/test/OrchardCore.Tests/Hosting/Console/CommandParserTests.cs b/test/OrchardCore.Tests/Hosting/Console/CommandParserTests.cs index 47c054dd58e..8aae7609589 100644 --- a/test/OrchardCore.Tests/Hosting/Console/CommandParserTests.cs +++ b/test/OrchardCore.Tests/Hosting/Console/CommandParserTests.cs @@ -183,6 +183,7 @@ public void ParserUnderstandsEmptyArgument2() Assert.Single(result); Assert.Equal("", result[0]); } + [Fact] public void ParserUnderstandsEmptyArgument3() { diff --git a/test/OrchardCore.Tests/Html/HtmlSanitizerTests.cs b/test/OrchardCore.Tests/Html/HtmlSanitizerTests.cs index 0568a9f3398..102debc454d 100644 --- a/test/OrchardCore.Tests/Html/HtmlSanitizerTests.cs +++ b/test/OrchardCore.Tests/Html/HtmlSanitizerTests.cs @@ -7,7 +7,10 @@ public class HtmlSanitizerTests private static readonly HtmlSanitizerService _sanitizer = new(Options.Create(new HtmlSanitizerOptions())); [Theory] - [InlineData("
Test
", "
Test
")] + [InlineData( + "
Test
", + "
Test
" + )] [InlineData("", @"")] [InlineData("Click me", @"Click me")] [InlineData("Click me", @"Click me")] @@ -25,10 +28,12 @@ public void ShouldConfigureSanitizer() { var services = new ServiceCollection(); services.AddOptions(); - services.ConfigureHtmlSanitizer((sanitizer) => - { - sanitizer.AllowedAttributes.Add("class"); - }); + services.ConfigureHtmlSanitizer( + (sanitizer) => + { + sanitizer.AllowedAttributes.Add("class"); + } + ); services.AddScoped(); @@ -45,10 +50,12 @@ public void ShouldReconfigureSanitizer() // Setup. With defaults. var services = new ServiceCollection(); services.AddOptions(); - services.ConfigureHtmlSanitizer((sanitizer) => - { - sanitizer.AllowedAttributes.Add("class"); - }); + services.ConfigureHtmlSanitizer( + (sanitizer) => + { + sanitizer.AllowedAttributes.Add("class"); + } + ); // Act. Reconfigure to remove defaults. services.Configure(o => diff --git a/test/OrchardCore.Tests/Localization/CultureDictionaryTests.cs b/test/OrchardCore.Tests/Localization/CultureDictionaryTests.cs index 245cb020eef..d48c9f730b0 100644 --- a/test/OrchardCore.Tests/Localization/CultureDictionaryTests.cs +++ b/test/OrchardCore.Tests/Localization/CultureDictionaryTests.cs @@ -59,11 +59,7 @@ public void EnumerateCultureDictionary() { // Arrange var dictionary = new CultureDictionary("ar", PluralizationRule.Arabic); - dictionary.MergeTranslations( - [ - new("Hello", "مرحبا"), - new("Bye", "مع السلامة") - ]); + dictionary.MergeTranslations([new("Hello", "مرحبا"), new("Bye", "مع السلامة")]); // Act & Assert Assert.NotEmpty(dictionary); diff --git a/test/OrchardCore.Tests/Localization/CultureScopeTests.cs b/test/OrchardCore.Tests/Localization/CultureScopeTests.cs index 748fa03cdd8..4b98a861c2e 100644 --- a/test/OrchardCore.Tests/Localization/CultureScopeTests.cs +++ b/test/OrchardCore.Tests/Localization/CultureScopeTests.cs @@ -41,10 +41,7 @@ public void CultureScopeSetsOrginalCulturesAfterEndOfScope() var uiCulture = CultureInfo.CurrentUICulture; // Act - using (var cultureScope = CultureScope.Create("FR")) - { - - } + using (var cultureScope = CultureScope.Create("FR")) { } // Assert Assert.Equal(culture, CultureInfo.CurrentCulture); diff --git a/test/OrchardCore.Tests/Localization/LocalizationManagerTests.cs b/test/OrchardCore.Tests/Localization/LocalizationManagerTests.cs index 3685c75f84c..7ec837ea160 100644 --- a/test/OrchardCore.Tests/Localization/LocalizationManagerTests.cs +++ b/test/OrchardCore.Tests/Localization/LocalizationManagerTests.cs @@ -22,10 +22,7 @@ public LocalizationManagerTests() [Fact] public void GetDictionaryReturnsDictionaryWithPluralRuleAndCultureIfNoTranslationsExists() { - _translationProvider.Setup(o => o.LoadTranslations( - It.Is(culture => culture == "cs"), - It.IsAny()) - ); + _translationProvider.Setup(o => o.LoadTranslations(It.Is(culture => culture == "cs"), It.IsAny())); var manager = new LocalizationManager(new[] { _pluralRuleProvider.Object }, new[] { _translationProvider.Object }, _memoryCache); @@ -56,16 +53,20 @@ public void GetDictionaryReturnsDictionaryWithTranslationsFromProvider() [Fact] public void GetDictionarySelectsPluralRuleFromProviderWithHigherPriority() { - PluralizationRuleDelegate csPluralRuleOverride = n => ((n == 1) ? 0 : (n >= 2 && n <= 4) ? 1 : 0); + PluralizationRuleDelegate csPluralRuleOverride = n => + ( + (n == 1) + ? 0 + : (n >= 2 && n <= 4) + ? 1 + : 0 + ); var highPriorityRuleProvider = new Mock(); highPriorityRuleProvider.SetupGet(o => o.Order).Returns(-1); highPriorityRuleProvider.Setup(o => o.TryGetRule(It.Is(culture => culture.Name == "cs"), out csPluralRuleOverride)).Returns(true); - _translationProvider.Setup(o => o.LoadTranslations( - It.Is(culture => culture == "cs"), - It.IsAny()) - ); + _translationProvider.Setup(o => o.LoadTranslations(It.Is(culture => culture == "cs"), It.IsAny())); var manager = new LocalizationManager(new[] { _pluralRuleProvider.Object, highPriorityRuleProvider.Object }, new[] { _translationProvider.Object }, _memoryCache); diff --git a/test/OrchardCore.Tests/Localization/PluralizationRule.cs b/test/OrchardCore.Tests/Localization/PluralizationRule.cs index e120ccd4e5b..f236e8d1139 100644 --- a/test/OrchardCore.Tests/Localization/PluralizationRule.cs +++ b/test/OrchardCore.Tests/Localization/PluralizationRule.cs @@ -4,9 +4,29 @@ namespace OrchardCore.Tests.Localization; public class PluralizationRule { - public static readonly PluralizationRuleDelegate Czech = n => ((n == 1) ? 0 : (n >= 2 && n <= 4) ? 1 : 2); + public static readonly PluralizationRuleDelegate Czech = n => + ( + (n == 1) + ? 0 + : (n >= 2 && n <= 4) + ? 1 + : 2 + ); public static readonly PluralizationRuleDelegate English = n => (n == 1) ? 0 : 1; - public static readonly PluralizationRuleDelegate Arabic = n => (n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5); + public static readonly PluralizationRuleDelegate Arabic = n => + ( + n == 0 + ? 0 + : n == 1 + ? 1 + : n == 2 + ? 2 + : n % 100 >= 3 && n % 100 <= 10 + ? 3 + : n % 100 >= 11 + ? 4 + : 5 + ); } diff --git a/test/OrchardCore.Tests/Localization/PoParserTests.cs b/test/OrchardCore.Tests/Localization/PoParserTests.cs index f392905e5b1..07c2b3ace4d 100644 --- a/test/OrchardCore.Tests/Localization/PoParserTests.cs +++ b/test/OrchardCore.Tests/Localization/PoParserTests.cs @@ -122,7 +122,10 @@ public void ParseHandlesMultilineEntry() var entries = ParseText("EntryWithMultilineText"); Assert.Equal("Here is an example of how one might continue a very long string\nfor the common case the string represents multi-line output.", entries[0].Key); - Assert.Equal("Here is an example of how one might continue a very long translation\nfor the common case the string represents multi-line output.", entries[0].Translations[0]); + Assert.Equal( + "Here is an example of how one might continue a very long translation\nfor the common case the string represents multi-line output.", + entries[0].Translations[0] + ); } [Fact] @@ -173,8 +176,14 @@ public void ParseReadsPluralAndMultilineText() var entries = ParseText("EntryWithPluralAndMultilineText"); Assert.Equal("Here is an example of how one might continue a very long string\nfor the common case the string represents multi-line output.", entries[0].Key); - Assert.Equal("Here is an example of how one might continue a very long translation\nfor the common case the string represents multi-line output.", entries[0].Translations[0]); - Assert.Equal("Here are examples of how one might continue a very long translation\nfor the common case the string represents multi-line output.", entries[0].Translations[1]); + Assert.Equal( + "Here is an example of how one might continue a very long translation\nfor the common case the string represents multi-line output.", + entries[0].Translations[0] + ); + Assert.Equal( + "Here are examples of how one might continue a very long translation\nfor the common case the string represents multi-line output.", + entries[0].Translations[1] + ); } [Fact] diff --git a/test/OrchardCore.Tests/Localization/PortableObjectStringLocalizerFactoryTests.cs b/test/OrchardCore.Tests/Localization/PortableObjectStringLocalizerFactoryTests.cs index 50f35a1734d..638344e86f2 100644 --- a/test/OrchardCore.Tests/Localization/PortableObjectStringLocalizerFactoryTests.cs +++ b/test/OrchardCore.Tests/Localization/PortableObjectStringLocalizerFactoryTests.cs @@ -5,8 +5,7 @@ namespace OrchardCore.Tests.Localization public class PortableObjectStringLocalizerFactoryTests { [Fact] - public async Task LocalizerReturnsTranslationFromInnerClass() - => await StartupRunner.Run(typeof(PortableObjectStringLocalizerFactory), "ar", "مرحبا"); + public async Task LocalizerReturnsTranslationFromInnerClass() => await StartupRunner.Run(typeof(PortableObjectStringLocalizerFactory), "ar", "مرحبا"); public class PortableObjectStringLocalizerFactory { @@ -23,21 +22,17 @@ public void ConfigureServices(IServiceCollection services) #pragma warning disable CA1822 // Mark members as static public void Configure( #pragma warning restore CA1822 // Mark members as static - IApplicationBuilder app, - IStringLocalizer localizer) + IApplicationBuilder app, IStringLocalizer localizer) { var supportedCultures = new[] { "ar", "en" }; - app.UseRequestLocalization(options => - options - .AddSupportedCultures(supportedCultures) - .AddSupportedUICultures(supportedCultures) - .SetDefaultCulture("ar") - ); + app.UseRequestLocalization(options => options.AddSupportedCultures(supportedCultures).AddSupportedUICultures(supportedCultures).SetDefaultCulture("ar")); - app.Run(async (context) => - { - await context.Response.WriteAsync(localizer["Hello"]); - }); + app.Run( + async (context) => + { + await context.Response.WriteAsync(localizer["Hello"]); + } + ); } } diff --git a/test/OrchardCore.Tests/Localization/PortableObjectStringLocalizerTests.cs b/test/OrchardCore.Tests/Localization/PortableObjectStringLocalizerTests.cs index be361129d41..ae589012f14 100644 --- a/test/OrchardCore.Tests/Localization/PortableObjectStringLocalizerTests.cs +++ b/test/OrchardCore.Tests/Localization/PortableObjectStringLocalizerTests.cs @@ -17,14 +17,11 @@ public PortableObjectStringLocalizerTests() [Fact] public void LocalizerReturnsTranslationsFromProvidedDictionary() { - SetupDictionary("cs", new[] { - new CultureDictionaryRecord("ball", "míč", "míče", "míčů") - }); + SetupDictionary("cs", new[] { new CultureDictionaryRecord("ball", "míč", "míče", "míčů") }); var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("cs")) { - var translation = localizer["ball"]; Assert.Equal("míč", translation); @@ -34,9 +31,7 @@ public void LocalizerReturnsTranslationsFromProvidedDictionary() [Fact] public void LocalizerReturnsOriginalTextIfTranslationsDoesntExistInProvidedDictionary() { - SetupDictionary("cs", new[] { - new CultureDictionaryRecord("ball", "míč", "míče", "míčů") - }); + SetupDictionary("cs", new[] { new CultureDictionaryRecord("ball", "míč", "míče", "míčů") }); var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("cs")) @@ -64,13 +59,9 @@ public void LocalizerReturnsOriginalTextIfDictionaryIsEmpty() [Fact] public void LocalizerFallbacksToParentCultureIfTranslationDoesntExistInSpecificCulture() { - SetupDictionary("cs", new[] { - new CultureDictionaryRecord("ball", "míč", "míče", "míčů") - }); + SetupDictionary("cs", new[] { new CultureDictionaryRecord("ball", "míč", "míče", "míčů") }); - SetupDictionary("cs-CZ", new[] { - new CultureDictionaryRecord("car", "auto", "auta", "aut") - }); + SetupDictionary("cs-CZ", new[] { new CultureDictionaryRecord("car", "auto", "auta", "aut") }); var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("cs-cz")) @@ -84,13 +75,9 @@ public void LocalizerFallbacksToParentCultureIfTranslationDoesntExistInSpecificC [Fact] public void LocalizerReturnsTranslationFromSpecificCultureIfItExists() { - SetupDictionary("cs", new[] { - new CultureDictionaryRecord("ball", "míč", "míče", "míčů") - }); + SetupDictionary("cs", new[] { new CultureDictionaryRecord("ball", "míč", "míče", "míčů") }); - SetupDictionary("cs-CZ", new[] { - new CultureDictionaryRecord("ball", "balón", "balóny", "balónů") - }); + SetupDictionary("cs-CZ", new[] { new CultureDictionaryRecord("ball", "balón", "balóny", "balónů") }); var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("cs-CZ")) @@ -104,10 +91,7 @@ public void LocalizerReturnsTranslationFromSpecificCultureIfItExists() [Fact] public void LocalizerReturnsTranslationWithSpecificContext() { - SetupDictionary("cs", new[] { - new CultureDictionaryRecord("ball", "míč", "míče", "míčů"), - new CultureDictionaryRecord("ball", "small", ["míček", "míčky", "míčků"]) - }); + SetupDictionary("cs", new[] { new CultureDictionaryRecord("ball", "míč", "míče", "míčů"), new CultureDictionaryRecord("ball", "small", ["míček", "míčky", "míčků"]) }); var localizer = new PortableObjectStringLocalizer("small", _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("cs")) @@ -121,10 +105,7 @@ public void LocalizerReturnsTranslationWithSpecificContext() [Fact] public void LocalizerReturnsTranslationWithoutContextIfTranslationWithContextDoesntExist() { - SetupDictionary("cs", new[] { - new CultureDictionaryRecord("ball", "míč", "míče", "míčů"), - new CultureDictionaryRecord("ball", "big", ["míček", "míčky", "míčků"]) - }); + SetupDictionary("cs", new[] { new CultureDictionaryRecord("ball", "míč", "míče", "míčů"), new CultureDictionaryRecord("ball", "big", ["míček", "míčky", "míčků"]) }); var localizer = new PortableObjectStringLocalizer("small", _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("cs")) @@ -138,9 +119,7 @@ public void LocalizerReturnsTranslationWithoutContextIfTranslationWithContextDoe [Fact] public void LocalizerReturnsFormattedTranslation() { - SetupDictionary("cs", new[] { - new CultureDictionaryRecord("The page (ID:{0}) was deleted.", "Stránka (ID:{0}) byla smazána.") - }); + SetupDictionary("cs", new[] { new CultureDictionaryRecord("The page (ID:{0}) was deleted.", "Stránka (ID:{0}) byla smazána.") }); var localizer = new PortableObjectStringLocalizer("small", _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("cs")) @@ -154,9 +133,7 @@ public void LocalizerReturnsFormattedTranslation() [Fact] public void HtmlLocalizerDoesNotFormatTwiceIfFormattedTranslationContainsCurlyBraces() { - SetupDictionary("cs", new[] { - new CultureDictionaryRecord("The page (ID:{0}) was deleted.", "Stránka (ID:{0}) byla smazána.") - }); + SetupDictionary("cs", new[] { new CultureDictionaryRecord("The page (ID:{0}) was deleted.", "Stránka (ID:{0}) byla smazána.") }); var localizer = new PortableObjectStringLocalizer("small", _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("cs")) @@ -186,9 +163,7 @@ public void HtmlLocalizerDoesNotFormatTwiceIfFormattedTranslationContainsCurlyBr [InlineData("cars", 2)] public void LocalizerReturnsOriginalTextForPluralIfTranslationDoesntExist(string expected, int count) { - SetupDictionary("cs", new[] { - new CultureDictionaryRecord("ball", "míč", "míče", "míčů"), - }); + SetupDictionary("cs", new[] { new CultureDictionaryRecord("ball", "míč", "míče", "míčů"), }); var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("cs")) @@ -224,9 +199,7 @@ public void LocalizerReturnsCorrectTranslationForPluralIfNoPluralFormsSpecified( [InlineData("5 míčů", 5)] public void LocalizerReturnsTranslationInCorrectPluralForm(string expected, int count) { - SetupDictionary("cs", new[] { - new CultureDictionaryRecord("ball", "míč", "{0} míče", "{0} míčů"), - }); + SetupDictionary("cs", new[] { new CultureDictionaryRecord("ball", "míč", "{0} míče", "{0} míčů"), }); var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("cs")) @@ -259,10 +232,7 @@ public void LocalizerReturnsOriginalValuesIfTranslationDoesntExistAndMultiplePlu [InlineData("2 balls", 2)] public void LocalizerReturnsCorrectPluralFormIfMultiplePluraflFormsAreSpecified(string expected, int count) { - SetupDictionary("en", new CultureDictionaryRecord[] - { - new("míč", "ball", "{0} balls") - }, PluralizationRule.English); + SetupDictionary("en", new CultureDictionaryRecord[] { new("míč", "ball", "{0} balls") }, PluralizationRule.English); var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object); using (CultureScope.Create("en")) @@ -278,10 +248,7 @@ public void LocalizerReturnsCorrectPluralFormIfMultiplePluraflFormsAreSpecified( [InlineData(true, "hello", "مرحبا")] public void LocalizerFallBackToParentCultureIfFallBackToParentUICulturesIsTrue(bool fallBackToParentCulture, string resourceKey, string expected) { - SetupDictionary("ar", new CultureDictionaryRecord[] - { - new("hello", "مرحبا") - }, PluralizationRule.Arabic); + SetupDictionary("ar", new CultureDictionaryRecord[] { new("hello", "مرحبا") }, PluralizationRule.Arabic); SetupDictionary("ar-YE", Array.Empty(), PluralizationRule.Arabic); @@ -299,19 +266,13 @@ public void LocalizerFallBackToParentCultureIfFallBackToParentUICulturesIsTrue(b [InlineData(true, new[] { "مدونة", "منتج", "قائمة", "صفحة", "مقالة" })] public void LocalizerReturnsGetAllStrings(bool includeParentCultures, string[] expected) { - SetupDictionary("ar", new CultureDictionaryRecord[] - { - new("Blog", "مدونة"), - new("Menu", "قائمة"), - new("Page", "صفحة"), - new("Article", "مقالة") - }, PluralizationRule.Arabic); + SetupDictionary( + "ar", + new CultureDictionaryRecord[] { new("Blog", "مدونة"), new("Menu", "قائمة"), new("Page", "صفحة"), new("Article", "مقالة") }, + PluralizationRule.Arabic + ); - SetupDictionary("ar-YE", new CultureDictionaryRecord[] - { - new("Blog", "مدونة"), - new("Product", "منتج") - }, PluralizationRule.Arabic); + SetupDictionary("ar-YE", new CultureDictionaryRecord[] { new("Blog", "مدونة"), new("Product", "منتج") }, PluralizationRule.Arabic); var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, false, _logger.Object); using (CultureScope.Create("ar-YE")) @@ -323,8 +284,7 @@ public void LocalizerReturnsGetAllStrings(bool includeParentCultures, string[] e } [Fact] - public async Task PortableObjectStringLocalizerShouldRegisterIStringLocalizerOfT() - => await StartupRunner.Run(typeof(PortableObjectLocalizationStartup), "en", "Hello"); + public async Task PortableObjectStringLocalizerShouldRegisterIStringLocalizerOfT() => await StartupRunner.Run(typeof(PortableObjectLocalizationStartup), "en", "Hello"); [Theory] [InlineData("ar", 1)] @@ -348,11 +308,10 @@ public void LocalizerWithContextShouldCallGetDictionaryOncePerCulture(string cul Assert.Equal("Hello", translation); } - private static bool TryGetRuleFromDefaultPluralRuleProvider(CultureInfo culture, out PluralizationRuleDelegate rule) - => ((IPluralRuleProvider)new DefaultPluralRuleProvider()).TryGetRule(culture, out rule); + private static bool TryGetRuleFromDefaultPluralRuleProvider(CultureInfo culture, out PluralizationRuleDelegate rule) => + ((IPluralRuleProvider)new DefaultPluralRuleProvider()).TryGetRule(culture, out rule); - private void SetupDictionary(string cultureName, IEnumerable records) - => SetupDictionary(cultureName, records, PluralizationRule.Czech); + private void SetupDictionary(string cultureName, IEnumerable records) => SetupDictionary(cultureName, records, PluralizationRule.Czech); private void SetupDictionary(string cultureName, IEnumerable records, PluralizationRuleDelegate pluralRule) { @@ -375,21 +334,17 @@ public void ConfigureServices(IServiceCollection services) #pragma warning disable CA1822 // Mark members as static public void Configure( #pragma warning restore CA1822 // Mark members as static - IApplicationBuilder app, - IStringLocalizer localizer) + IApplicationBuilder app, IStringLocalizer localizer) { var supportedCultures = new[] { "ar", "en" }; - app.UseRequestLocalization(options => - options - .AddSupportedCultures(supportedCultures) - .AddSupportedUICultures(supportedCultures) - .SetDefaultCulture("en") - ); + app.UseRequestLocalization(options => options.AddSupportedCultures(supportedCultures).AddSupportedUICultures(supportedCultures).SetDefaultCulture("en")); - app.Run(async (context) => - { - await context.Response.WriteAsync(localizer["Hello"]); - }); + app.Run( + async (context) => + { + await context.Response.WriteAsync(localizer["Hello"]); + } + ); } } } diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Contents/Feeds/RssFeedTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Contents/Feeds/RssFeedTests.cs index 2e46b5e8878..4cc282459ee 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Contents/Feeds/RssFeedTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Contents/Feeds/RssFeedTests.cs @@ -19,21 +19,11 @@ public async Task AvoidDoubleEncodeCDATA(string format) var commonFeedItemBuilder = new CommonFeedItemBuilder(contentManagerMock.Object); var feedContext = CreateFeedContext(format); - contentManagerMock.SetReturnsDefault(Task.FromResult(new ContentItemMetadata - { - DisplayRouteValues = [] - })); - - contentManagerMock.SetReturnsDefault(Task.FromResult(new BodyAspect - { - Body = new HtmlString("

The news description goes here ...

") - })); - - feedContext.Builder.AddItem(feedContext, new ContentItem - { - DisplayText = "News", - PublishedUtc = DateTime.UtcNow - }); + contentManagerMock.SetReturnsDefault(Task.FromResult(new ContentItemMetadata { DisplayRouteValues = [] })); + + contentManagerMock.SetReturnsDefault(Task.FromResult(new BodyAspect { Body = new HtmlString("

The news description goes here ...

") })); + + feedContext.Builder.AddItem(feedContext, new ContentItem { DisplayText = "News", PublishedUtc = DateTime.UtcNow }); // Act await commonFeedItemBuilder.PopulateAsync(feedContext); @@ -55,21 +45,11 @@ public async Task ShouldOnlyHtmlEntityEscapeFeedTitle(string format) var commonFeedItemBuilder = new CommonFeedItemBuilder(contentManagerMock.Object); var feedContext = CreateFeedContext(format); - contentManagerMock.SetReturnsDefault(Task.FromResult(new ContentItemMetadata - { - DisplayRouteValues = [] - })); - - contentManagerMock.SetReturnsDefault(Task.FromResult(new BodyAspect - { - Body = new HtmlString("

The news description goes here ...

") - })); - - feedContext.Builder.AddItem(feedContext, new ContentItem - { - DisplayText = "It's a great title & so much > than anybody's!", - PublishedUtc = DateTime.UtcNow - }); + contentManagerMock.SetReturnsDefault(Task.FromResult(new ContentItemMetadata { DisplayRouteValues = [] })); + + contentManagerMock.SetReturnsDefault(Task.FromResult(new BodyAspect { Body = new HtmlString("

The news description goes here ...

") })); + + feedContext.Builder.AddItem(feedContext, new ContentItem { DisplayText = "It's a great title & so much > than anybody's!", PublishedUtc = DateTime.UtcNow }); // Act await commonFeedItemBuilder.PopulateAsync(feedContext); diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Email/Workflows/EmailTaskTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Email/Workflows/EmailTaskTests.cs index ea181507ea0..a22d8d05267 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Email/Workflows/EmailTaskTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Email/Workflows/EmailTaskTests.cs @@ -15,25 +15,13 @@ public async Task ExecuteTask_WhenToAndCcAndBccAreNotSet_ShouldFails() { // Arrange var smtpService = CreateSmtpService(new SmtpSettings()); - var task = new EmailTask( - smtpService, - new SimpleWorkflowExpressionEvaluator(), - Mock.Of>(), - HtmlEncoder.Default) + var task = new EmailTask(smtpService, new SimpleWorkflowExpressionEvaluator(), Mock.Of>(), HtmlEncoder.Default) { Subject = new WorkflowExpression("Test"), Body = new WorkflowExpression("Test message!!") }; - var executionContext = new WorkflowExecutionContext( - new WorkflowType(), - new Workflow(), - _emptyDictionary, - _emptyDictionary, - _emptyDictionary, - [], - default, - []); + var executionContext = new WorkflowExecutionContext(new WorkflowType(), new Workflow(), _emptyDictionary, _emptyDictionary, _emptyDictionary, [], default, []); var activityContext = Mock.Of(); // Act @@ -57,8 +45,8 @@ private static ISmtpService CreateSmtpService(SmtpSettings settings) private class SimpleWorkflowExpressionEvaluator : IWorkflowExpressionEvaluator { - public async Task EvaluateAsync(WorkflowExpression expression, WorkflowExecutionContext workflowContext, TextEncoder encoder) - => await Task.FromResult((T)Convert.ChangeType(expression.Expression, typeof(T))); + public async Task EvaluateAsync(WorkflowExpression expression, WorkflowExecutionContext workflowContext, TextEncoder encoder) => + await Task.FromResult((T)Convert.ChangeType(expression.Expression, typeof(T))); } } } diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Media/AssetUrlShortcodeTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Media/AssetUrlShortcodeTests.cs index abd8ee63602..f301bf86056 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Media/AssetUrlShortcodeTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Media/AssetUrlShortcodeTests.cs @@ -23,16 +23,14 @@ public class AssetUrlShortcodeTests [InlineData("", @"foo [asset_url width=""100"" height=""50"" mode=""stretch""]bar[/asset_url] baz", @"foo /media/bar?width=100&height=50&rmode=stretch baz")] [InlineData("", "foo [asset_url]bar[/asset_url] baz foo [asset_url]bar[/asset_url] baz", @"foo /media/bar baz foo /media/bar baz")] [InlineData("", @"foo baz", @"foo baz")] - [InlineData("", @"foo baz", @"foo baz")] + [InlineData( + "", + @"foo baz", + @"foo baz" + )] public async Task ShouldProcess(string cdnBaseUrl, string text, string expected) { - var fileStore = new DefaultMediaFileStore( - Mock.Of(), - "/media", - cdnBaseUrl, - [], - [], - Mock.Of>()); + var fileStore = new DefaultMediaFileStore(Mock.Of(), "/media", cdnBaseUrl, [], [], Mock.Of>()); var sanitizer = new HtmlSanitizerService(Options.Create(new HtmlSanitizerOptions())); @@ -55,7 +53,10 @@ public async Task ShouldProcess(string cdnBaseUrl, string text, string expected) [Theory] [InlineData(@"foo baz", @"foo baz")] // Sanitizing strips the closing shortcode tag when it finds onload. This is fine, as the user cannot expect a good shortcode when they attempt xss - [InlineData(@"foo baz", @"foo baz")] + [InlineData( + @"foo baz", + @"foo baz" + )] public void ShouldSanitizeUnprocessed(string text, string expected) { // The html parts santize on save, so do not process the shortcode first. diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Media/ImageShortcodeTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Media/ImageShortcodeTests.cs index 6e7a442be38..f10151c5479 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Media/ImageShortcodeTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Media/ImageShortcodeTests.cs @@ -28,10 +28,22 @@ public class ImageShortcodeTests [InlineData("", @"foo [image width=""100"" height=""50"" mode=""stretch""]bar[/image] baz", @"foo baz")] [InlineData("", @"foo [image class=""className""]bar[/image] baz", @"foo baz")] [InlineData("", @"foo [image alt=""text""]bar[/image] baz", @"foo baz")] - [InlineData("", @"foo [image width=""100"" height=""50"" mode=""stretch"" alt=""text"" class=""className""]bar[/image] baz", @"foo baz")] + [InlineData( + "", + @"foo [image width=""100"" height=""50"" mode=""stretch"" alt=""text"" class=""className""]bar[/image] baz", + @"foo baz" + )] [InlineData("", "foo [image]bar[/image] baz foo [image]bar[/image] baz", @"foo baz foo baz")] - [InlineData("", "foo [image]bar[/image] baz foo [image]bar[/image] baz foo [image]bar[/image] baz", @"foo baz foo baz foo baz")] - [InlineData("", "foo [image]bar.png[/image] baz foo-extended [image]bar-extended.png[/image] baz-extended", @"foo baz foo-extended baz-extended")] + [InlineData( + "", + "foo [image]bar[/image] baz foo [image]bar[/image] baz foo [image]bar[/image] baz", + @"foo baz foo baz foo baz" + )] + [InlineData( + "", + "foo [image]bar.png[/image] baz foo-extended [image]bar-extended.png[/image] baz-extended", + @"foo baz foo-extended baz-extended" + )] [InlineData("", "foo [media]bar[/media] baz foo [image]bar[/image] baz", @"foo baz foo baz")] [InlineData("", "foo [image]bàr.jpeg?width=100[/image] baz", @"foo baz")] [InlineData("", "foo [image]bàr.jpeg?width=100 onload=\"javascript: alert('XSS')\"[/image] baz", @"foo baz")] @@ -40,13 +52,7 @@ public async Task ShouldProcess(string cdnBaseUrl, string text, string expected) var sanitizerOptions = new HtmlSanitizerOptions(); sanitizerOptions.Configure.Add(opt => opt.AllowedAttributes.Add("class")); - var fileStore = new DefaultMediaFileStore( - Mock.Of(), - "/media", - cdnBaseUrl, - [], - [], - Mock.Of>()); + var fileStore = new DefaultMediaFileStore(Mock.Of(), "/media", cdnBaseUrl, [], [], Mock.Of>()); var fileVersionProvider = Mock.Of(); diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Media/MediaEventTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Media/MediaEventTests.cs index 1ecf93db761..2f19dbde9d0 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Media/MediaEventTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Media/MediaEventTests.cs @@ -8,11 +8,7 @@ public class MediaEventTests public async Task DisposesMediaCreatingStreams() { var streams = new List(); - var creatingEventHandlers = new List() - { - new TestMediaEventHandler(), - new TestMediaEventHandler() - }; + var creatingEventHandlers = new List() { new TestMediaEventHandler(), new TestMediaEventHandler() }; Stream originalStream = null; @@ -31,10 +27,7 @@ public async Task DisposesMediaCreatingStreams() var outputStream = inputStream; try { - var context = new MediaCreatingContext - { - Path = path - }; + var context = new MediaCreatingContext { Path = path }; foreach (var eventHandler in creatingEventHandlers) { diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Media/MediaTokenTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Media/MediaTokenTests.cs index c4a36598795..cfe05f0f865 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Media/MediaTokenTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Media/MediaTokenTests.cs @@ -80,10 +80,7 @@ public class MediaTokenTests public MediaTokenTests() { - _mediaTokenSettings = new MediaTokenSettings - { - HashKey = _hashKey, - }; + _mediaTokenSettings = new MediaTokenSettings { HashKey = _hashKey, }; } [Theory] diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/ApplicationControllerTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/ApplicationControllerTests.cs index da001c03095..36cd56209dc 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/ApplicationControllerTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/ApplicationControllerTests.cs @@ -22,7 +22,8 @@ public async Task UsersShouldNotBeAbleToCreateIfNotAllowed() Mock.Of(), Mock.Of>(), Mock.Of(), - Mock.Of()); + Mock.Of() + ); var result = await controller.Create(); Assert.IsType(result); @@ -43,7 +44,8 @@ public async Task UsersShouldBeAbleToCreateApplicationIfAllowed() mockOpenIdScopeManager.Object, Mock.Of>(), Mock.Of(), - Mock.Of()) + Mock.Of() + ) { ControllerContext = CreateControllerContext(), }; @@ -68,7 +70,8 @@ public async Task ConfidentionalClientNeedsSecret(string clientType, string clie Mock.Of(), Mock.Of>(), Mock.Of(), - Mock.Of()) + Mock.Of() + ) { ControllerContext = CreateControllerContext(), }; @@ -109,7 +112,8 @@ public async Task RedirectUrisAreValid(string uris, bool expectValidModel) Mock.Of(), Mock.Of>(), Mock.Of(), - Mock.Of()) + Mock.Of() + ) { ControllerContext = CreateControllerContext(), }; @@ -146,7 +150,9 @@ public Mock MockAuthorizationServiceMock() { var securityMock = new Mock(MockBehavior.Strict); - securityMock.Setup(x => x.AuthorizeAsync(It.IsAny(), It.IsAny(), It.IsAny>())).Returns(Task.FromResult(AuthorizationResult.Success())); + securityMock + .Setup(x => x.AuthorizeAsync(It.IsAny(), It.IsAny(), It.IsAny>())) + .Returns(Task.FromResult(AuthorizationResult.Success())); securityMock.Setup(x => x.AuthorizeAsync(It.IsAny(), It.IsAny(), It.IsAny())).Returns(Task.FromResult(AuthorizationResult.Success())); return securityMock; } @@ -156,10 +162,7 @@ public ControllerContext CreateControllerContext() var mockContext = new Mock(MockBehavior.Loose); mockContext.SetupGet(hc => hc.User).Returns(new ClaimsPrincipal()); - return new ControllerContext() - { - HttpContext = mockContext.Object, - }; + return new ControllerContext() { HttpContext = mockContext.Object, }; } public Mock> MockStringLocalizer() diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdApplicationStepTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdApplicationStepTests.cs index 8bb3535a655..b3bc6712a9b 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdApplicationStepTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdApplicationStepTests.cs @@ -18,43 +18,24 @@ public async Task OpenIdApplicationCanBeParsed(string recipeName, OpenIdApplicat OpenIdApplicationDescriptor actual = null; var appManagerMock = new Mock(MockBehavior.Strict); - appManagerMock.Setup(m => - m.FindByClientIdAsync( - It.IsAny(), - It.IsAny())) - .Returns( - new ValueTask(actual)); - - appManagerMock.Setup(m => - m.CreateAsync( - It.IsAny(), - It.IsAny())) - .Callback((app, c) => - actual = (OpenIdApplicationDescriptor)app) - .Returns( - new ValueTask(actual)); + appManagerMock.Setup(m => m.FindByClientIdAsync(It.IsAny(), It.IsAny())).Returns(new ValueTask(actual)); + + appManagerMock + .Setup(m => m.CreateAsync(It.IsAny(), It.IsAny())) + .Callback((app, c) => actual = (OpenIdApplicationDescriptor)app) + .Returns(new ValueTask(actual)); var step = new OpenIdApplicationStep(appManagerMock.Object); var recipe = JsonNode.Parse(GetRecipeFileContent(recipeName)); - var context = new RecipeExecutionContext - { - Name = recipe["steps"][0].Value("name"), - Step = (JsonObject)recipe["steps"][0], - }; + var context = new RecipeExecutionContext { Name = recipe["steps"][0].Value("name"), Step = (JsonObject)recipe["steps"][0], }; // Act await step.ExecuteAsync(context); // Assert - appManagerMock.Verify(m => - m.FindByClientIdAsync( - It.Is(ci => ci == expected.ClientId), - It.IsAny())); + appManagerMock.Verify(m => m.FindByClientIdAsync(It.Is(ci => ci == expected.ClientId), It.IsAny())); - appManagerMock.Verify(m => - m.CreateAsync( - It.IsAny(), - It.IsAny())); + appManagerMock.Verify(m => m.CreateAsync(It.IsAny(), It.IsAny())); Assert.Equal(expected.ClientId, actual.ClientId); Assert.Equal(expected.ClientSecret, actual.ClientSecret); @@ -73,18 +54,10 @@ public async Task OpenIdApplicationCanBeUpdated() // Arrange var recipeName = "app-recipe3"; var clientId = "a1"; - var expected = new OpenIdApplicationDescriptor - { - ClientId = clientId, - DisplayName = "Expected Name" - }; + var expected = new OpenIdApplicationDescriptor { ClientId = clientId, DisplayName = "Expected Name" }; expected.RedirectUris.UnionWith(new[] { new Uri("https://localhost/redirect") }); - var actual = new OpenIdApplicationDescriptor - { - ClientId = clientId, - DisplayName = "Actual Name" - }; + var actual = new OpenIdApplicationDescriptor { ClientId = clientId, DisplayName = "Actual Name" }; actual.RedirectUris.UnionWith(new[] { new Uri("https://localhost/x") }); actual.Roles.UnionWith(new[] { "x" }); actual.Permissions.UnionWith(new[] { $"{OpenIddictConstants.Permissions.Prefixes.Scope}x" }); @@ -100,53 +73,26 @@ public async Task OpenIdApplicationCanBeUpdated() var appManagerMock = new Mock(MockBehavior.Strict); - appManagerMock.Setup(m => - m.FindByClientIdAsync( - It.IsAny(), - It.IsAny())) - .Returns( - new ValueTask(actualDb)); - - appManagerMock.Setup(m => - m.PopulateAsync( - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Returns( - new ValueTask()); - - appManagerMock.Setup(m => - m.UpdateAsync( - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Callback((app, desc, c) => - actual = (OpenIdApplicationDescriptor)desc) - .Returns( - new ValueTask()); + appManagerMock.Setup(m => m.FindByClientIdAsync(It.IsAny(), It.IsAny())).Returns(new ValueTask(actualDb)); + + appManagerMock.Setup(m => m.PopulateAsync(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new ValueTask()); + + appManagerMock + .Setup(m => m.UpdateAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((app, desc, c) => actual = (OpenIdApplicationDescriptor)desc) + .Returns(new ValueTask()); var step = new OpenIdApplicationStep(appManagerMock.Object); var recipe = JsonNode.Parse(GetRecipeFileContent(recipeName)); - var context = new RecipeExecutionContext - { - Name = recipe["steps"][0].Value("name"), - Step = (JsonObject)recipe["steps"][0], - }; + var context = new RecipeExecutionContext { Name = recipe["steps"][0].Value("name"), Step = (JsonObject)recipe["steps"][0], }; // Act await step.ExecuteAsync(context); // Assert - appManagerMock.Verify(m => - m.FindByClientIdAsync( - It.Is(ci => ci == expected.ClientId), - It.IsAny())); + appManagerMock.Verify(m => m.FindByClientIdAsync(It.Is(ci => ci == expected.ClientId), It.IsAny())); - appManagerMock.Verify(m => - m.UpdateAsync( - It.IsAny(), - It.IsAny(), - It.IsAny())); + appManagerMock.Verify(m => m.UpdateAsync(It.IsAny(), It.IsAny(), It.IsAny())); Assert.Equal(expected.ClientId, actual.ClientId); Assert.Equal(expected.ClientSecret, actual.ClientSecret); @@ -161,9 +107,7 @@ public async Task OpenIdApplicationCanBeUpdated() private string GetRecipeFileContent(string recipeName) { - return new EmbeddedFileProvider(GetType().Assembly) - .GetFileInfo($"Modules.OrchardCore.OpenId.RecipeFiles.{recipeName}.json") - .ReadToEnd(); + return new EmbeddedFileProvider(GetType().Assembly).GetFileInfo($"Modules.OrchardCore.OpenId.RecipeFiles.{recipeName}.json").ReadToEnd(); } } } diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdApplicationStepTestsData.cs b/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdApplicationStepTestsData.cs index 390189c499e..108b9790aa3 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdApplicationStepTestsData.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdApplicationStepTestsData.cs @@ -2,8 +2,7 @@ namespace OrchardCore.Tests.Modules.OrchardCore.OpenId { - internal class OpenIdApplicationStepTestsData - : TheoryData + internal class OpenIdApplicationStepTestsData : TheoryData { public OpenIdApplicationStepTestsData() { @@ -20,14 +19,16 @@ public OpenIdApplicationStepTestsData() new[] { new Uri("https://localhost:111/logout-redirect"), new Uri("https://localhost:222/logout-redirect") }, new[] { new Uri("https://localhost:111/redirect"), new Uri("https://localhost:222/redirect") }, null, - new[] { + new[] + { OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.GrantTypes.RefreshToken, OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.Endpoints.Logout, OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.ResponseTypes.Code, - }); + } + ); AddWithHashsets( "app-recipe2", @@ -42,11 +43,13 @@ public OpenIdApplicationStepTestsData() new[] { new Uri("https://localhost/logout-redirect") }, new[] { new Uri("https://localhost/redirect") }, new[] { "role1", "role2" }, - new[] { + new[] + { OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.Endpoints.Token, $"{OpenIddictConstants.Permissions.Prefixes.Scope}scope1" - }); + } + ); } private static void UnionIfNotNull(ISet itemSet, IEnumerable items) @@ -63,7 +66,8 @@ private void AddWithHashsets( IEnumerable postLogoutRedirectUris, IEnumerable redirectUris, IEnumerable roles, - IEnumerable permissions) + IEnumerable permissions + ) { UnionIfNotNull(app.PostLogoutRedirectUris, postLogoutRedirectUris); UnionIfNotNull(app.RedirectUris, redirectUris); diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdScopeStepTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdScopeStepTests.cs index 486edb0a2c8..2d1aef089ec 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdScopeStepTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdScopeStepTests.cs @@ -12,9 +12,7 @@ public class OpenIdScopeStepTests { private string GetRecipeFileContent(string recipeName) { - return new EmbeddedFileProvider(GetType().Assembly) - .GetFileInfo($"Modules.OrchardCore.OpenId.RecipeFiles.{recipeName}.json") - .ReadToEnd(); + return new EmbeddedFileProvider(GetType().Assembly).GetFileInfo($"Modules.OrchardCore.OpenId.RecipeFiles.{recipeName}.json").ReadToEnd(); } private static OpenIdScopeDescriptor CreateScopeDescriptor(string name, string suffix, params string[] resources) @@ -35,48 +33,28 @@ public async Task OpenIdScopeCanBeParsed() // Arrange // Match expected with scope-recipe.json - var expected = CreateScopeDescriptor( - "test_scope", "A", "res1", "res2", "res3"); + var expected = CreateScopeDescriptor("test_scope", "A", "res1", "res2", "res3"); OpenIdScopeDescriptor actual = null; var scopeManagerMock = new Mock(MockBehavior.Strict); - scopeManagerMock.Setup(m => - m.FindByNameAsync( - It.IsAny(), - It.IsAny())) - .Returns( - new ValueTask(actual)); - - scopeManagerMock.Setup(m => - m.CreateAsync( - It.IsAny(), - It.IsAny())) - .Callback((s, c) => - actual = (OpenIdScopeDescriptor)s) - .Returns( - new ValueTask()); + scopeManagerMock.Setup(m => m.FindByNameAsync(It.IsAny(), It.IsAny())).Returns(new ValueTask(actual)); + + scopeManagerMock + .Setup(m => m.CreateAsync(It.IsAny(), It.IsAny())) + .Callback((s, c) => actual = (OpenIdScopeDescriptor)s) + .Returns(new ValueTask()); var step = new OpenIdScopeStep(scopeManagerMock.Object); var recipe = JsonNode.Parse(GetRecipeFileContent("scope-recipe")); - var context = new RecipeExecutionContext - { - Name = recipe["steps"][0].Value("name"), - Step = (JsonObject)recipe["steps"][0], - }; + var context = new RecipeExecutionContext { Name = recipe["steps"][0].Value("name"), Step = (JsonObject)recipe["steps"][0], }; // Act await step.ExecuteAsync(context); // Assert - scopeManagerMock.Verify(m => - m.FindByNameAsync( - It.Is(v => v == expected.Name), - It.IsAny())); + scopeManagerMock.Verify(m => m.FindByNameAsync(It.Is(v => v == expected.Name), It.IsAny())); - scopeManagerMock.Verify(m => - m.CreateAsync( - It.IsAny(), - It.IsAny())); + scopeManagerMock.Verify(m => m.CreateAsync(It.IsAny(), It.IsAny())); Assert.Equal(expected.Name, actual.Name); Assert.Equal(expected.DisplayName, actual.DisplayName); @@ -91,70 +69,33 @@ public async Task OpenIdScopeCanBeUpdated() // Match expected with scope-recipe.json var scopeName = "test_scope"; - var expected = CreateScopeDescriptor( - scopeName, "A", "res1", "res2", "res3"); - var actual = CreateScopeDescriptor( - scopeName, "B", "res"); - var dbActual = new OpenIdScope - { - Name = actual.Name, - Resources = actual.Resources.ToImmutableArray() - }; + var expected = CreateScopeDescriptor(scopeName, "A", "res1", "res2", "res3"); + var actual = CreateScopeDescriptor(scopeName, "B", "res"); + var dbActual = new OpenIdScope { Name = actual.Name, Resources = actual.Resources.ToImmutableArray() }; var scopeManagerMock = new Mock(MockBehavior.Strict); - scopeManagerMock.Setup(m => - m.FindByNameAsync( - It.IsAny(), - It.IsAny())) - .Returns( - new ValueTask(dbActual)); - - scopeManagerMock.Setup(m => - m.PopulateAsync( - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Returns( - new ValueTask()); - - scopeManagerMock.Setup(m => - m.UpdateAsync( - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Callback((s, desc, c) => - actual = (OpenIdScopeDescriptor)desc) - .Returns( - new ValueTask()); + scopeManagerMock.Setup(m => m.FindByNameAsync(It.IsAny(), It.IsAny())).Returns(new ValueTask(dbActual)); + + scopeManagerMock.Setup(m => m.PopulateAsync(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new ValueTask()); + + scopeManagerMock + .Setup(m => m.UpdateAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((s, desc, c) => actual = (OpenIdScopeDescriptor)desc) + .Returns(new ValueTask()); var step = new OpenIdScopeStep(scopeManagerMock.Object); var recipe = JsonNode.Parse(GetRecipeFileContent("scope-recipe")); - var context = new RecipeExecutionContext - { - Name = recipe["steps"][0].Value("name"), - Step = (JsonObject)recipe["steps"][0], - }; + var context = new RecipeExecutionContext { Name = recipe["steps"][0].Value("name"), Step = (JsonObject)recipe["steps"][0], }; // Act await step.ExecuteAsync(context); // Assert - scopeManagerMock.Verify(m => - m.FindByNameAsync( - It.Is(v => v == expected.Name), - It.IsAny())); - - scopeManagerMock.Verify(m => - m.PopulateAsync( - It.IsAny(), - It.IsAny(), - It.IsAny())); - - scopeManagerMock.Verify(m => - m.UpdateAsync( - It.IsAny(), - It.IsAny(), - It.IsAny())); + scopeManagerMock.Verify(m => m.FindByNameAsync(It.Is(v => v == expected.Name), It.IsAny())); + + scopeManagerMock.Verify(m => m.PopulateAsync(It.IsAny(), It.IsAny(), It.IsAny())); + + scopeManagerMock.Verify(m => m.UpdateAsync(It.IsAny(), It.IsAny(), It.IsAny())); Assert.Equal(expected.Name, actual.Name); Assert.Equal(expected.DisplayName, actual.DisplayName); diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdServerDeploymentSourceTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdServerDeploymentSourceTests.cs index 8cc39a4d739..66bdedf872b 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdServerDeploymentSourceTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.OpenId/OpenIdServerDeploymentSourceTests.cs @@ -13,11 +13,7 @@ public class OpenIdServerDeploymentSourceTests { private static OpenIdServerSettings CreateSettings(string authority, OpenIdServerSettings.TokenFormat tokenFormat, bool initializeAllProperties) { - var result = new OpenIdServerSettings - { - Authority = new Uri(authority), - AccessTokenFormat = tokenFormat - }; + var result = new OpenIdServerSettings { Authority = new Uri(authority), AccessTokenFormat = tokenFormat }; if (initializeAllProperties) { @@ -56,13 +52,9 @@ private static Mock CreateServerServiceWithSettingsMock(Op { var serverService = new Mock(); - serverService - .Setup(m => m.GetSettingsAsync()) - .ReturnsAsync(settings); + serverService.Setup(m => m.GetSettingsAsync()).ReturnsAsync(settings); - serverService - .Setup(m => m.LoadSettingsAsync()) - .ReturnsAsync(settings); + serverService.Setup(m => m.LoadSettingsAsync()).ReturnsAsync(settings); return serverService; } @@ -79,14 +71,11 @@ public async Task ServerDeploymentSourceIsReadableByRecipe() var actualSettings = CreateSettings("https://recipe.localhost", OpenIdServerSettings.TokenFormat.DataProtection, false); var recipeServerServiceMock = CreateServerServiceWithSettingsMock(actualSettings); - var settingsProperties = typeof(OpenIdServerSettings) - .GetProperties(); + var settingsProperties = typeof(OpenIdServerSettings).GetProperties(); foreach (var property in settingsProperties) { - Assert.NotEqual( - property.GetValue(expectedSettings), - property.GetValue(actualSettings)); + Assert.NotEqual(property.GetValue(expectedSettings), property.GetValue(actualSettings)); } var fileBuilder = new MemoryFileBuilder(); @@ -99,10 +88,7 @@ public async Task ServerDeploymentSourceIsReadableByRecipe() await deploymentSource.ProcessDeploymentStepAsync(new OpenIdServerDeploymentStep(), result); await result.FinalizeAsync(); - var deploy = JsonNode.Parse( - fileBuilder.GetFileContents( - recipeFile, - Encoding.UTF8)); + var deploy = JsonNode.Parse(fileBuilder.GetFileContents(recipeFile, Encoding.UTF8)); var recipeContext = new RecipeExecutionContext { @@ -117,9 +103,7 @@ public async Task ServerDeploymentSourceIsReadableByRecipe() // Assert foreach (var property in settingsProperties) { - Assert.Equal( - property.GetValue(expectedSettings), - property.GetValue(actualSettings)); + Assert.Equal(property.GetValue(expectedSettings), property.GetValue(actualSettings)); } } } diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Roles/RolesMockHelper.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Roles/RolesMockHelper.cs index fc1131de564..99728459d5e 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Roles/RolesMockHelper.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Roles/RolesMockHelper.cs @@ -7,10 +7,7 @@ public static Mock> MockRoleManager() { var store = new Mock>().Object; - var validators = new List> - { - new RoleValidator(), - }; + var validators = new List> { new RoleValidator(), }; return new Mock>(store, validators, new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), null); } diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Roles/RolesPermissionsHandlerTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Roles/RolesPermissionsHandlerTests.cs index 17c340ebbec..4f6e61437c0 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Roles/RolesPermissionsHandlerTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Roles/RolesPermissionsHandlerTests.cs @@ -18,22 +18,8 @@ public async Task GrantsRolesPermissions(string required, bool authenticated, bo var context = PermissionHandlerHelper.CreateTestAuthorizationHandlerContext(new Permission(required), authenticated: authenticated); var permissionHandler = CreatePermissionHandler( - new Role - { - RoleName = "Anonymous", - RoleClaims = - [ - new() { ClaimType = Permission.ClaimType, ClaimValue = "AllowAnonymous" } - ] - }, - new Role - { - RoleName = "Authenticated", - RoleClaims = - [ - new() { ClaimType = Permission.ClaimType, ClaimValue = "AllowAuthenticated" } - ] - } + new Role { RoleName = "Anonymous", RoleClaims = [new() { ClaimType = Permission.ClaimType, ClaimValue = "AllowAnonymous" }] }, + new Role { RoleName = "Authenticated", RoleClaims = [new() { ClaimType = Permission.ClaimType, ClaimValue = "AllowAuthenticated" }] } ); // Act @@ -71,14 +57,7 @@ public async Task GrantsInheritedPermissions() var context = PermissionHandlerHelper.CreateTestAuthorizationHandlerContext(required); var permissionHandler = CreatePermissionHandler( - new Role - { - RoleName = "Anonymous", - RoleClaims = - [ - new() { ClaimType = Permission.ClaimType, ClaimValue = "Implicit2" } - ] - } + new Role { RoleName = "Anonymous", RoleClaims = [new() { ClaimType = Permission.ClaimType, ClaimValue = "Implicit2" }] } ); // Act @@ -97,22 +76,8 @@ public async Task IsCaseIsensitive(string required, bool authenticated) var context = PermissionHandlerHelper.CreateTestAuthorizationHandlerContext(new Permission(required), authenticated: authenticated); var permissionHandler = CreatePermissionHandler( - new Role - { - RoleName = "Anonymous", - RoleClaims = - [ - new() { ClaimType = Permission.ClaimType, ClaimValue = "aLlOwAnOnYmOuS" } - ] - }, - new Role - { - RoleName = "Authenticated", - RoleClaims = - [ - new() { ClaimType = Permission.ClaimType, ClaimValue = "aLlOwAuThEnTiCaTeD" } - ] - } + new Role { RoleName = "Anonymous", RoleClaims = [new() { ClaimType = Permission.ClaimType, ClaimValue = "aLlOwAnOnYmOuS" }] }, + new Role { RoleName = "Authenticated", RoleClaims = [new() { ClaimType = Permission.ClaimType, ClaimValue = "aLlOwAuThEnTiCaTeD" }] } ); // Act diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Rules/RuleTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Rules/RuleTests.cs index 10250a0b980..28513609f39 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Rules/RuleTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Rules/RuleTests.cs @@ -31,19 +31,9 @@ public async Task ShouldEvaluateRuleFalseWhenNoConditions() [InlineData("/notthehomepage", false, true)] public async Task ShouldEvaluateHomepage(string path, bool isHomepage, bool expected) { - var rule = new Rule - { - Conditions = - [ - new HomepageCondition - { - Value = isHomepage - } - ] - }; + var rule = new Rule { Conditions = [new HomepageCondition { Value = isHomepage }] }; - var services = CreateRuleServiceCollection() - .AddCondition>(); + var services = CreateRuleServiceCollection().AddCondition>(); var mockHttpContextAccessor = new Mock(); var context = new DefaultHttpContext(); @@ -64,16 +54,9 @@ public async Task ShouldEvaluateHomepage(string path, bool isHomepage, bool expe [InlineData(false, false)] public async Task ShouldEvaluateBoolean(bool boolean, bool expected) { - var rule = new Rule - { - Conditions = - [ - new BooleanCondition { Value = boolean } - ] - }; + var rule = new Rule { Conditions = [new BooleanCondition { Value = boolean }] }; - var services = CreateRuleServiceCollection() - .AddCondition>(); + var services = CreateRuleServiceCollection().AddCondition>(); var serviceProvider = services.BuildServiceProvider(); @@ -88,20 +71,7 @@ public async Task ShouldEvaluateBoolean(bool boolean, bool expected) [InlineData(false, false, false)] public async Task ShouldEvaluateAny(bool first, bool second, bool expected) { - var rule = new Rule - { - Conditions = - [ - new AnyConditionGroup - { - Conditions = - [ - new BooleanCondition { Value = first }, - new BooleanCondition { Value = second } - ] - } - ] - }; + var rule = new Rule { Conditions = [new AnyConditionGroup { Conditions = [new BooleanCondition { Value = first }, new BooleanCondition { Value = second }] }] }; var services = CreateRuleServiceCollection() .AddCondition>() @@ -119,20 +89,9 @@ public async Task ShouldEvaluateAny(bool first, bool second, bool expected) [InlineData("/bar", "/foo", false)] public async Task ShouldEvaluateUrlEquals(string path, string requestPath, bool expected) { - var rule = new Rule - { - Conditions = - [ - new UrlCondition - { - Value = path, - Operation = new StringEqualsOperator() - } - ] - }; + var rule = new Rule { Conditions = [new UrlCondition { Value = path, Operation = new StringEqualsOperator() }] }; - var services = CreateRuleServiceCollection() - .AddCondition>(); + var services = CreateRuleServiceCollection().AddCondition>(); var mockHttpContextAccessor = new Mock(); var context = new DefaultHttpContext(); @@ -153,16 +112,7 @@ public async Task ShouldEvaluateUrlEquals(string path, string requestPath, bool [InlineData("isHomepage()", "/foo", false)] public async Task ShouldEvaluateJavascriptCondition(string script, string requestPath, bool expected) { - var rule = new Rule - { - Conditions = - [ - new JavascriptCondition - { - Script = script - } - ] - }; + var rule = new Rule { Conditions = [new JavascriptCondition { Script = script }] }; var services = CreateRuleServiceCollection() .AddCondition>() diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Search.AzureAI/NamingTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Search.AzureAI/NamingTests.cs index 03a17523998..a91ababcc42 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Search.AzureAI/NamingTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Search.AzureAI/NamingTests.cs @@ -10,8 +10,6 @@ public class NamingTests [Fact] public void CreateLengthSafeIndexName() { - - var isValid1 = AzureAISearchIndexNamingHelper.TryGetSafeIndexName(_maxName, out var result1); Assert.True(isValid1); diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Security/Extensions/SecurityHeadersApplicationBuilderExtensionsTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Security/Extensions/SecurityHeadersApplicationBuilderExtensionsTests.cs index 9ce20790e65..57f009d0bcb 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Security/Extensions/SecurityHeadersApplicationBuilderExtensionsTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Security/Extensions/SecurityHeadersApplicationBuilderExtensionsTests.cs @@ -14,9 +14,7 @@ public void SecurityHeadersShouldBeAddedWithDefaultValues() // Act applicationBuilder.UseSecurityHeaders(); - applicationBuilder - .Build() - .Invoke(context); + applicationBuilder.Build().Invoke(context); // Assert Assert.Equal(SecurityHeaderDefaults.ContentSecurityPolicy, context.Response.Headers[SecurityHeaderNames.ContentSecurityPolicy]); @@ -52,14 +50,18 @@ public void SecurityHeadersShouldAddedAccordingSuppliedOptions() // Act applicationBuilder.UseSecurityHeaders(options); - applicationBuilder - .Build() - .Invoke(context); + applicationBuilder.Build().Invoke(context); // Assert - Assert.Equal("child-src 'none',connect-src 'self' https://www.domain1.com https://www.domain2.com,default-src *", context.Response.Headers[SecurityHeaderNames.ContentSecurityPolicy]); + Assert.Equal( + "child-src 'none',connect-src 'self' https://www.domain1.com https://www.domain2.com,default-src *", + context.Response.Headers[SecurityHeaderNames.ContentSecurityPolicy] + ); Assert.Equal(ContentTypeOptionsValue.NoSniff, context.Response.Headers[SecurityHeaderNames.XContentTypeOptions]); - Assert.Equal("camera=self,microphone=*,speaker-selection=self https://www.domain1.com https://www.domain2.com", context.Response.Headers[SecurityHeaderNames.PermissionsPolicy]); + Assert.Equal( + "camera=self,microphone=*,speaker-selection=self https://www.domain1.com https://www.domain2.com", + context.Response.Headers[SecurityHeaderNames.PermissionsPolicy] + ); Assert.Equal(ReferrerPolicyValue.Origin, context.Response.Headers[SecurityHeaderNames.ReferrerPolicy]); } @@ -76,21 +78,24 @@ public void SecurityHeadersShouldBeAddedAccordingBuildConfiguration() config .AddContentSecurityPolicy("child-src 'none'", "connect-src 'self' https://www.domain1.com https://www.domain2.com", "default-src *") .AddContentTypeOptions() - .AddPermissionsPolicy(new Dictionary - { - { "camera", "self"}, - { "microphone", "*" }, - { "speaker", "self https://www.domain1.com https://www.domain2.com"} - }) + .AddPermissionsPolicy( + new Dictionary + { + { "camera", "self" }, + { "microphone", "*" }, + { "speaker", "self https://www.domain1.com https://www.domain2.com" } + } + ) .AddReferrerPolicy(ReferrerPolicyValue.Origin); }); - applicationBuilder - .Build() - .Invoke(context); + applicationBuilder.Build().Invoke(context); // Assert - Assert.Equal("child-src 'none',connect-src 'self' https://www.domain1.com https://www.domain2.com,default-src *", context.Response.Headers[SecurityHeaderNames.ContentSecurityPolicy]); + Assert.Equal( + "child-src 'none',connect-src 'self' https://www.domain1.com https://www.domain2.com,default-src *", + context.Response.Headers[SecurityHeaderNames.ContentSecurityPolicy] + ); Assert.Equal(ContentTypeOptionsValue.NoSniff, context.Response.Headers[SecurityHeaderNames.XContentTypeOptions]); Assert.Equal("camera=self,microphone=*,speaker=self https://www.domain1.com https://www.domain2.com", context.Response.Headers[SecurityHeaderNames.PermissionsPolicy]); Assert.Equal(ReferrerPolicyValue.Origin, context.Response.Headers[SecurityHeaderNames.ReferrerPolicy]); diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Security/SecurityHeadersMiddlewareTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Security/SecurityHeadersMiddlewareTests.cs index 843d746a6df..281fafa76ff 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Security/SecurityHeadersMiddlewareTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Security/SecurityHeadersMiddlewareTests.cs @@ -8,28 +8,75 @@ public class SecurityMiddlewareTests public static IEnumerable ContentSecurityPolicies => new List { - new object[] { new[] { $"{ContentSecurityPolicyValue.BaseUri} {ContentSecurityPolicyOriginValue.None}"}, "base-uri 'none'" }, - new object[] { new[] { $"{ContentSecurityPolicyValue.ChildSource} {ContentSecurityPolicyOriginValue.Self}"}, "child-src 'self'" }, - new object[] { new[] { $"{ContentSecurityPolicyValue.ConnectSource} {ContentSecurityPolicyOriginValue.Self} https://www.domain.com/" }, "connect-src 'self' https://www.domain.com/" }, - new object[] { new[] { $"{ContentSecurityPolicyValue.DefaultSource} {ContentSecurityPolicyOriginValue.Self} https://www.domain1.com/ https://www.domain2.com/" }, "default-src 'self' https://www.domain1.com/ https://www.domain2.com/" }, - new object[] { new[] { $"{ContentSecurityPolicyValue.FontSource} {ContentSecurityPolicyOriginValue.Any}"}, "font-src *" }, - new object[] { new[] { $"{ContentSecurityPolicyValue.ScriptSource} {ContentSecurityPolicyOriginValue.Self} https://www.domain.com/", $"{ContentSecurityPolicyValue.StyleSource} {ContentSecurityPolicyOriginValue.Self} https://www.domain.com/" }, "script-src 'self' https://www.domain.com/,style-src 'self' https://www.domain.com/" }, - new object[] { new[] { $"{ContentSecurityPolicyValue.Sandbox}"}, "sandbox" }, + new object[] { new[] { $"{ContentSecurityPolicyValue.BaseUri} {ContentSecurityPolicyOriginValue.None}" }, "base-uri 'none'" }, + new object[] { new[] { $"{ContentSecurityPolicyValue.ChildSource} {ContentSecurityPolicyOriginValue.Self}" }, "child-src 'self'" }, + new object[] + { + new[] { $"{ContentSecurityPolicyValue.ConnectSource} {ContentSecurityPolicyOriginValue.Self} https://www.domain.com/" }, + "connect-src 'self' https://www.domain.com/" + }, + new object[] + { + new[] { $"{ContentSecurityPolicyValue.DefaultSource} {ContentSecurityPolicyOriginValue.Self} https://www.domain1.com/ https://www.domain2.com/" }, + "default-src 'self' https://www.domain1.com/ https://www.domain2.com/" + }, + new object[] { new[] { $"{ContentSecurityPolicyValue.FontSource} {ContentSecurityPolicyOriginValue.Any}" }, "font-src *" }, + new object[] + { + new[] + { + $"{ContentSecurityPolicyValue.ScriptSource} {ContentSecurityPolicyOriginValue.Self} https://www.domain.com/", + $"{ContentSecurityPolicyValue.StyleSource} {ContentSecurityPolicyOriginValue.Self} https://www.domain.com/" + }, + "script-src 'self' https://www.domain.com/,style-src 'self' https://www.domain.com/" + }, + new object[] { new[] { $"{ContentSecurityPolicyValue.Sandbox}" }, "sandbox" }, new object[] { new[] { $"{ContentSecurityPolicyValue.Sandbox} allow-scripts" }, "sandbox allow-scripts" }, - new object[] { new[] { $"{ContentSecurityPolicyValue.UpgradeInsecureRequests}"}, "upgrade-insecure-requests" }, + new object[] { new[] { $"{ContentSecurityPolicyValue.UpgradeInsecureRequests}" }, "upgrade-insecure-requests" }, }; public static IEnumerable PermissionsPolicies => new List { - new object[] { new[] { $"{PermissionsPolicyValue.Accelerometer}={PermissionsPolicyOriginValue.None}"}, "accelerometer=()" }, - new object[] { new[] { $"{PermissionsPolicyValue.AmbientLightSensor}={PermissionsPolicyOriginValue.Any}"}, "ambient-light-sensor=*" }, - new object[] { new[] { $"{PermissionsPolicyValue.Camera}={PermissionsPolicyOriginValue.Self}"}, "camera=self" }, - new object[] { new[] { $"{PermissionsPolicyValue.EncryptedMedia}={PermissionsPolicyOriginValue.Self} https://www.domain.com" }, "encrypted-media=self https://www.domain.com" }, - new object[] { new[] { $"{PermissionsPolicyValue.FullScreen}={PermissionsPolicyOriginValue.Self} https://www.domain.com https://www.sub.domain.com" }, "fullscreen=self https://www.domain.com https://www.sub.domain.com" }, - new object[] { new[] { $"{PermissionsPolicyValue.Geolocation}={PermissionsPolicyOriginValue.None}", $"{PermissionsPolicyValue.Gyroscope}={PermissionsPolicyOriginValue.Any}" }, "geolocation=(),gyroscope=*" }, - new object[] { new[] { $"{PermissionsPolicyValue.Magnetometer}={PermissionsPolicyOriginValue.None}", $"{PermissionsPolicyValue.Microphone}={PermissionsPolicyOriginValue.Any}", $"{PermissionsPolicyValue.Midi}={PermissionsPolicyOriginValue.Self}" }, "magnetometer=(),microphone=*,midi=self" }, - new object[] { new[] { $"{PermissionsPolicyValue.Usb}={PermissionsPolicyOriginValue.Self}", $"{PermissionsPolicyValue.Payment}={PermissionsPolicyOriginValue.Self} https://www.domain.com", $"{PermissionsPolicyValue.PictureInPicture}={PermissionsPolicyOriginValue.Self}", $"{PermissionsPolicyValue.Push}={PermissionsPolicyOriginValue.Self} https://www.domain.com https://www.sub.domain.com" }, "usb=self,payment=self https://www.domain.com,picture-in-picture=self,push=self https://www.domain.com https://www.sub.domain.com" } + new object[] { new[] { $"{PermissionsPolicyValue.Accelerometer}={PermissionsPolicyOriginValue.None}" }, "accelerometer=()" }, + new object[] { new[] { $"{PermissionsPolicyValue.AmbientLightSensor}={PermissionsPolicyOriginValue.Any}" }, "ambient-light-sensor=*" }, + new object[] { new[] { $"{PermissionsPolicyValue.Camera}={PermissionsPolicyOriginValue.Self}" }, "camera=self" }, + new object[] + { + new[] { $"{PermissionsPolicyValue.EncryptedMedia}={PermissionsPolicyOriginValue.Self} https://www.domain.com" }, + "encrypted-media=self https://www.domain.com" + }, + new object[] + { + new[] { $"{PermissionsPolicyValue.FullScreen}={PermissionsPolicyOriginValue.Self} https://www.domain.com https://www.sub.domain.com" }, + "fullscreen=self https://www.domain.com https://www.sub.domain.com" + }, + new object[] + { + new[] { $"{PermissionsPolicyValue.Geolocation}={PermissionsPolicyOriginValue.None}", $"{PermissionsPolicyValue.Gyroscope}={PermissionsPolicyOriginValue.Any}" }, + "geolocation=(),gyroscope=*" + }, + new object[] + { + new[] + { + $"{PermissionsPolicyValue.Magnetometer}={PermissionsPolicyOriginValue.None}", + $"{PermissionsPolicyValue.Microphone}={PermissionsPolicyOriginValue.Any}", + $"{PermissionsPolicyValue.Midi}={PermissionsPolicyOriginValue.Self}" + }, + "magnetometer=(),microphone=*,midi=self" + }, + new object[] + { + new[] + { + $"{PermissionsPolicyValue.Usb}={PermissionsPolicyOriginValue.Self}", + $"{PermissionsPolicyValue.Payment}={PermissionsPolicyOriginValue.Self} https://www.domain.com", + $"{PermissionsPolicyValue.PictureInPicture}={PermissionsPolicyOriginValue.Self}", + $"{PermissionsPolicyValue.Push}={PermissionsPolicyOriginValue.Self} https://www.domain.com https://www.sub.domain.com" + }, + "usb=self,payment=self https://www.domain.com,picture-in-picture=self,push=self https://www.domain.com https://www.sub.domain.com" + } }; public static IEnumerable ReferrerPolicies => @@ -50,10 +97,7 @@ public class SecurityMiddlewareTests public async Task ContentSecurityPolicyHeaderShouldBeAdded(string[] contentSecurityPolicies, string expectedValue) { // Arrange - var options = new SecurityHeadersOptions - { - ContentSecurityPolicy = contentSecurityPolicies - }; + var options = new SecurityHeadersOptions { ContentSecurityPolicy = contentSecurityPolicies }; var middleware = new SecurityHeadersMiddleware(options, Request); var context = new DefaultHttpContext(); @@ -69,10 +113,7 @@ public async Task ContentSecurityPolicyHeaderShouldBeAdded(string[] contentSecur public async Task ContentTypeOptionsHeaderShouldBeAdded() { // Arrange - var options = new SecurityHeadersOptions - { - ContentTypeOptions = ContentTypeOptionsValue.NoSniff - }; + var options = new SecurityHeadersOptions { ContentTypeOptions = ContentTypeOptionsValue.NoSniff }; var middleware = new SecurityHeadersMiddleware(options, Request); var context = new DefaultHttpContext(); @@ -89,10 +130,7 @@ public async Task ContentTypeOptionsHeaderShouldBeAdded() public async Task PermissionsPolicyHeaderShouldBeAdded(string[] permissionsPolicies, string expectedValue) { // Arrange - var options = new SecurityHeadersOptions - { - PermissionsPolicy = permissionsPolicies - }; + var options = new SecurityHeadersOptions { PermissionsPolicy = permissionsPolicies }; var middleware = new SecurityHeadersMiddleware(options, Request); var context = new DefaultHttpContext(); @@ -109,10 +147,7 @@ public async Task PermissionsPolicyHeaderShouldBeAdded(string[] permissionsPolic public async Task ReferrerPolicyHeaderShouldBeAdded(string policy, string expectedValue) { // Arrange - var options = new SecurityHeadersOptions - { - ReferrerPolicy = policy - }; + var options = new SecurityHeadersOptions { ReferrerPolicy = policy }; var middleware = new SecurityHeadersMiddleware(options, Request); var context = new DefaultHttpContext(); diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Tenants/ApiControllerTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Tenants/ApiControllerTests.cs index a7a95049239..37410f4ed9a 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Tenants/ApiControllerTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Tenants/ApiControllerTests.cs @@ -15,10 +15,7 @@ public class ApiControllerTests { private readonly Dictionary _shellSettings = []; private readonly Mock _clockMock = new(); - private readonly Dictionary _featureProfiles = new() - { - { "Feature Profile", new FeatureProfile() } - }; + private readonly Dictionary _featureProfiles = new() { { "Feature Profile", new FeatureProfile() } }; private delegate void TryGetSettingsCallback(string name, out ShellSettings settings); @@ -42,9 +39,7 @@ public async Task CallCreateApiMultipleTimes_ShouldCreateTenant_ReturnsSetupToke Assert.True(controller.ModelState.IsValid); Assert.IsType(result); - var token1 = (result as OkObjectResult).Value - .ToString() - .Split("token=")?[1]; + var token1 = (result as OkObjectResult).Value.ToString().Split("token=")?[1]; Assert.NotNull(token1); @@ -55,9 +50,7 @@ public async Task CallCreateApiMultipleTimes_ShouldCreateTenant_ReturnsSetupToke Assert.True(controller.ModelState.IsValid); Assert.IsType(result); - var token2 = (result as CreatedResult).Location - .ToString() - .Split("token=")?[1]; + var token2 = (result as CreatedResult).Location.ToString().Split("token=")?[1]; Assert.NotNull(token2); Assert.Equal(token1, token2); @@ -83,9 +76,7 @@ public async Task ShouldGetNewTenantSetupToken_WhenThePreviousTokenExpired() Assert.True(controller.ModelState.IsValid); Assert.IsType(result); - var token1 = (result as OkObjectResult).Value - .ToString() - .Split("token=")?[1]; + var token1 = (result as OkObjectResult).Value.ToString().Split("token=")?[1]; Assert.NotNull(token1); @@ -99,9 +90,7 @@ public async Task ShouldGetNewTenantSetupToken_WhenThePreviousTokenExpired() Assert.True(controller.ModelState.IsValid); Assert.IsType(result); - var token2 = (result as CreatedResult).Location - .ToString() - .Split("token=")?[1]; + var token2 = (result as CreatedResult).Location.ToString().Split("token=")?[1]; Assert.NotNull(token2); Assert.NotEqual(token1, token2); @@ -109,14 +98,10 @@ public async Task ShouldGetNewTenantSetupToken_WhenThePreviousTokenExpired() private ApiController CreateController() { - var defaultShellSettings = new ShellSettings() - .AsDefaultShell() - .AsRunning(); + var defaultShellSettings = new ShellSettings().AsDefaultShell().AsRunning(); var shellHostMock = new Mock(); - shellHostMock - .Setup(host => host.UpdateShellSettingsAsync(It.IsAny())) - .Callback(settings => _shellSettings.Add(settings.Name, settings)); + shellHostMock.Setup(host => host.UpdateShellSettingsAsync(It.IsAny())).Callback(settings => _shellSettings.Add(settings.Name, settings)); var _ = It.IsAny(); shellHostMock @@ -125,39 +110,29 @@ private ApiController CreateController() .Returns((name, _) => _shellSettings.ContainsKey(name)); var shellSettingsManagerMock = new Mock(); - shellSettingsManagerMock - .Setup(shellSettingsManager => shellSettingsManager.CreateDefaultSettings()) - .Returns(defaultShellSettings); + shellSettingsManagerMock.Setup(shellSettingsManager => shellSettingsManager.CreateDefaultSettings()).Returns(defaultShellSettings); var dataProtectionProviderMock = new Mock(); - dataProtectionProviderMock - .Setup(dataProtectionProvider => dataProtectionProvider.CreateProtector(It.IsAny())) - .Returns(new FakeDataProtector()); + dataProtectionProviderMock.Setup(dataProtectionProvider => dataProtectionProvider.CreateProtector(It.IsAny())).Returns(new FakeDataProtector()); var authorizeServiceMock = new Mock(); authorizeServiceMock - .Setup(authorizeService => authorizeService.AuthorizeAsync( - It.IsAny(), - It.IsAny(), - It.IsAny>())) + .Setup(authorizeService => authorizeService.AuthorizeAsync(It.IsAny(), It.IsAny(), It.IsAny>())) .ReturnsAsync(AuthorizationResult.Success); var featureProfilesService = new Mock(); - featureProfilesService - .Setup(featureProfiles => featureProfiles.GetFeatureProfilesAsync()) - .ReturnsAsync(_featureProfiles); + featureProfilesService.Setup(featureProfiles => featureProfiles.GetFeatureProfilesAsync()).ReturnsAsync(_featureProfiles); var stringLocalizerMock = new Mock>(); - stringLocalizerMock - .Setup(localizer => localizer[It.IsAny()]) - .Returns((string name) => new LocalizedString(name, name)); + stringLocalizerMock.Setup(localizer => localizer[It.IsAny()]).Returns((string name) => new LocalizedString(name, name)); var tenantValidator = new TenantValidator( shellHostMock.Object, shellSettingsManagerMock.Object, featureProfilesService.Object, Mock.Of(), - stringLocalizerMock.Object); + stringLocalizerMock.Object + ); return new ApiController( shellHostMock.Object, @@ -174,7 +149,8 @@ private ApiController CreateController() [], tenantValidator, Mock.Of>(), - Mock.Of>()) + Mock.Of>() + ) { ControllerContext = new ControllerContext { HttpContext = CreateHttpContext() } }; @@ -182,15 +158,9 @@ private ApiController CreateController() private static HttpContext CreateHttpContext() { - var httpContext = new DefaultHttpContext - { - User = new ClaimsPrincipal() - }; + var httpContext = new DefaultHttpContext { User = new ClaimsPrincipal() }; - httpContext.Features.Set(new ShellContextFeature - { - OriginalPathBase = PathString.Empty - }); + httpContext.Features.Set(new ShellContextFeature { OriginalPathBase = PathString.Empty }); httpContext.User.AddIdentity(new ClaimsIdentity()); diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Tenants/Services/TenantValidatorTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Tenants/Services/TenantValidatorTests.cs index 849ed49fc92..5875c392a0c 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Tenants/Services/TenantValidatorTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Tenants/Services/TenantValidatorTests.cs @@ -9,9 +9,7 @@ namespace OrchardCore.Modules.Tenants.Services.Tests { public class TenantValidatorTests : SiteContext { - static TenantValidatorTests() - { - } + static TenantValidatorTests() { } [Theory] [InlineData("Tenant1", "tenant1", "", "Feature Profile", new[] { "A tenant with the same name already exists." })] @@ -27,7 +25,13 @@ static TenantValidatorTests() [InlineData("@Invalid Tenant", "tenant7", "example1.com", "Feature Profile", new[] { "Invalid tenant name. Must contain characters only and no spaces." })] [InlineData("Tenant7", null, " ", "Feature Profile", new[] { "A tenant with the same host and prefix already exists." })] [InlineData("Tenant7", "/tenant7", "", "Feature Profile", new[] { "The url prefix can not contain more than one segment." })] - [InlineData("@Invalid Tenant", "/tenant7", "", "Feature Profile", new[] { "Invalid tenant name. Must contain characters only and no spaces.", "The url prefix can not contain more than one segment." })] + [InlineData( + "@Invalid Tenant", + "/tenant7", + "", + "Feature Profile", + new[] { "Invalid tenant name. Must contain characters only and no spaces.", "The url prefix can not contain more than one segment." } + )] [InlineData("Tenant8", "tenant4", "example6.com,example4.com, example5.com", "Feature Profile", new[] { "A tenant with the same host and prefix already exists." })] [InlineData("Tenant9", "tenant9", "", "Feature Profile", new string[] { })] [InlineData("Tenant9", "", "example6.com", "Feature Profile", new string[] { })] @@ -101,44 +105,51 @@ public async Task DuplicateTenantHostOrPrefixShouldFailValidation(bool isNewTena private static TenantValidator CreateTenantValidator(bool defaultTenant = true) { var featureProfilesServiceMock = new Mock(); - featureProfilesServiceMock.Setup(fp => fp.GetFeatureProfilesAsync()) - .Returns(Task.FromResult((IDictionary)new Dictionary - { - { "Feature Profile", new FeatureProfile() } - })); + featureProfilesServiceMock + .Setup(fp => fp.GetFeatureProfilesAsync()) + .Returns(Task.FromResult((IDictionary)new Dictionary { { "Feature Profile", new FeatureProfile() } })); var stringLocalizerMock = new Mock>(); - stringLocalizerMock - .Setup(l => l[It.IsAny()]) - .Returns(n => new LocalizedString(n, n)); - stringLocalizerMock - .Setup(l => l[It.IsAny(), It.IsAny()]) - .Returns((n, a) => new LocalizedString(n, n)); + stringLocalizerMock.Setup(l => l[It.IsAny()]).Returns(n => new LocalizedString(n, n)); + stringLocalizerMock.Setup(l => l[It.IsAny(), It.IsAny()]).Returns((n, a) => new LocalizedString(n, n)); - var shellSettings = defaultTenant - ? ShellHost.GetSettings(ShellSettings.DefaultShellName) - : new ShellSettings(); + var shellSettings = defaultTenant ? ShellHost.GetSettings(ShellSettings.DefaultShellName) : new ShellSettings(); var dbConnectionValidatorMock = new Mock(); var validationContext = new DbConnectionValidatorContext(shellSettings); dbConnectionValidatorMock.Setup(v => v.ValidateAsync(validationContext)); - return new TenantValidator( - ShellHost, - ShellSettingsManager, - featureProfilesServiceMock.Object, - dbConnectionValidatorMock.Object, - stringLocalizerMock.Object - ); + return new TenantValidator(ShellHost, ShellSettingsManager, featureProfilesServiceMock.Object, dbConnectionValidatorMock.Object, stringLocalizerMock.Object); } private static async Task SeedTenantsAsync() { await ShellHost.GetOrCreateShellContextAsync(new ShellSettings { Name = "Tenant1", RequestUrlPrefix = "tenant1" }.AsUninitialized()); - await ShellHost.GetOrCreateShellContextAsync(new ShellSettings { Name = "Tenant2", RequestUrlPrefix = string.Empty, RequestUrlHost = "example2.com" }.AsUninitialized()); - await ShellHost.GetOrCreateShellContextAsync(new ShellSettings { Name = "Tenant3", RequestUrlPrefix = "tenant3", RequestUrlHost = string.Empty }.AsUninitialized()); - await ShellHost.GetOrCreateShellContextAsync(new ShellSettings { Name = "Tenant4", RequestUrlPrefix = "tenant4", RequestUrlHost = "example4.com, example5.com" }.AsUninitialized()); + await ShellHost.GetOrCreateShellContextAsync( + new ShellSettings + { + Name = "Tenant2", + RequestUrlPrefix = string.Empty, + RequestUrlHost = "example2.com" + }.AsUninitialized() + ); + await ShellHost.GetOrCreateShellContextAsync( + new ShellSettings + { + Name = "Tenant3", + RequestUrlPrefix = "tenant3", + RequestUrlHost = string.Empty + }.AsUninitialized() + ); + await ShellHost.GetOrCreateShellContextAsync( + new ShellSettings + { + Name = "Tenant4", + RequestUrlPrefix = "tenant4", + RequestUrlHost = "example4.com, example5.com" + }.AsUninitialized() + ); } } } diff --git a/test/OrchardCore.Tests/Modules/OrchardCore.Twitter/TwitterClientTests.cs b/test/OrchardCore.Tests/Modules/OrchardCore.Twitter/TwitterClientTests.cs index aaca240d555..f3773f3c921 100644 --- a/test/OrchardCore.Tests/Modules/OrchardCore.Twitter/TwitterClientTests.cs +++ b/test/OrchardCore.Tests/Modules/OrchardCore.Twitter/TwitterClientTests.cs @@ -7,12 +7,15 @@ namespace OrchardCore.Tests.Modules.OrchardCore.Twitter { public class TwitterClientTests { - private const string ExpectedOauthHeader = "OAuth oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", oauth_signature=\"hCtSmYh%2BiHYCEqBWrE7C7hYmtUk%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1318622958\", oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", oauth_version=\"1.0\""; - private const string UpdateStatusResponse = "{\r\n \"created_at\": \"Fri Jan 25 22:04:26 +0000 2019\",\r\n \"id\": 1088920554520961000,\r\n \"id_str\": \"1088920554520961026\",\r\n \"text\": \"okay\",\r\n \"truncated\": false,\r\n \"entities\": {\r\n \"hashtags\": [],\r\n \"symbols\": [],\r\n \"user_mentions\": [],\r\n \"urls\": []\r\n },\r\n \"source\": \"Learning Twitter API - Jess Gars\",\r\n \"in_reply_to_status_id\": null,\r\n \"in_reply_to_status_id_str\": null,\r\n \"in_reply_to_user_id\": null,\r\n \"in_reply_to_user_id_str\": null,\r\n \"in_reply_to_screen_name\": null,\r\n \"user\": {\r\n \"id\": 15772978,\r\n \"id_str\": \"15772978\",\r\n \"name\": \"Jessica Garson\uD83E\uDD95\",\r\n \"screen_name\": \"jessicagarson\",\r\n \"location\": \"Brooklyn, NY\",\r\n \"description\": \"Developer Advocate @Twitter. Python programmer. Noted thought leader on vegan snacks. Known sometimes as Messica Arson. She/They.\",\r\n \"url\": \"https://t.co/ai7MDeRPa5\",\r\n \"entities\": {\r\n \"url\": {\r\n \"urls\": [\r\n {\r\n \"url\": \"https://t.co/ai7MDeRPa5\",\r\n \"expanded_url\": \"http://jessicagarson.com\",\r\n \"display_url\": \"jessicagarson.com\",\r\n \"indices\": [\r\n 0,\r\n 23\r\n ]\r\n }\r\n ]\r\n },\r\n \"description\": {\r\n \"urls\": []\r\n }\r\n },\r\n \"protected\": false,\r\n \"followers_count\": 2097,\r\n \"friends_count\": 1986,\r\n \"listed_count\": 88,\r\n \"created_at\": \"Fri Aug 08 02:16:23 +0000 2008\",\r\n \"favourites_count\": 9946,\r\n \"utc_offset\": null,\r\n \"time_zone\": null,\r\n \"geo_enabled\": true,\r\n \"verified\": false,\r\n \"statuses_count\": 5514,\r\n \"lang\": \"en\",\r\n \"contributors_enabled\": false,\r\n \"is_translator\": false,\r\n \"is_translation_enabled\": false,\r\n \"profile_background_color\": \"000000\",\r\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme6/bg.gif\",\r\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme6/bg.gif\",\r\n \"profile_background_tile\": false,\r\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/971062453453905920/DKzs-vf8_normal.jpg\",\r\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/971062453453905920/DKzs-vf8_normal.jpg\",\r\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/15772978/1520354408\",\r\n \"profile_link_color\": \"FA743E\",\r\n \"profile_sidebar_border_color\": \"000000\",\r\n \"profile_sidebar_fill_color\": \"000000\",\r\n \"profile_text_color\": \"000000\",\r\n \"profile_use_background_image\": false,\r\n \"has_extended_profile\": false,\r\n \"default_profile\": false,\r\n \"default_profile_image\": false,\r\n \"following\": false,\r\n \"follow_request_sent\": false,\r\n \"notifications\": false,\r\n \"translator_type\": \"none\"\r\n },\r\n \"geo\": null,\r\n \"coordinates\": null,\r\n \"place\": null,\r\n \"contributors\": null,\r\n \"is_quote_status\": false,\r\n \"retweet_count\": 0,\r\n \"favorite_count\": 0,\r\n \"favorited\": false,\r\n \"retweeted\": false,\r\n \"lang\": \"en\"\r\n}"; + private const string ExpectedOauthHeader = + "OAuth oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", oauth_signature=\"hCtSmYh%2BiHYCEqBWrE7C7hYmtUk%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1318622958\", oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", oauth_version=\"1.0\""; + private const string UpdateStatusResponse = + "{\r\n \"created_at\": \"Fri Jan 25 22:04:26 +0000 2019\",\r\n \"id\": 1088920554520961000,\r\n \"id_str\": \"1088920554520961026\",\r\n \"text\": \"okay\",\r\n \"truncated\": false,\r\n \"entities\": {\r\n \"hashtags\": [],\r\n \"symbols\": [],\r\n \"user_mentions\": [],\r\n \"urls\": []\r\n },\r\n \"source\": \"Learning Twitter API - Jess Gars\",\r\n \"in_reply_to_status_id\": null,\r\n \"in_reply_to_status_id_str\": null,\r\n \"in_reply_to_user_id\": null,\r\n \"in_reply_to_user_id_str\": null,\r\n \"in_reply_to_screen_name\": null,\r\n \"user\": {\r\n \"id\": 15772978,\r\n \"id_str\": \"15772978\",\r\n \"name\": \"Jessica Garson\uD83E\uDD95\",\r\n \"screen_name\": \"jessicagarson\",\r\n \"location\": \"Brooklyn, NY\",\r\n \"description\": \"Developer Advocate @Twitter. Python programmer. Noted thought leader on vegan snacks. Known sometimes as Messica Arson. She/They.\",\r\n \"url\": \"https://t.co/ai7MDeRPa5\",\r\n \"entities\": {\r\n \"url\": {\r\n \"urls\": [\r\n {\r\n \"url\": \"https://t.co/ai7MDeRPa5\",\r\n \"expanded_url\": \"http://jessicagarson.com\",\r\n \"display_url\": \"jessicagarson.com\",\r\n \"indices\": [\r\n 0,\r\n 23\r\n ]\r\n }\r\n ]\r\n },\r\n \"description\": {\r\n \"urls\": []\r\n }\r\n },\r\n \"protected\": false,\r\n \"followers_count\": 2097,\r\n \"friends_count\": 1986,\r\n \"listed_count\": 88,\r\n \"created_at\": \"Fri Aug 08 02:16:23 +0000 2008\",\r\n \"favourites_count\": 9946,\r\n \"utc_offset\": null,\r\n \"time_zone\": null,\r\n \"geo_enabled\": true,\r\n \"verified\": false,\r\n \"statuses_count\": 5514,\r\n \"lang\": \"en\",\r\n \"contributors_enabled\": false,\r\n \"is_translator\": false,\r\n \"is_translation_enabled\": false,\r\n \"profile_background_color\": \"000000\",\r\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme6/bg.gif\",\r\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme6/bg.gif\",\r\n \"profile_background_tile\": false,\r\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/971062453453905920/DKzs-vf8_normal.jpg\",\r\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/971062453453905920/DKzs-vf8_normal.jpg\",\r\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/15772978/1520354408\",\r\n \"profile_link_color\": \"FA743E\",\r\n \"profile_sidebar_border_color\": \"000000\",\r\n \"profile_sidebar_fill_color\": \"000000\",\r\n \"profile_text_color\": \"000000\",\r\n \"profile_use_background_image\": false,\r\n \"has_extended_profile\": false,\r\n \"default_profile\": false,\r\n \"default_profile_image\": false,\r\n \"following\": false,\r\n \"follow_request_sent\": false,\r\n \"notifications\": false,\r\n \"translator_type\": \"none\"\r\n },\r\n \"geo\": null,\r\n \"coordinates\": null,\r\n \"place\": null,\r\n \"contributors\": null,\r\n \"is_quote_status\": false,\r\n \"retweet_count\": 0,\r\n \"favorite_count\": 0,\r\n \"favorited\": false,\r\n \"retweeted\": false,\r\n \"lang\": \"en\"\r\n}"; private readonly Mock _mockHttpMessageHandler; private readonly Mock _mockFakeHttpMessageHandler; private readonly IDataProtectionProvider _mockDataProtectionProvider; + public TwitterClientTests() { _mockFakeHttpMessageHandler = new Mock() { CallBase = true }; @@ -29,20 +32,16 @@ public TwitterClientTests() settings.AccessTokenSecret = fakeDataProtector.Protect(settings.AccessTokenSecret); settings.ConsumerSecret = fakeDataProtector.Protect(settings.ConsumerSecret); - var signinSettings = new TwitterSigninSettings - { - CallbackPath = null, - }; + var signinSettings = new TwitterSigninSettings { CallbackPath = null, }; - _mockDataProtectionProvider = Mock.Of(dpp => - dpp.CreateProtector(It.IsAny()) == fakeDataProtector - ); + _mockDataProtectionProvider = Mock.Of(dpp => dpp.CreateProtector(It.IsAny()) == fakeDataProtector); var ticks = 13186229580000000 + 621355968000000000; _mockHttpMessageHandler = new Mock( Mock.Of(i => i.UtcNow == new DateTime(ticks)), Options.Create(settings), - _mockDataProtectionProvider); + _mockDataProtectionProvider + ); } [Fact] @@ -54,25 +53,14 @@ public async Task HttpRequestMessageShouldHaveCorrectSignedOAuthHeader() { HttpRequestMessage message = null; - _mockFakeHttpMessageHandler.Setup(c => c.Send( - It.IsAny()) - ).Returns((HttpRequestMessage request) => - new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(UpdateStatusResponse), - } - ).Callback((msg) => - message = msg - ); - - var mockTwitterClient = new Mock( - new HttpClient(_mockFakeHttpMessageHandler.Object), Mock.Of>()) - { - CallBase = true, - }; + _mockFakeHttpMessageHandler + .Setup(c => c.Send(It.IsAny())) + .Returns((HttpRequestMessage request) => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(UpdateStatusResponse), }) + .Callback((msg) => message = msg); + + var mockTwitterClient = new Mock(new HttpClient(_mockFakeHttpMessageHandler.Object), Mock.Of>()) { CallBase = true, }; - _mockHttpMessageHandler.Setup(c => c.GetNonce()) - .Returns(() => "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"); + _mockHttpMessageHandler.Setup(c => c.GetNonce()).Returns(() => "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"); var result = await mockTwitterClient.Object.UpdateStatus("Hello Ladies + Gentlemen, a signed OAuth request!", "include_entities=true"); diff --git a/test/OrchardCore.Tests/Modules/PoweredByMiddlewareTests.cs b/test/OrchardCore.Tests/Modules/PoweredByMiddlewareTests.cs index d9b1a55a40f..0faf766a710 100644 --- a/test/OrchardCore.Tests/Modules/PoweredByMiddlewareTests.cs +++ b/test/OrchardCore.Tests/Modules/PoweredByMiddlewareTests.cs @@ -8,7 +8,8 @@ public class PoweredByMiddlewareTests public async Task InjectPoweredByHeader() { // Arrange - string key = "X-Powered-By", value = "OrchardCore"; + string key = "X-Powered-By", + value = "OrchardCore"; var headersArray = new Dictionary() { { key, string.Empty } }; var headersDic = new HeaderDictionary(headersArray); var httpResponseMock = new Mock(); @@ -36,15 +37,15 @@ public async Task InjectPoweredByHeader() public async Task DoNotInjectPoweredByHeaderIfDisabled() { // Arrange - string key = "X-Powered-By", value = "OrchardCore"; + string key = "X-Powered-By", + value = "OrchardCore"; var httpResponseMock = new Mock(); #pragma warning disable ASP0019 // Suggest using IHeaderDictionary.Append or the indexer _ = httpResponseMock.Setup(r => r.Headers.Add(key, value)); #pragma warning restore ASP0019 // Suggest using IHeaderDictionary.Append or the indexer Func dueTask = null; - httpResponseMock.Setup(r => r.OnStarting(It.IsAny>())) - .Callback>((f) => dueTask = f); + httpResponseMock.Setup(r => r.OnStarting(It.IsAny>())).Callback>((f) => dueTask = f); var httpContextMock = new Mock(); httpContextMock.Setup(c => c.Response).Returns(httpResponseMock.Object); diff --git a/test/OrchardCore.Tests/Orchard.Queries/SqlParserTests.cs b/test/OrchardCore.Tests/Orchard.Queries/SqlParserTests.cs index ecb13a75136..d140631833b 100644 --- a/test/OrchardCore.Tests/Orchard.Queries/SqlParserTests.cs +++ b/test/OrchardCore.Tests/Orchard.Queries/SqlParserTests.cs @@ -108,11 +108,23 @@ public void ShouldDefineDefaultParametersValue() [Theory] [InlineData("select a from b inner join c on b.b1 = c.c1", "SELECT [a] FROM [tp_b] INNER JOIN [tp_c] ON [tp_b].[b1] = [tp_c].[c1];")] [InlineData("select a from b as ba inner join c as ca on ba.b1 = ca.c1", "SELECT [a] FROM [tp_b] AS ba INNER JOIN [tp_c] AS ca ON ba.[b1] = ca.[c1];")] - [InlineData("select a from b inner join c on b.b1 = c.c1 left join d on d.a = d.b", "SELECT [a] FROM [tp_b] INNER JOIN [tp_c] ON [tp_b].[b1] = [tp_c].[c1] LEFT JOIN [tp_d] ON [tp_d].[a] = [tp_d].[b];")] - [InlineData("select a from b inner join c on b.b1 = c.c1 and b.b2 = c.c2", "SELECT [a] FROM [tp_b] INNER JOIN [tp_c] ON [tp_b].[b1] = [tp_c].[c1] AND [tp_b].[b2] = [tp_c].[c2];")] - [InlineData("select a from b inner join c on b.b1 = c.c1 and b.b2 = @param", "SELECT [a] FROM [tp_b] INNER JOIN [tp_c] ON [tp_b].[b1] = [tp_c].[c1] AND [tp_b].[b2] = @param;")] + [InlineData( + "select a from b inner join c on b.b1 = c.c1 left join d on d.a = d.b", + "SELECT [a] FROM [tp_b] INNER JOIN [tp_c] ON [tp_b].[b1] = [tp_c].[c1] LEFT JOIN [tp_d] ON [tp_d].[a] = [tp_d].[b];" + )] + [InlineData( + "select a from b inner join c on b.b1 = c.c1 and b.b2 = c.c2", + "SELECT [a] FROM [tp_b] INNER JOIN [tp_c] ON [tp_b].[b1] = [tp_c].[c1] AND [tp_b].[b2] = [tp_c].[c2];" + )] + [InlineData( + "select a from b inner join c on b.b1 = c.c1 and b.b2 = @param", + "SELECT [a] FROM [tp_b] INNER JOIN [tp_c] ON [tp_b].[b1] = [tp_c].[c1] AND [tp_b].[b2] = @param;" + )] [InlineData("select a from b inner join c on 1 = 1 and @param = 'foo'", "SELECT [a] FROM [tp_b] INNER JOIN [tp_c] ON 1 = 1 AND @param = N'foo';")] - [InlineData("select a from b inner join c on 1 = @param left join d on d.a = @param left join e on e.a = 'foo'", "SELECT [a] FROM [tp_b] INNER JOIN [tp_c] ON 1 = @param LEFT JOIN [tp_d] ON [tp_d].[a] = @param LEFT JOIN [tp_e] ON [tp_e].[a] = N'foo';")] + [InlineData( + "select a from b inner join c on 1 = @param left join d on d.a = @param left join e on e.a = 'foo'", + "SELECT [a] FROM [tp_b] INNER JOIN [tp_c] ON 1 = @param LEFT JOIN [tp_d] ON [tp_d].[a] = @param LEFT JOIN [tp_e] ON [tp_e].[a] = N'foo';" + )] public void ShouldParseJoinClause(string sql, string expectedSql) { var result = SqlParser.TryParse(sql, _schema, _defaultDialect, _defaultTablePrefix, null, out var rawQuery, out _); @@ -218,9 +230,18 @@ public void ShouldParseUnionClause(string sql, string expectedSql) [Theory] [InlineData("with cte as (select a from t) select * from cte", "WITH cte AS (SELECT [a] FROM [tp_t]) SELECT * FROM [cte];")] - [InlineData("with cte as (select a from t), cte2 as (select b from t) select * from cte2", "WITH cte AS (SELECT [a] FROM [tp_t]), cte2 AS (SELECT [b] FROM [tp_t]) SELECT * FROM [cte2];")] - [InlineData("with cte as (select a from t union all select b from t) select * from cte", "WITH cte AS (SELECT [a] FROM [tp_t] UNION ALL SELECT [b] FROM [tp_t]) SELECT * FROM [cte];")] - [InlineData("with cte1(abc, def) as (select id as abc, id as def from t), cte2(ghi,jkl) as (select abc as ghi, def as jkl from cte1) select ghi, jkl from cte2", "WITH cte1(abc, def) AS (SELECT [id] AS abc, [id] AS def FROM [tp_t]), cte2(ghi, jkl) AS (SELECT [abc] AS ghi, [def] AS jkl FROM [cte1]) SELECT [ghi], [jkl] FROM [cte2];")] + [InlineData( + "with cte as (select a from t), cte2 as (select b from t) select * from cte2", + "WITH cte AS (SELECT [a] FROM [tp_t]), cte2 AS (SELECT [b] FROM [tp_t]) SELECT * FROM [cte2];" + )] + [InlineData( + "with cte as (select a from t union all select b from t) select * from cte", + "WITH cte AS (SELECT [a] FROM [tp_t] UNION ALL SELECT [b] FROM [tp_t]) SELECT * FROM [cte];" + )] + [InlineData( + "with cte1(abc, def) as (select id as abc, id as def from t), cte2(ghi,jkl) as (select abc as ghi, def as jkl from cte1) select ghi, jkl from cte2", + "WITH cte1(abc, def) AS (SELECT [id] AS abc, [id] AS def FROM [tp_t]), cte2(ghi, jkl) AS (SELECT [abc] AS ghi, [def] AS jkl FROM [cte1]) SELECT [ghi], [jkl] FROM [cte2];" + )] [InlineData("with test(test) as (select a as test from t) select test from test", "WITH test(test) AS (SELECT [a] AS test FROM [tp_t]) SELECT [test] FROM [test];")] public void ShouldParseCte(string sql, string expectedSql) { @@ -234,9 +255,18 @@ public void ShouldParseCte(string sql, string expectedSql) [InlineData("select b.a from (select a from t) as b where b.a = b.a", "SELECT b.[a] FROM (SELECT [a] FROM [tp_t]) AS b WHERE b.[a] = b.[a];")] [InlineData("select c.b from (select a as b from t) as c", "SELECT c.[b] FROM (SELECT [a] AS b FROM [tp_t]) AS c;")] [InlineData("select b.a from (select a from t where [a] = 1) as b where b.a = 1", "SELECT b.[a] FROM (SELECT [a] FROM [tp_t] WHERE [a] = 1) AS b WHERE b.[a] = 1;")] - [InlineData("select b.a from (select a from t where [a] = 1 union all select a from t where [a] = 2) as b", "SELECT b.[a] FROM (SELECT [a] FROM [tp_t] WHERE [a] = 1 UNION ALL SELECT [a] FROM [tp_t] WHERE [a] = 2) AS b;")] - [InlineData("select d.b, g.b from (select a as b from c) as d, (select e as b from f) as g", "SELECT d.[b], g.[b] FROM (SELECT [a] AS b FROM [tp_c]) AS d, (SELECT [e] AS b FROM [tp_f]) AS g;")] - [InlineData("select * from (select d as e from (select c as d from (select b as c from (select a as b from t) as l4) as l3) as l2) as l1", "SELECT * FROM (SELECT [d] AS e FROM (SELECT [c] AS d FROM (SELECT [b] AS c FROM (SELECT [a] AS b FROM [tp_t]) AS l4) AS l3) AS l2) AS l1;")] + [InlineData( + "select b.a from (select a from t where [a] = 1 union all select a from t where [a] = 2) as b", + "SELECT b.[a] FROM (SELECT [a] FROM [tp_t] WHERE [a] = 1 UNION ALL SELECT [a] FROM [tp_t] WHERE [a] = 2) AS b;" + )] + [InlineData( + "select d.b, g.b from (select a as b from c) as d, (select e as b from f) as g", + "SELECT d.[b], g.[b] FROM (SELECT [a] AS b FROM [tp_c]) AS d, (SELECT [e] AS b FROM [tp_f]) AS g;" + )] + [InlineData( + "select * from (select d as e from (select c as d from (select b as c from (select a as b from t) as l4) as l3) as l2) as l1", + "SELECT * FROM (SELECT [d] AS e FROM (SELECT [c] AS d FROM (SELECT [b] AS c FROM (SELECT [a] AS b FROM [tp_t]) AS l4) AS l3) AS l2) AS l1;" + )] public void ShouldParseSubquery(string sql, string expectedSql) { var result = SqlParser.TryParse(sql, _schema, _defaultDialect, _defaultTablePrefix, null, out var rawQuery, out _); diff --git a/test/OrchardCore.Tests/OrchardCore.Environment.Cache/CacheScopeManagerTests.cs b/test/OrchardCore.Tests/OrchardCore.Environment.Cache/CacheScopeManagerTests.cs index a989ae25fe8..0f62ddab0bc 100644 --- a/test/OrchardCore.Tests/OrchardCore.Environment.Cache/CacheScopeManagerTests.cs +++ b/test/OrchardCore.Tests/OrchardCore.Environment.Cache/CacheScopeManagerTests.cs @@ -43,11 +43,9 @@ public void ContextsAreBubbledUp1() sut.ExitScope(); sut.ExitScope(); - Assert.Collection(scopeA.Contexts, context => Assert.Contains("1", context), - context => Assert.Contains("2", context)); + Assert.Collection(scopeA.Contexts, context => Assert.Contains("1", context), context => Assert.Contains("2", context)); - Assert.Collection(scopeB.Contexts, context => Assert.Contains("1", context), - context => Assert.Contains("2", context)); + Assert.Collection(scopeB.Contexts, context => Assert.Contains("1", context), context => Assert.Contains("2", context)); } [Fact] @@ -64,8 +62,7 @@ public void ContextsAreBubbledUp2() sut.ExitScope(); sut.ExitScope(); - Assert.Collection(scopeA.Contexts, context => Assert.Contains("1", context), - context => Assert.Contains("2", context)); + Assert.Collection(scopeA.Contexts, context => Assert.Contains("1", context), context => Assert.Contains("2", context)); Assert.False(scopeB.Contexts.Any()); } @@ -84,13 +81,15 @@ public void ContextsAreBubbledUp3() sut.ExitScope(); sut.ExitScope(); - Assert.Collection(scopeA.Contexts, context => Assert.Contains("3", context), - context => Assert.Contains("4", context), - context => Assert.Contains("1", context), - context => Assert.Contains("2", context)); + Assert.Collection( + scopeA.Contexts, + context => Assert.Contains("3", context), + context => Assert.Contains("4", context), + context => Assert.Contains("1", context), + context => Assert.Contains("2", context) + ); - Assert.Collection(scopeB.Contexts, context => Assert.Contains("1", context), - context => Assert.Contains("2", context)); + Assert.Collection(scopeB.Contexts, context => Assert.Contains("1", context), context => Assert.Contains("2", context)); } [Fact] @@ -107,11 +106,9 @@ public void TagsAreBubbledUp1() sut.ExitScope(); sut.ExitScope(); - Assert.Collection(scopeA.Tags, tag => Assert.Contains("1", tag), - tag => Assert.Contains("2", tag)); + Assert.Collection(scopeA.Tags, tag => Assert.Contains("1", tag), tag => Assert.Contains("2", tag)); - Assert.Collection(scopeB.Tags, tag => Assert.Contains("1", tag), - tag => Assert.Contains("2", tag)); + Assert.Collection(scopeB.Tags, tag => Assert.Contains("1", tag), tag => Assert.Contains("2", tag)); } [Fact] @@ -128,8 +125,7 @@ public void TagsAreBubbledUp2() sut.ExitScope(); sut.ExitScope(); - Assert.Collection(scopeA.Tags, tag => Assert.Contains("1", tag), - tag => Assert.Contains("2", tag)); + Assert.Collection(scopeA.Tags, tag => Assert.Contains("1", tag), tag => Assert.Contains("2", tag)); Assert.False(scopeB.Tags.Any()); } @@ -148,13 +144,9 @@ public void TagsAreBubbledUp3() sut.ExitScope(); sut.ExitScope(); - Assert.Collection(scopeA.Tags, tag => Assert.Contains("3", tag), - tag => Assert.Contains("4", tag), - tag => Assert.Contains("1", tag), - tag => Assert.Contains("2", tag)); + Assert.Collection(scopeA.Tags, tag => Assert.Contains("3", tag), tag => Assert.Contains("4", tag), tag => Assert.Contains("1", tag), tag => Assert.Contains("2", tag)); - Assert.Collection(scopeB.Tags, tag => Assert.Contains("1", tag), - tag => Assert.Contains("2", tag)); + Assert.Collection(scopeB.Tags, tag => Assert.Contains("1", tag), tag => Assert.Contains("2", tag)); } [Fact] @@ -322,22 +314,13 @@ public void ExpirySlidingIsBubbledUp3() [Fact] public void ComplexNesting() { - var scopeA = new CacheContext("a") - .AddContext("c1") - .AddTag("t1"); + var scopeA = new CacheContext("a").AddContext("c1").AddTag("t1"); - var scopeAA = new CacheContext("aa") - .AddContext("c2") - .WithExpiryAfter(new TimeSpan(0, 1, 0)); + var scopeAA = new CacheContext("aa").AddContext("c2").WithExpiryAfter(new TimeSpan(0, 1, 0)); - var scopeAB = new CacheContext("ab") - .WithExpirySliding(new TimeSpan(3, 30, 26)) - .WithExpiryAfter(new TimeSpan(0, 5, 0)); + var scopeAB = new CacheContext("ab").WithExpirySliding(new TimeSpan(3, 30, 26)).WithExpiryAfter(new TimeSpan(0, 5, 0)); - var scopeABA = new CacheContext("aaa") - .AddContext("deepestcontext") - .AddTag("deepesttag") - .WithExpiryOn(new DateTime(2018, 10, 26)); + var scopeABA = new CacheContext("aaa").AddContext("deepestcontext").AddTag("deepesttag").WithExpiryOn(new DateTime(2018, 10, 26)); var sut = new CacheScopeManager(); @@ -351,12 +334,14 @@ public void ComplexNesting() sut.ExitScope(); // scopeA // Scope A - Assert.Collection(scopeA.Contexts, context => Assert.Contains("c1", context), - context => Assert.Contains("c2", context), - context => Assert.Contains("deepestcontext", context)); - - Assert.Collection(scopeA.Tags, tag => Assert.Contains("t1", tag), - tag => Assert.Contains("deepesttag", tag)); + Assert.Collection( + scopeA.Contexts, + context => Assert.Contains("c1", context), + context => Assert.Contains("c2", context), + context => Assert.Contains("deepestcontext", context) + ); + + Assert.Collection(scopeA.Tags, tag => Assert.Contains("t1", tag), tag => Assert.Contains("deepesttag", tag)); Assert.Equal(new TimeSpan(0, 1, 0), scopeA.ExpiresAfter); Assert.Equal(new TimeSpan(3, 30, 26), scopeA.ExpiresSliding); diff --git a/test/OrchardCore.Tests/OrchardCore.Users/OrchardCore.Users.Core/DefaultUserClaimsPrincipalProviderFactoryTests.cs b/test/OrchardCore.Tests/OrchardCore.Users/OrchardCore.Users.Core/DefaultUserClaimsPrincipalProviderFactoryTests.cs index 31b78fe2553..e9cb4ffae69 100644 --- a/test/OrchardCore.Tests/OrchardCore.Users/OrchardCore.Users.Core/DefaultUserClaimsPrincipalProviderFactoryTests.cs +++ b/test/OrchardCore.Tests/OrchardCore.Users/OrchardCore.Users.Core/DefaultUserClaimsPrincipalProviderFactoryTests.cs @@ -14,7 +14,12 @@ public async Task EnsurePrincipalHasExpectedClaims(bool emailVerified) { //Arrange var userManager = UsersMockHelper.MockUserManager(); - var user = new User { UserId = Guid.NewGuid().ToString("n"), UserName = "Foo", Email = "foo@foo.com" }; + var user = new User + { + UserId = Guid.NewGuid().ToString("n"), + UserName = "Foo", + Email = "foo@foo.com" + }; userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.UserId); userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName); userManager.Setup(m => m.GetEmailAsync(user)).ReturnsAsync(user.Email); @@ -29,10 +34,7 @@ public async Task EnsurePrincipalHasExpectedClaims(bool emailVerified) var options = new Mock>(); options.Setup(a => a.Value).Returns(new IdentityOptions()); - var claimsProviders = new List() - { - new EmailClaimsProvider(userManager.Object) - }; + var claimsProviders = new List() { new EmailClaimsProvider(userManager.Object) }; var factory = new DefaultUserClaimsPrincipalProviderFactory(userManager.Object, roleManager, options.Object, claimsProviders, null); @@ -56,5 +58,4 @@ public async Task EnsurePrincipalHasExpectedClaims(bool emailVerified) Assert.Equal(emailVerified.ToString(), emailVerifiedClaim.Value); } } - } diff --git a/test/OrchardCore.Tests/OrchardCore.Users/RegistrationControllerTests.cs b/test/OrchardCore.Tests/OrchardCore.Users/RegistrationControllerTests.cs index de95ccf00f3..2f8d5804791 100644 --- a/test/OrchardCore.Tests/OrchardCore.Users/RegistrationControllerTests.cs +++ b/test/OrchardCore.Tests/OrchardCore.Users/RegistrationControllerTests.cs @@ -18,10 +18,7 @@ public class RegistrationControllerTests public async Task UsersShouldNotBeAbleToRegisterIfNotAllowed() { // Arrange - var controller = SetupRegistrationController(new RegistrationSettings - { - UsersCanRegister = UserRegistrationType.NoRegistration - }); + var controller = SetupRegistrationController(new RegistrationSettings { UsersCanRegister = UserRegistrationType.NoRegistration }); // Act & Assert var result = await controller.Register(); @@ -67,11 +64,7 @@ public async Task UsersShouldNotBeAbleToRegisterIfEmailIsDuplicate() public async Task UsersCanRequireModeration() { // Arrange - var controller = SetupRegistrationController(new RegistrationSettings - { - UsersCanRegister = UserRegistrationType.AllowRegistration, - UsersAreModerated = true, - }); + var controller = SetupRegistrationController(new RegistrationSettings { UsersCanRegister = UserRegistrationType.AllowRegistration, UsersAreModerated = true, }); // Act var result = await controller.Register(new RegisterViewModel { UserName = "ModerateMe", Email = "requiresmoderation@orchardcore.net" }); @@ -85,11 +78,7 @@ public async Task UsersCanRequireModeration() public async Task UsersCanRequireEmailConfirmation() { // Arrange - var controller = SetupRegistrationController(new RegistrationSettings - { - UsersCanRegister = UserRegistrationType.AllowRegistration, - UsersMustValidateEmail = true - }); + var controller = SetupRegistrationController(new RegistrationSettings { UsersCanRegister = UserRegistrationType.AllowRegistration, UsersMustValidateEmail = true }); // Act & Assert var result = await controller.Register(new RegisterViewModel { UserName = "ConfirmMe", Email = "requiresemailconfirmation@orchardcore.net" }); @@ -99,7 +88,8 @@ public async Task UsersCanRequireEmailConfirmation() Assert.Equal("ConfirmEmailSent", ((RedirectToActionResult)result).ActionName); } - private static Mock> MockSignInManager(UserManager userManager = null) where TUser : class, IUser + private static Mock> MockSignInManager(UserManager userManager = null) + where TUser : class, IUser { var context = new Mock(); var manager = userManager ?? UsersMockHelper.MockUserManager().Object; @@ -111,26 +101,26 @@ private static Mock> MockSignInManager(UserManager x.SignInAsync(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + signInManager.Setup(x => x.SignInAsync(It.IsAny(), It.IsAny(), It.IsAny())).Returns(Task.CompletedTask); return signInManager; } - private static RegistrationController SetupRegistrationController() - => SetupRegistrationController(new RegistrationSettings - { - UsersCanRegister = UserRegistrationType.AllowRegistration - }); + private static RegistrationController SetupRegistrationController() => + SetupRegistrationController(new RegistrationSettings { UsersCanRegister = UserRegistrationType.AllowRegistration }); private static RegistrationController SetupRegistrationController(RegistrationSettings registrationSettings) { var users = new List(); var mockUserManager = UsersMockHelper.MockUserManager(); - mockUserManager.Setup(um => um.FindByEmailAsync(It.IsAny())) + mockUserManager + .Setup(um => um.FindByEmailAsync(It.IsAny())) .Returns(e => { var user = users.SingleOrDefault(u => (u as User).Email == e); @@ -142,11 +132,11 @@ private static RegistrationController SetupRegistrationController(RegistrationSe var mockSiteService = Mock.Of(ss => ss.GetSiteSettingsAsync() == Task.FromResult(mockSite.Object)); var mockSmtpService = Mock.Of(x => x.SendAsync(It.IsAny()) == Task.FromResult(SmtpResult.Success)); var mockStringLocalizer = new Mock>(); - mockStringLocalizer.Setup(l => l[It.IsAny()]) - .Returns(s => new LocalizedString(s, s)); + mockStringLocalizer.Setup(l => l[It.IsAny()]).Returns(s => new LocalizedString(s, s)); var userService = new Mock(); - userService.Setup(u => u.CreateUserAsync(It.IsAny(), It.IsAny(), It.IsAny>())) + userService + .Setup(u => u.CreateUserAsync(It.IsAny(), It.IsAny(), It.IsAny>())) .Callback>((u, p, e) => users.Add(u)) .ReturnsAsync, IUserService, IUser>((u, p, e) => u); @@ -154,12 +144,10 @@ private static RegistrationController SetupRegistrationController(RegistrationSe urlHelperMock.Setup(urlHelper => urlHelper.Action(It.IsAny())); var mockUrlHelperFactory = new Mock(); - mockUrlHelperFactory.Setup(f => f.GetUrlHelper(It.IsAny())) - .Returns(urlHelperMock.Object); + mockUrlHelperFactory.Setup(f => f.GetUrlHelper(It.IsAny())).Returns(urlHelperMock.Object); var mockDisplayHelper = new Mock(); - mockDisplayHelper.Setup(x => x.ShapeExecuteAsync(It.IsAny())) - .ReturnsAsync(HtmlString.Empty); + mockDisplayHelper.Setup(x => x.ShapeExecuteAsync(It.IsAny())).ReturnsAsync(HtmlString.Empty); var controller = new RegistrationController( mockUserManager.Object, @@ -168,58 +156,33 @@ private static RegistrationController SetupRegistrationController(RegistrationSe Mock.Of(), Mock.Of>(), Mock.Of>(), - mockStringLocalizer.Object) + mockStringLocalizer.Object + ) { Url = urlHelperMock.Object }; var mockServiceProvider = new Mock(); - mockServiceProvider - .Setup(x => x.GetService(typeof(ISmtpService))) - .Returns(mockSmtpService); - mockServiceProvider - .Setup(x => x.GetService(typeof(UserManager))) - .Returns(mockUserManager.Object); - mockServiceProvider - .Setup(x => x.GetService(typeof(ISiteService))) - .Returns(mockSiteService); - mockServiceProvider - .Setup(x => x.GetService(typeof(IEnumerable))) - .Returns(Array.Empty()); - mockServiceProvider - .Setup(x => x.GetService(typeof(IUserService))) - .Returns(userService.Object); - mockServiceProvider - .Setup(x => x.GetService(typeof(SignInManager))) - .Returns(MockSignInManager(mockUserManager.Object).Object); - mockServiceProvider - .Setup(x => x.GetService(typeof(ITempDataDictionaryFactory))) - .Returns(Mock.Of()); - mockServiceProvider - .Setup(x => x.GetService(typeof(IObjectModelValidator))) - .Returns(Mock.Of()); - mockServiceProvider - .Setup(x => x.GetService(typeof(IDisplayHelper))) - .Returns(mockDisplayHelper.Object); - mockServiceProvider - .Setup(x => x.GetService(typeof(IUrlHelperFactory))) - .Returns(mockUrlHelperFactory.Object); - mockServiceProvider - .Setup(x => x.GetService(typeof(HtmlEncoder))) - .Returns(HtmlEncoder.Default); + mockServiceProvider.Setup(x => x.GetService(typeof(ISmtpService))).Returns(mockSmtpService); + mockServiceProvider.Setup(x => x.GetService(typeof(UserManager))).Returns(mockUserManager.Object); + mockServiceProvider.Setup(x => x.GetService(typeof(ISiteService))).Returns(mockSiteService); + mockServiceProvider.Setup(x => x.GetService(typeof(IEnumerable))).Returns(Array.Empty()); + mockServiceProvider.Setup(x => x.GetService(typeof(IUserService))).Returns(userService.Object); + mockServiceProvider.Setup(x => x.GetService(typeof(SignInManager))).Returns(MockSignInManager(mockUserManager.Object).Object); + mockServiceProvider.Setup(x => x.GetService(typeof(ITempDataDictionaryFactory))).Returns(Mock.Of()); + mockServiceProvider.Setup(x => x.GetService(typeof(IObjectModelValidator))).Returns(Mock.Of()); + mockServiceProvider.Setup(x => x.GetService(typeof(IDisplayHelper))).Returns(mockDisplayHelper.Object); + mockServiceProvider.Setup(x => x.GetService(typeof(IUrlHelperFactory))).Returns(mockUrlHelperFactory.Object); + mockServiceProvider.Setup(x => x.GetService(typeof(HtmlEncoder))).Returns(HtmlEncoder.Default); // var mockRequest = new Mock(); // mockRequest.Setup(x => x.Scheme) // .Returns("http"); var mockHttpContext = new Mock(); - mockHttpContext - .Setup(x => x.RequestServices) - .Returns(mockServiceProvider.Object); - mockHttpContext - .Setup(x => x.Request) - .Returns(Mock.Of(x => x.Scheme == "http")); + mockHttpContext.Setup(x => x.RequestServices).Returns(mockServiceProvider.Object); + mockHttpContext.Setup(x => x.Request).Returns(Mock.Of(x => x.Scheme == "http")); controller.ControllerContext.HttpContext = mockHttpContext.Object; diff --git a/test/OrchardCore.Tests/OrchardCore.Users/UserValidatorTests.cs b/test/OrchardCore.Tests/OrchardCore.Users/UserValidatorTests.cs index f5531c4471b..4df3936cfa4 100644 --- a/test/OrchardCore.Tests/OrchardCore.Users/UserValidatorTests.cs +++ b/test/OrchardCore.Tests/OrchardCore.Users/UserValidatorTests.cs @@ -10,7 +10,12 @@ public async Task CanValidateUser() { // Arrange var userManager = UsersMockHelper.MockUserManager(); - var user = new User { UserId = Guid.NewGuid().ToString("n"), UserName = "Foo", Email = "foo@foo.com" }; + var user = new User + { + UserId = Guid.NewGuid().ToString("n"), + UserName = "Foo", + Email = "foo@foo.com" + }; userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.UserId); userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName); userManager.Setup(m => m.GetEmailAsync(user)).ReturnsAsync(user.Email); @@ -49,7 +54,12 @@ public async Task ShouldRequireValidEmail() // Arrange var describer = new IdentityErrorDescriber(); var userManager = UsersMockHelper.MockUserManager(); - var user = new User { UserId = Guid.NewGuid().ToString("n"), UserName = "Foo", Email = "foo" }; + var user = new User + { + UserId = Guid.NewGuid().ToString("n"), + UserName = "Foo", + Email = "foo" + }; userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.UserId); userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName); userManager.Setup(m => m.GetEmailAsync(user)).ReturnsAsync(user.Email); @@ -69,14 +79,24 @@ public async Task ShouldRequireUniqueEmail() // Arrange var describer = new IdentityErrorDescriber(); var userManager = UsersMockHelper.MockUserManager(); - var existingUser = new User { UserId = Guid.NewGuid().ToString("n"), UserName = "Foo", Email = "foo@foo.com" }; + var existingUser = new User + { + UserId = Guid.NewGuid().ToString("n"), + UserName = "Foo", + Email = "foo@foo.com" + }; userManager.Setup(m => m.GetUserIdAsync(existingUser)).ReturnsAsync(existingUser.UserId); userManager.Setup(m => m.GetUserNameAsync(existingUser)).ReturnsAsync(existingUser.UserName); userManager.Setup(m => m.GetEmailAsync(existingUser)).ReturnsAsync(existingUser.Email); userManager.Setup(m => m.FindByEmailAsync(existingUser.Email)).ReturnsAsync(existingUser); userManager.Setup(m => m.FindByNameAsync(existingUser.UserName)).ReturnsAsync(existingUser); - var user = new User { UserId = Guid.NewGuid().ToString("n"), UserName = "Bar", Email = "foo@foo.com" }; + var user = new User + { + UserId = Guid.NewGuid().ToString("n"), + UserName = "Bar", + Email = "foo@foo.com" + }; userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.UserId); userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName); userManager.Setup(m => m.GetEmailAsync(user)).ReturnsAsync(user.Email); @@ -96,7 +116,12 @@ public async Task ShouldRequireUserNameIsNotAnEmailAddress() // Arrange var describer = new IdentityErrorDescriber(); var userManager = UsersMockHelper.MockUserManager(); - var user = new User { UserId = Guid.NewGuid().ToString("n"), UserName = "foo@foo.com", Email = "foo" }; + var user = new User + { + UserId = Guid.NewGuid().ToString("n"), + UserName = "foo@foo.com", + Email = "foo" + }; userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.UserId); userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName); userManager.Setup(m => m.GetEmailAsync(user)).ReturnsAsync(user.Email); @@ -116,14 +141,24 @@ public async Task ShouldRequireUniqueUserName() // Arrange var describer = new IdentityErrorDescriber(); var userManager = UsersMockHelper.MockUserManager(); - var existingUser = new User { UserId = Guid.NewGuid().ToString("n"), UserName = "Foo", Email = "bar@bar.com" }; + var existingUser = new User + { + UserId = Guid.NewGuid().ToString("n"), + UserName = "Foo", + Email = "bar@bar.com" + }; userManager.Setup(m => m.GetUserIdAsync(existingUser)).ReturnsAsync(existingUser.UserId); userManager.Setup(m => m.GetUserNameAsync(existingUser)).ReturnsAsync(existingUser.UserName); userManager.Setup(m => m.GetEmailAsync(existingUser)).ReturnsAsync(existingUser.Email); userManager.Setup(m => m.FindByEmailAsync(existingUser.Email)).ReturnsAsync(existingUser); userManager.Setup(m => m.FindByNameAsync(existingUser.UserName)).ReturnsAsync(existingUser); - var user = new User { UserId = Guid.NewGuid().ToString("n"), UserName = "Foo", Email = "foo@foo.com" }; + var user = new User + { + UserId = Guid.NewGuid().ToString("n"), + UserName = "Foo", + Email = "foo@foo.com" + }; userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.UserId); userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName); userManager.Setup(m => m.GetEmailAsync(user)).ReturnsAsync(user.Email); diff --git a/test/OrchardCore.Tests/OrchardCore.Users/UsersMockHelper.cs b/test/OrchardCore.Tests/OrchardCore.Users/UsersMockHelper.cs index d221ca37482..1d612bfda92 100644 --- a/test/OrchardCore.Tests/OrchardCore.Users/UsersMockHelper.cs +++ b/test/OrchardCore.Tests/OrchardCore.Users/UsersMockHelper.cs @@ -2,7 +2,8 @@ namespace OrchardCore.Tests.OrchardCore.Users { public static class UsersMockHelper { - public static Mock> MockUserManager() where TUser : class + public static Mock> MockUserManager() + where TUser : class { var store = new Mock>(); var identityOptions = new IdentityOptions(); @@ -16,14 +17,12 @@ public static Mock> MockUserManager() where TUser : cl return mgr; } - public static Mock> MockRoleManager() where TRole : class + public static Mock> MockRoleManager() + where TRole : class { var store = new Mock>().Object; - var roles = new List> - { - new RoleValidator(), - }; + var roles = new List> { new RoleValidator(), }; return new Mock>(store, roles, new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), null); } diff --git a/test/OrchardCore.Tests/Recipes/RecipeExecutorTests.cs b/test/OrchardCore.Tests/Recipes/RecipeExecutorTests.cs index 76b16d9fa39..fb1e28ab4e0 100644 --- a/test/OrchardCore.Tests/Recipes/RecipeExecutorTests.cs +++ b/test/OrchardCore.Tests/Recipes/RecipeExecutorTests.cs @@ -26,16 +26,11 @@ public async Task ShouldTrimValidScriptExpression(string recipeName, string expe // Arrange var shellHostMock = new Mock(); - shellHostMock.Setup(h => h.GetScopeAsync(It.IsAny())) - .Returns(GetScopeAsync); + shellHostMock.Setup(h => h.GetScopeAsync(It.IsAny())).Returns(GetScopeAsync); var recipeEventHandlers = new List { new RecipeEventHandler() }; var loggerMock = new Mock>(); - var recipeExecutor = new RecipeExecutor( - shellHostMock.Object, - scope.ShellContext.Settings, - recipeEventHandlers, - loggerMock.Object); + var recipeExecutor = new RecipeExecutor(shellHostMock.Object, scope.ShellContext.Settings, recipeEventHandlers, loggerMock.Object); // Act var executionId = Guid.NewGuid().ToString("n"); @@ -51,17 +46,10 @@ public async Task ShouldTrimValidScriptExpression(string recipeName, string expe private static Task GetScopeAsync() => ShellScope.Context.CreateScopeAsync(); - private static ShellContext CreateShellContext() => new() - { - Settings = new ShellSettings().AsDefaultShell().AsRunning(), - ServiceProvider = CreateServiceProvider(), - }; - - private static IServiceProvider CreateServiceProvider() => new ServiceCollection() - .AddScripting() - .AddSingleton() - .AddLogging() - .BuildServiceProvider(); + private static ShellContext CreateShellContext() => new() { Settings = new ShellSettings().AsDefaultShell().AsRunning(), ServiceProvider = CreateServiceProvider(), }; + + private static IServiceProvider CreateServiceProvider() => + new ServiceCollection().AddScripting().AddSingleton().AddLogging().BuildServiceProvider(); private IFileInfo GetRecipeFileInfo(string recipeName) { diff --git a/test/OrchardCore.Tests/ResourceManagement/ResourceDefinitionTests.cs b/test/OrchardCore.Tests/ResourceManagement/ResourceDefinitionTests.cs index 13b2bbc6d01..ca8f490dce3 100644 --- a/test/OrchardCore.Tests/ResourceManagement/ResourceDefinitionTests.cs +++ b/test/OrchardCore.Tests/ResourceManagement/ResourceDefinitionTests.cs @@ -19,9 +19,7 @@ public ResourceDefinitionTests() [InlineData("/virtualpath/tenant")] public void GetScriptResourceWithUrl(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineScript("foo") - .SetUrl("~/foo.js", "~/foo.debug.js") - .SetCdn("https://cdn.tld/foo.js", "https://cdn.tld/foo.debug.js"); + var resourceDefinition = _resourceManifest.DefineScript("foo").SetUrl("~/foo.js", "~/foo.debug.js").SetCdn("https://cdn.tld/foo.js", "https://cdn.tld/foo.debug.js"); var requireSettings = new RequireSettings { DebugMode = false, CdnMode = false }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); @@ -34,9 +32,7 @@ public void GetScriptResourceWithUrl(string applicationPath) [InlineData("/base")] public void GetScriptResourceWithBasePath(string basePath) { - var resourceDefinition = _resourceManifest.DefineScript("foo") - .SetUrl("~/foo.js", "~/foo.debug.js") - .SetBasePath(basePath); + var resourceDefinition = _resourceManifest.DefineScript("foo").SetUrl("~/foo.js", "~/foo.debug.js").SetBasePath(basePath); var requireSettings = new RequireSettings { DebugMode = false, CdnMode = false }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, string.Empty, StubFileVersionProvider.Instance); @@ -51,9 +47,7 @@ public void GetScriptResourceWithBasePath(string basePath) [InlineData("/virtualpath/tenant")] public void GetScriptResourceWithDebugUrl(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineScript("foo") - .SetUrl("~/foo.js", "~/foo.debug.js") - .SetCdn("https://cdn.tld/foo.js", "https://cdn.tld/foo.debug.js"); + var resourceDefinition = _resourceManifest.DefineScript("foo").SetUrl("~/foo.js", "~/foo.debug.js").SetCdn("https://cdn.tld/foo.js", "https://cdn.tld/foo.debug.js"); var requireSettings = new RequireSettings { DebugMode = true, CdnMode = false }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); @@ -68,9 +62,7 @@ public void GetScriptResourceWithDebugUrl(string applicationPath) [InlineData("/virtualpath/tenant")] public void GetScriptResourceWithCdnUrl(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineScript("foo") - .SetUrl("~/foo.js", "~/foo.debug.js") - .SetCdn("https://cdn.tld/foo.js", "https://cdn.tld/foo.debug.js"); + var resourceDefinition = _resourceManifest.DefineScript("foo").SetUrl("~/foo.js", "~/foo.debug.js").SetCdn("https://cdn.tld/foo.js", "https://cdn.tld/foo.debug.js"); var requireSettings = new RequireSettings { DebugMode = false, CdnMode = true }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); @@ -85,11 +77,14 @@ public void GetScriptResourceWithCdnUrl(string applicationPath) [InlineData("/virtualpath/tenant")] public void GetScriptResourceWithDebugCdnUrl(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineScript("foo") - .SetUrl("~/foo.js", "~/foo.debug.js") - .SetCdn("https://cdn.tld/foo.js", "https://cdn.tld/foo.debug.js"); + var resourceDefinition = _resourceManifest.DefineScript("foo").SetUrl("~/foo.js", "~/foo.debug.js").SetCdn("https://cdn.tld/foo.js", "https://cdn.tld/foo.debug.js"); - var requireSettings = new RequireSettings { DebugMode = true, CdnMode = true, CdnBaseUrl = "https://hostcdn.net" }; + var requireSettings = new RequireSettings + { + DebugMode = true, + CdnMode = true, + CdnBaseUrl = "https://hostcdn.net" + }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); Assert.Equal("script", tagBuilder.TagName); @@ -107,10 +102,14 @@ public void GetScriptResourceWithDebugCdnUrl(string applicationPath) [InlineData("/tenant", "https://external.com/foo.js", "https://external.com/foo.js")] public void GetLocalScriptResourceWithCdnBaseUrl(string applicationPath, string url, string expected) { - var resourceDefinition = _resourceManifest.DefineScript("foo") - .SetUrl(url, url); + var resourceDefinition = _resourceManifest.DefineScript("foo").SetUrl(url, url); - var requireSettings = new RequireSettings { DebugMode = false, CdnMode = true, CdnBaseUrl = "https://hostcdn.net" }; + var requireSettings = new RequireSettings + { + DebugMode = false, + CdnMode = true, + CdnBaseUrl = "https://hostcdn.net" + }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); Assert.Equal("script", tagBuilder.TagName); @@ -123,11 +122,9 @@ public void GetLocalScriptResourceWithCdnBaseUrl(string applicationPath, string [InlineData("/virtualpath/tenant")] public void GetScriptResourceWithInlineContent(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineScript("foo") - .SetInnerContent("console.log('foo');"); + var resourceDefinition = _resourceManifest.DefineScript("foo").SetInnerContent("console.log('foo');"); - var requireSettings = new RequireSettings() - .UseCdnBaseUrl("https://hostcdn.net"); + var requireSettings = new RequireSettings().UseCdnBaseUrl("https://hostcdn.net"); var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); Assert.Equal("script", tagBuilder.TagName); @@ -140,9 +137,7 @@ public void GetScriptResourceWithInlineContent(string applicationPath) [InlineData("/virtualpath/tenant")] public void GetStyleResourceWithUrl(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineStyle("foo") - .SetUrl("~/foo.css", "~/foo.debug.css") - .SetCdn("https://cdn.tld/foo.css", "https://cdn.tld/foo.debug.css"); + var resourceDefinition = _resourceManifest.DefineStyle("foo").SetUrl("~/foo.css", "~/foo.debug.css").SetCdn("https://cdn.tld/foo.css", "https://cdn.tld/foo.debug.css"); var requireSettings = new RequireSettings { DebugMode = false, CdnMode = false }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); @@ -159,9 +154,7 @@ public void GetStyleResourceWithUrl(string applicationPath) [InlineData("/virtualpath/tenant")] public void GetStyleResourceWithDebugUrl(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineStyle("foo") - .SetUrl("~/foo.css", "~/foo.debug.css") - .SetCdn("https://cdn.tld/foo.css", "https://cdn.tld/foo.debug.css"); + var resourceDefinition = _resourceManifest.DefineStyle("foo").SetUrl("~/foo.css", "~/foo.debug.css").SetCdn("https://cdn.tld/foo.css", "https://cdn.tld/foo.debug.css"); var requireSettings = new RequireSettings { DebugMode = true, CdnMode = false }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); @@ -178,9 +171,7 @@ public void GetStyleResourceWithDebugUrl(string applicationPath) [InlineData("/virtualpath/tenant")] public void GetStyleResourceWithCdnUrl(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineStyle("foo") - .SetUrl("~/foo.css", "~/foo.debug.css") - .SetCdn("https://cdn.tld/foo.css", "https://cdn.tld/foo.debug.css"); + var resourceDefinition = _resourceManifest.DefineStyle("foo").SetUrl("~/foo.css", "~/foo.debug.css").SetCdn("https://cdn.tld/foo.css", "https://cdn.tld/foo.debug.css"); var requireSettings = new RequireSettings { DebugMode = false, CdnMode = true }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); @@ -202,10 +193,14 @@ public void GetStyleResourceWithCdnUrl(string applicationPath) [InlineData("/tenant", "https://external.com/foo.css", "https://external.com/foo.css")] public void GetLocalStyleResourceWithCdnBaseUrl(string applicationPath, string url, string expected) { - var resourceDefinition = _resourceManifest.DefineStyle("foo") - .SetUrl(url, url); + var resourceDefinition = _resourceManifest.DefineStyle("foo").SetUrl(url, url); - var requireSettings = new RequireSettings { DebugMode = false, CdnMode = true, CdnBaseUrl = "https://hostcdn.net" }; + var requireSettings = new RequireSettings + { + DebugMode = false, + CdnMode = true, + CdnBaseUrl = "https://hostcdn.net" + }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); Assert.Equal("link", tagBuilder.TagName); @@ -220,9 +215,7 @@ public void GetLocalStyleResourceWithCdnBaseUrl(string applicationPath, string u [InlineData("/virtualpath/tenant")] public void GetStyleResourceWithDebugCdnUrl(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineStyle("foo") - .SetUrl("~/foo.css", "~/foo.debug.css") - .SetCdn("https://cdn.tld/foo.css", "https://cdn.tld/foo.debug.css"); + var resourceDefinition = _resourceManifest.DefineStyle("foo").SetUrl("~/foo.css", "~/foo.debug.css").SetCdn("https://cdn.tld/foo.css", "https://cdn.tld/foo.debug.css"); var requireSettings = new RequireSettings { DebugMode = true, CdnMode = true }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); @@ -239,10 +232,7 @@ public void GetStyleResourceWithDebugCdnUrl(string applicationPath) [InlineData("/virtualpath/tenant")] public void GetStyleResourceWithAttributes(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineStyle("foo") - .SetUrl("~/foo.css", "~/foo.debug.css") - .SetAttribute("id", "foo") - .SetAttribute("media", "all"); + var resourceDefinition = _resourceManifest.DefineStyle("foo").SetUrl("~/foo.css", "~/foo.debug.css").SetAttribute("id", "foo").SetAttribute("media", "all"); var requireSettings = new RequireSettings { DebugMode = false, CdnMode = false }; var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); @@ -260,11 +250,9 @@ public void GetStyleResourceWithAttributes(string applicationPath) [InlineData("/virtualpath/tenant")] public void GetStyleResourceWithInlineContent(string applicationPath) { - var resourceDefinition = _resourceManifest.DefineStyle("foo") - .SetInnerContent("body { background-color: white; }"); + var resourceDefinition = _resourceManifest.DefineStyle("foo").SetInnerContent("body { background-color: white; }"); - var requireSettings = new RequireSettings() - .UseCdnBaseUrl("https://cdn.net"); + var requireSettings = new RequireSettings().UseCdnBaseUrl("https://cdn.net"); var tagBuilder = resourceDefinition.GetTagBuilder(requireSettings, applicationPath, StubFileVersionProvider.Instance); Assert.Equal("style", tagBuilder.TagName); diff --git a/test/OrchardCore.Tests/ResourceManagement/ResourceManagerTests.cs b/test/OrchardCore.Tests/ResourceManagement/ResourceManagerTests.cs index f6f1a8a8dfc..f5585464df5 100644 --- a/test/OrchardCore.Tests/ResourceManagement/ResourceManagerTests.cs +++ b/test/OrchardCore.Tests/ResourceManagement/ResourceManagerTests.cs @@ -29,10 +29,7 @@ public void FindResourceFromManifestProviders() options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); var resourceDefinition = resourceManager.FindResource(new RequireSettings { Type = "foo", Name = "bar2" }); @@ -49,23 +46,14 @@ public void FindHighestVersionedResourceFromManifest() var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineResource("foo", "bar") - .SetUrl("~/bar1.js"); - manifest.DefineResource("foo", "bar") - .SetUrl("~/bar2.js") - .SetVersion("1.0.0"); - manifest.DefineResource("foo", "bar") - .SetUrl("~/bar3.js") - .SetVersion("2.0.0"); - manifest.DefineResource("foo", "bar") - .SetUrl("~/bar4.js"); + manifest.DefineResource("foo", "bar").SetUrl("~/bar1.js"); + manifest.DefineResource("foo", "bar").SetUrl("~/bar2.js").SetVersion("1.0.0"); + manifest.DefineResource("foo", "bar").SetUrl("~/bar3.js").SetVersion("2.0.0"); + manifest.DefineResource("foo", "bar").SetUrl("~/bar4.js"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); var resourceDefinition = resourceManager.FindResource(new RequireSettings { Type = "foo", Name = "bar" }); Assert.NotNull(resourceDefinition); @@ -78,10 +66,7 @@ public void FindHighestVersionedResourceFromManifest() [Fact] public void RegisterResouceUrl() { - var resourceManager = new ResourceManager( - new OptionsWrapper(new ResourceManagementOptions()), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(new ResourceManagementOptions()), StubFileVersionProvider.Instance); var requireSetting = resourceManager.RegisterUrl("foo", "schema://domain.ext/resource", "schema://domain.ext/resource.debug"); @@ -95,10 +80,7 @@ public void RegisterResouceUrl() [Fact] public void RegisteredResouceUrlIsRequired() { - var resourceManager = new ResourceManager( - new OptionsWrapper(new ResourceManagementOptions()), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(new ResourceManagementOptions()), StubFileVersionProvider.Instance); resourceManager.RegisterUrl("foo", "schema://domain.ext/resource", "schema://domain.ext/resource.debug"); @@ -121,10 +103,7 @@ public void RegisteredResouceNameIsRequired() options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); resourceManager.RegisterResource("foo", "bar"); @@ -143,40 +122,26 @@ public void RequireDependencies() var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineResource("foo", "first-resource") - .SetDependencies("first-dependency") - .SetPosition(ResourcePosition.First); - manifest.DefineResource("foo", "requires-dependency") - .SetDependencies("dependency"); + manifest.DefineResource("foo", "first-resource").SetDependencies("first-dependency").SetPosition(ResourcePosition.First); + manifest.DefineResource("foo", "requires-dependency").SetDependencies("dependency"); manifest.DefineResource("foo", "dependency"); - manifest.DefineResource("foo", "another-dependency") - .SetDependencies("first-dependency"); + manifest.DefineResource("foo", "another-dependency").SetDependencies("first-dependency"); manifest.DefineResource("foo", "first-dependency"); - manifest.DefineResource("foo", "last-dependency") - .SetPosition(ResourcePosition.Last) - .SetDependencies("another-dependency"); - manifest.DefineResource("foo", "simple-resource") - .SetDependencies("first-dependency"); - manifest.DefineResource("foo", "last-resource") - .SetPosition(ResourcePosition.Last) - .SetDependencies("last-dependency"); + manifest.DefineResource("foo", "last-dependency").SetPosition(ResourcePosition.Last).SetDependencies("another-dependency"); + manifest.DefineResource("foo", "simple-resource").SetDependencies("first-dependency"); + manifest.DefineResource("foo", "last-resource").SetPosition(ResourcePosition.Last).SetDependencies("last-dependency"); manifest.DefineResource("foo", "not-used-resource"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); resourceManager.RegisterResource("foo", "last-resource"); resourceManager.RegisterResource("foo", "requires-dependency"); resourceManager.RegisterResource("foo", "first-resource"); resourceManager.RegisterResource("foo", "simple-resource"); - var requiredResources = resourceManager.GetRequiredResources("foo") - .Select(ctx => ctx.Resource) - .ToList(); + var requiredResources = resourceManager.GetRequiredResources("foo").Select(ctx => ctx.Resource).ToList(); // Ensure dependencies loaded Assert.True(requiredResources.Count == 8); @@ -206,17 +171,12 @@ public void RequireCircularDependenciesShouldThrowException() var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineResource("foo", "required") - .SetDependencies("dependency"); - manifest.DefineResource("foo", "dependency") - .SetDependencies("required"); + manifest.DefineResource("foo", "required").SetDependencies("dependency"); + manifest.DefineResource("foo", "dependency").SetDependencies("required"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); resourceManager.RegisterResource("foo", "required"); @@ -230,19 +190,13 @@ public void RequireCircularNestedDependencyShouldThrowException() var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineResource("foo", "requires-dependency") - .SetDependencies("dependency"); - manifest.DefineResource("foo", "requires-indirect-dependency") - .SetDependencies("requires-dependency"); - manifest.DefineResource("foo", "dependency") - .SetDependencies("requires-indirect-dependency"); + manifest.DefineResource("foo", "requires-dependency").SetDependencies("dependency"); + manifest.DefineResource("foo", "requires-indirect-dependency").SetDependencies("requires-dependency"); + manifest.DefineResource("foo", "dependency").SetDependencies("requires-indirect-dependency"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); resourceManager.RegisterResource("foo", "requires-indirect-dependency"); resourceManager.RegisterResource("foo", "requires-dependency"); @@ -257,23 +211,16 @@ public void RequireByDependencyResourceThatDependsOnLastPositionedResourceShould var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineResource("foo", "resource") - .SetDependencies("last-resource"); - manifest.DefineResource("foo", "last-resource") - .SetPosition(ResourcePosition.Last); + manifest.DefineResource("foo", "resource").SetDependencies("last-resource"); + manifest.DefineResource("foo", "last-resource").SetPosition(ResourcePosition.Last); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); resourceManager.RegisterResource("foo", "resource"); - var requiredResources = resourceManager.GetRequiredResources("foo") - .Select(ctx => ctx.Resource) - .ToList(); + var requiredResources = resourceManager.GetRequiredResources("foo").Select(ctx => ctx.Resource).ToList(); // Ensure dependencies loaded Assert.True(requiredResources.Count == 2); @@ -292,22 +239,15 @@ public void RequireFirstPositionedResourceThatDependsOnByDependencyResourceShoul var manifest = new ResourceManifest(); manifest.DefineResource("foo", "dependency"); - manifest.DefineResource("foo", "first-resource") - .SetDependencies("dependency") - .SetPosition(ResourcePosition.First); + manifest.DefineResource("foo", "first-resource").SetDependencies("dependency").SetPosition(ResourcePosition.First); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); resourceManager.RegisterResource("foo", "first-resource"); - var requiredResources = resourceManager.GetRequiredResources("foo") - .Select(ctx => ctx.Resource) - .ToList(); + var requiredResources = resourceManager.GetRequiredResources("foo").Select(ctx => ctx.Resource).ToList(); // Ensure dependencies loaded Assert.True(requiredResources.Count == 2); @@ -325,20 +265,13 @@ public void RequireFirstPositionedResourceWithDependencyToResourcePositionedLast var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineResource("foo", "resource") - .SetDependencies("last-resource"); - manifest.DefineResource("foo", "last-resource") - .SetPosition(ResourcePosition.Last); - manifest.DefineResource("foo", "first-resource") - .SetPosition(ResourcePosition.First) - .SetDependencies("resource"); + manifest.DefineResource("foo", "resource").SetDependencies("last-resource"); + manifest.DefineResource("foo", "last-resource").SetPosition(ResourcePosition.Last); + manifest.DefineResource("foo", "first-resource").SetPosition(ResourcePosition.First).SetDependencies("resource"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); resourceManager.RegisterResource("foo", "first-resource"); resourceManager.RegisterResource("foo", "last-resource"); @@ -359,19 +292,14 @@ public void RemoveRequiredResource() options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); resourceManager.RegisterResource("foo", "required"); resourceManager.RegisterResource("foo", "to-remove"); resourceManager.NotRequired("foo", "to-remove"); - var requiredResources = resourceManager.GetRequiredResources("foo") - .Select(ctx => ctx.Resource) - .ToList(); + var requiredResources = resourceManager.GetRequiredResources("foo").Select(ctx => ctx.Resource).ToList(); Assert.Contains(requiredResources, resource => resource.Name == "required"); Assert.DoesNotContain(requiredResources, resource => resource.Name == "to-remove"); @@ -385,26 +313,20 @@ public void RemoveRequiredResourceDependency() var manifest = new ResourceManifest(); manifest.DefineResource("foo", "required"); - manifest.DefineResource("foo", "to-remove") - .SetDependencies("dependency"); + manifest.DefineResource("foo", "to-remove").SetDependencies("dependency"); manifest.DefineResource("foo", "dependency"); manifest.DefineResource("foo", "not-required"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); resourceManager.RegisterResource("foo", "required"); resourceManager.RegisterResource("foo", "to-remove"); resourceManager.NotRequired("foo", "to-remove"); - var requiredResources = resourceManager.GetRequiredResources("foo") - .Select(ctx => ctx.Resource) - .ToList(); + var requiredResources = resourceManager.GetRequiredResources("foo").Select(ctx => ctx.Resource).ToList(); Assert.Contains(requiredResources, resource => resource.Name == "required"); Assert.DoesNotContain(requiredResources, resource => resource.Name == "to-remove"); @@ -415,10 +337,7 @@ public void RemoveRequiredResourceDependency() [Fact] public void RegisterHeadScript() { - var resourceManager = new ResourceManager( - new OptionsWrapper(new ResourceManagementOptions()), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(new ResourceManagementOptions()), StubFileVersionProvider.Instance); var customScript = ""; resourceManager.RegisterHeadScript(new HtmlString(customScript)); @@ -431,10 +350,7 @@ public void RegisterHeadScript() [Fact] public void RegisterFootScript() { - var resourceManager = new ResourceManager( - new OptionsWrapper(new ResourceManagementOptions()), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(new ResourceManagementOptions()), StubFileVersionProvider.Instance); var customScript = ""; resourceManager.RegisterFootScript(new HtmlString(customScript)); @@ -447,10 +363,7 @@ public void RegisterFootScript() [Fact] public void RegisterStyle() { - var resourceManager = new ResourceManager( - new OptionsWrapper(new ResourceManagementOptions()), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(new ResourceManagementOptions()), StubFileVersionProvider.Instance); var customStyle = ""; resourceManager.RegisterStyle(new HtmlString(customStyle)); @@ -463,16 +376,9 @@ public void RegisterStyle() [Fact] public void RegisterLink() { - var resourceManager = new ResourceManager( - new OptionsWrapper(new ResourceManagementOptions()), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(new ResourceManagementOptions()), StubFileVersionProvider.Instance); - var linkEntry = new LinkEntry - { - Rel = "foo", - Href = "bar.ext" - }; + var linkEntry = new LinkEntry { Rel = "foo", Href = "bar.ext" }; resourceManager.RegisterLink(linkEntry); @@ -484,10 +390,7 @@ public void RegisterLink() [Fact] public void RegisterMeta() { - var resourceManager = new ResourceManager( - new OptionsWrapper(new ResourceManagementOptions()), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(new ResourceManagementOptions()), StubFileVersionProvider.Instance); var metaEntry = new MetaEntry(name: "foo", content: "bar"); @@ -501,25 +404,18 @@ public void RegisterMeta() [Fact] public async Task AppendMeta() { - var resourceManager = new ResourceManager( - new OptionsWrapper(new ResourceManagementOptions()), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(new ResourceManagementOptions()), StubFileVersionProvider.Instance); - var first = new MetaEntry(name: "keywords", content: "bar") - .AddAttribute("attr1", "val1"); - var second = new MetaEntry(name: "keywords", content: "baz") - .AddAttribute("attr2", "val2"); + var first = new MetaEntry(name: "keywords", content: "bar").AddAttribute("attr1", "val1"); + var second = new MetaEntry(name: "keywords", content: "baz").AddAttribute("attr2", "val2"); resourceManager.AppendMeta(first, ","); resourceManager.AppendMeta(second, ","); - var keywordsMeta = resourceManager.GetRegisteredMetas() - .FirstOrDefault(entry => entry.Name == "keywords"); + var keywordsMeta = resourceManager.GetRegisteredMetas().FirstOrDefault(entry => entry.Name == "keywords"); var document = await ParseHtmlAsync(keywordsMeta.GetTag()); - var meta = document - .QuerySelector("meta[name=keywords]"); + var meta = document.QuerySelector("meta[name=keywords]"); Assert.Equal("bar,baz", meta.Content); Assert.Contains(meta.Attributes, attr => attr.Name == "attr1" && attr.Value == "val1"); @@ -529,10 +425,7 @@ public async Task AppendMeta() [Fact] public async Task RenderMeta() { - var resourceManager = new ResourceManager( - new OptionsWrapper(new ResourceManagementOptions()), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(new ResourceManagementOptions()), StubFileVersionProvider.Instance); resourceManager.RegisterMeta(new MetaEntry { Charset = "utf-8" }); resourceManager.RegisterMeta(new MetaEntry { Name = "description", Content = "Some content" }); @@ -544,8 +437,7 @@ public async Task RenderMeta() htmlBuilder.AppendHtml(sw.ToString()); var document = await ParseHtmlAsync(htmlBuilder); - var metas = document - .QuerySelectorAll("meta"); + var metas = document.QuerySelectorAll("meta"); Assert.Equal(3, metas.Count()); Assert.Contains(metas, meta => meta.Charset == "utf-8"); @@ -556,14 +448,18 @@ public async Task RenderMeta() [Fact] public async Task RenderHeadLink() { - var resourceManager = new ResourceManager( - new OptionsWrapper(new ResourceManagementOptions()), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(new ResourceManagementOptions()), StubFileVersionProvider.Instance); - resourceManager.RegisterUrl("stylesheet", "other.min.css", "other.css"); // Should not be rendered + resourceManager.RegisterUrl("stylesheet", "other.min.css", "other.css"); // Should not be rendered resourceManager.RegisterLink(new LinkEntry { Rel = "icon", Href = "/favicon.ico" }); - resourceManager.RegisterLink(new LinkEntry { Rel = "alternate", Type = "application/pdf", Href = "/pdf" }); + resourceManager.RegisterLink( + new LinkEntry + { + Rel = "alternate", + Type = "application/pdf", + Href = "/pdf" + } + ); using var sw = new StringWriter(); resourceManager.RenderHeadLink(sw); @@ -571,8 +467,7 @@ public async Task RenderHeadLink() htmlBuilder.AppendHtml(sw.ToString()); var document = await ParseHtmlAsync(htmlBuilder); - var links = document - .QuerySelectorAll("link"); + var links = document.QuerySelectorAll("link"); Assert.Equal(2, links.Count()); Assert.Contains(links, link => link.Relation == "icon" && link.Href == $"{BasePath}/favicon.ico"); @@ -585,19 +480,15 @@ public async Task RenderStylesheet() var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineStyle("required").SetUrl("required.css") - .SetDependencies("dependency"); + manifest.DefineStyle("required").SetUrl("required.css").SetDependencies("dependency"); manifest.DefineStyle("dependency").SetUrl("dependency.css"); manifest.DefineStyle("not-required").SetUrl("not-required.css"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); - resourceManager.RegisterLink(new LinkEntry { Rel = "icon", Href = "/favicon.ico" }); // Should not be rendered + resourceManager.RegisterLink(new LinkEntry { Rel = "icon", Href = "/favicon.ico" }); // Should not be rendered // Require resource resourceManager.RegisterResource("stylesheet", "required"); @@ -612,10 +503,8 @@ public async Task RenderStylesheet() htmlBuilder.AppendHtml(sw.ToString()); var document = await ParseHtmlAsync(htmlBuilder); - var links = document - .QuerySelectorAll("link"); - var styles = document - .QuerySelectorAll("style"); + var links = document.QuerySelectorAll("link"); + var styles = document.QuerySelectorAll("style"); Assert.Equal(2, links.Count()); Assert.Contains(links, link => link.Href == $"{BasePath}/dependency.css"); @@ -623,16 +512,14 @@ public async Task RenderStylesheet() Assert.Single(styles); Assert.Contains(styles, style => style.InnerHtml == customStyle); // Required stylesheet after its dependency - Assert.Equal(DocumentPositions.Following, links.First(link => link.Href == $"{BasePath}/dependency.css") - .CompareDocumentPosition( - links.First(link => link.Href == $"{BasePath}/required.css") - ) + Assert.Equal( + DocumentPositions.Following, + links.First(link => link.Href == $"{BasePath}/dependency.css").CompareDocumentPosition(links.First(link => link.Href == $"{BasePath}/required.css")) ); // Custom style after resources - Assert.Equal(DocumentPositions.Following, links.First(link => link.Href == $"{BasePath}/required.css") - .CompareDocumentPosition( - styles.First(style => style.InnerHtml == customStyle) - ) + Assert.Equal( + DocumentPositions.Following, + links.First(link => link.Href == $"{BasePath}/required.css").CompareDocumentPosition(styles.First(style => style.InnerHtml == customStyle)) ); } @@ -642,17 +529,13 @@ public async Task RenderHeadScript() var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineScript("required").SetUrl("required.js") - .SetDependencies("dependency"); + manifest.DefineScript("required").SetUrl("required.js").SetDependencies("dependency"); manifest.DefineScript("dependency").SetUrl("dependency.js"); manifest.DefineScript("not-required").SetUrl("not-required.js"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); // Require resource resourceManager.RegisterResource("script", "required").AtHead(); @@ -667,24 +550,21 @@ public async Task RenderHeadScript() htmlBuilder.AppendHtml(sw.ToString()); var document = await ParseHtmlAsync(htmlBuilder); - var scripts = document - .QuerySelectorAll("script"); + var scripts = document.QuerySelectorAll("script"); Assert.Equal(3, scripts.Count()); Assert.Contains(scripts, script => script.Source == "dependency.js"); Assert.Contains(scripts, script => script.Source == "required.js"); Assert.Contains(scripts, script => script.Text == customScript); // Required script after its dependency - Assert.Equal(DocumentPositions.Following, scripts.First(script => script.Source == "dependency.js") - .CompareDocumentPosition( - scripts.First(script => script.Source == "required.js") - ) + Assert.Equal( + DocumentPositions.Following, + scripts.First(script => script.Source == "dependency.js").CompareDocumentPosition(scripts.First(script => script.Source == "required.js")) ); // Custom script after resources - Assert.Equal(DocumentPositions.Following, scripts.First(script => script.Source == "required.js") - .CompareDocumentPosition( - scripts.First(script => script.Text == customScript) - ) + Assert.Equal( + DocumentPositions.Following, + scripts.First(script => script.Source == "required.js").CompareDocumentPosition(scripts.First(script => script.Text == customScript)) ); } @@ -694,17 +574,13 @@ public async Task RenderFootScript() var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineScript("required").SetUrl("required.js") - .SetDependencies("dependency"); + manifest.DefineScript("required").SetUrl("required.js").SetDependencies("dependency"); manifest.DefineScript("dependency").SetUrl("dependency.js"); manifest.DefineScript("not-required").SetUrl("not-required.js"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); // Require resource resourceManager.RegisterResource("script", "required").AtFoot(); @@ -719,24 +595,21 @@ public async Task RenderFootScript() htmlBuilder.AppendHtml(sw.ToString()); var document = await ParseHtmlAsync(htmlBuilder); - var scripts = document - .QuerySelectorAll("script"); + var scripts = document.QuerySelectorAll("script"); Assert.Equal(3, scripts.Count()); Assert.Contains(scripts, script => script.Source == "dependency.js"); Assert.Contains(scripts, script => script.Source == "required.js"); Assert.Contains(scripts, script => script.Text == customScript); // Required script after its dependency - Assert.Equal(DocumentPositions.Following, scripts.First(script => script.Source == "dependency.js") - .CompareDocumentPosition( - scripts.First(script => script.Source == "required.js") - ) + Assert.Equal( + DocumentPositions.Following, + scripts.First(script => script.Source == "dependency.js").CompareDocumentPosition(scripts.First(script => script.Source == "required.js")) ); // Custom script after resources - Assert.Equal(DocumentPositions.Following, scripts.First(script => script.Source == "required.js") - .CompareDocumentPosition( - scripts.First(script => script.Text == customScript) - ) + Assert.Equal( + DocumentPositions.Following, + scripts.First(script => script.Source == "required.js").CompareDocumentPosition(scripts.First(script => script.Text == customScript)) ); } @@ -746,27 +619,17 @@ public async Task RenderHeadAndFootScriptWithSameDependency() var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineScript("required") - .SetUrl("required.js") - .SetDependencies("dependency"); + manifest.DefineScript("required").SetUrl("required.js").SetDependencies("dependency"); - manifest.DefineScript("dependency") - .SetUrl("dependency.js"); + manifest.DefineScript("dependency").SetUrl("dependency.js"); - manifest.DefineScript("required-at-foot") - .SetUrl("required-at-foot.js") - .SetDependencies("dependency"); + manifest.DefineScript("required-at-foot").SetUrl("required-at-foot.js").SetDependencies("dependency"); - manifest.DefineScript("not-required") - .SetUrl("not-required.js"); + manifest.DefineScript("not-required").SetUrl("not-required.js"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager - ( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); // Require resource. resourceManager.RegisterResource("script", "required").AtHead(); @@ -784,8 +647,7 @@ public async Task RenderHeadAndFootScriptWithSameDependency() htmlBuilder.AppendHtml(sw1.ToString()); var document = await ParseHtmlAsync(htmlBuilder); - var headScripts = document - .QuerySelectorAll("script"); + var headScripts = document.QuerySelectorAll("script"); using var sw2 = new StringWriter(); resourceManager.RenderFootScript(sw2); @@ -793,8 +655,7 @@ public async Task RenderHeadAndFootScriptWithSameDependency() htmlBuilder.AppendHtml(sw2.ToString()); document = await ParseHtmlAsync(htmlBuilder); - var footScripts = document - .QuerySelectorAll("script"); + var footScripts = document.QuerySelectorAll("script"); // Should render 4 scripts in total, 3 at head and 1 at foot. Assert.Equal(4, headScripts.Count() + footScripts.Count()); @@ -814,17 +675,13 @@ public async Task RenderLocalScript() var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineScript("required").SetUrl("required.js") - .SetDependencies("dependency"); + manifest.DefineScript("required").SetUrl("required.js").SetDependencies("dependency"); manifest.DefineScript("dependency").SetUrl("dependency.js"); manifest.DefineScript("not-required").SetUrl("not-required.js"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); var requireSetting = resourceManager.RegisterResource("script", "required"); @@ -833,18 +690,15 @@ public async Task RenderLocalScript() var htmlBuilder = new HtmlContentBuilder(); htmlBuilder.AppendHtml(sw.ToString()); - var document = await ParseHtmlAsync(htmlBuilder); - var scripts = document - .QuerySelectorAll("script"); + var scripts = document.QuerySelectorAll("script"); Assert.Equal(2, scripts.Count()); Assert.Contains(scripts, script => script.Source == "dependency.js"); Assert.Contains(scripts, script => script.Source == "required.js"); - Assert.Equal(DocumentPositions.Following, scripts.First(script => script.Source == "dependency.js") - .CompareDocumentPosition( - scripts.First(script => script.Source == "required.js") - ) + Assert.Equal( + DocumentPositions.Following, + scripts.First(script => script.Source == "dependency.js").CompareDocumentPosition(scripts.First(script => script.Source == "required.js")) ); } @@ -854,17 +708,13 @@ public async Task RenderLocalStyle() var options = new ResourceManagementOptions(); var manifest = new ResourceManifest(); - manifest.DefineStyle("required").SetUrl("required.css") - .SetDependencies("dependency"); + manifest.DefineStyle("required").SetUrl("required.css").SetDependencies("dependency"); manifest.DefineStyle("dependency").SetUrl("dependency.css"); manifest.DefineStyle("not-required").SetUrl("not-required.css"); options.ResourceManifests.Add(manifest); - var resourceManager = new ResourceManager( - new OptionsWrapper(options), - StubFileVersionProvider.Instance - ); + var resourceManager = new ResourceManager(new OptionsWrapper(options), StubFileVersionProvider.Instance); var requireSetting = resourceManager.RegisterResource("stylesheet", "required").AtLocation(ResourceLocation.Inline); @@ -874,16 +724,14 @@ public async Task RenderLocalStyle() htmlBuilder.AppendHtml(sw.ToString()); var document = await ParseHtmlAsync(htmlBuilder); - var scripts = document - .QuerySelectorAll("link"); + var scripts = document.QuerySelectorAll("link"); Assert.Equal(2, scripts.Count()); Assert.Contains(scripts, script => script.Href.EndsWith("dependency.css")); Assert.Contains(scripts, script => script.Href.EndsWith("required.css")); - Assert.Equal(DocumentPositions.Following, scripts.First(script => script.Href.EndsWith("dependency.css")) - .CompareDocumentPosition( - scripts.First(script => script.Href.EndsWith("required.css")) - ) + Assert.Equal( + DocumentPositions.Following, + scripts.First(script => script.Href.EndsWith("dependency.css")).CompareDocumentPosition(scripts.First(script => script.Href.EndsWith("required.css"))) ); } diff --git a/test/OrchardCore.Tests/Routing/AutorouteEntriesTests.cs b/test/OrchardCore.Tests/Routing/AutorouteEntriesTests.cs index 17319ba1936..a358a701cf5 100644 --- a/test/OrchardCore.Tests/Routing/AutorouteEntriesTests.cs +++ b/test/OrchardCore.Tests/Routing/AutorouteEntriesTests.cs @@ -20,11 +20,7 @@ public async Task ShouldGetContainedEntryByPath() var entries = scope.ServiceProvider.GetRequiredService(); // Act - var initialEntries = new List() - { - new("container", "container-path"), - new("container", "contained-path", "contained") - }; + var initialEntries = new List() { new("container", "container-path"), new("container", "contained-path", "contained") }; entries.AddEntries(initialEntries); @@ -54,11 +50,7 @@ public async Task ShouldGetEntryByContainedContentItemId() var entries = scope.ServiceProvider.GetRequiredService(); // Act - var initialEntries = new List() - { - new("container", "container-path"), - new("container", "contained-path", "contained") - }; + var initialEntries = new List() { new("container", "container-path"), new("container", "contained-path", "contained") }; entries.AddEntries(initialEntries); @@ -88,11 +80,7 @@ public async Task RemovesContainedEntriesWhenContainerRemoved() var entries = scope.ServiceProvider.GetRequiredService(); // Act - var initialEntries = new List() - { - new("container", "container-path"), - new("container", "contained-path", "contained") - }; + var initialEntries = new List() { new("container", "container-path"), new("container", "contained-path", "contained") }; entries.AddEntries(initialEntries); @@ -132,11 +120,7 @@ public async Task RemovesContainedEntriesWhenDeleted() entries.AddEntries(initialEntries); - var updatedEntries = new List() - { - new("container", "container-path"), - new("container", "contained-path1", "contained1") - }; + var updatedEntries = new List() { new("container", "container-path"), new("container", "contained-path1", "contained1") }; entries.AddEntries(updatedEntries); @@ -165,19 +149,11 @@ public async Task RemovesOldContainedPaths() var entries = scope.ServiceProvider.GetRequiredService(); // Act - var initialEntries = new List() - { - new("container", "container-path"), - new("container", "contained-path-old", "contained") - }; + var initialEntries = new List() { new("container", "container-path"), new("container", "contained-path-old", "contained") }; entries.AddEntries(initialEntries); - var updatedEntries = new List() - { - new("container", "container-path"), - new("container", "contained-path-new", "contained") - }; + var updatedEntries = new List() { new("container", "container-path"), new("container", "contained-path-new", "contained") }; entries.AddEntries(updatedEntries); @@ -226,11 +202,7 @@ public async Task RemovesOldPaths() private static ShellContext CreateShellContext() { - return new ShellContext() - { - Settings = new ShellSettings().AsDefaultShell().AsRunning(), - ServiceProvider = CreateServiceProvider() - }; + return new ShellContext() { Settings = new ShellSettings().AsDefaultShell().AsRunning(), ServiceProvider = CreateServiceProvider() }; } private static ServiceProvider CreateServiceProvider() @@ -249,9 +221,13 @@ public interface IStubAutorouteEntries : IAutorouteEntries private class StubAutorouteEntries : AutorouteEntries, IStubAutorouteEntries { - public StubAutorouteEntries() : base(null) { } + public StubAutorouteEntries() + : base(null) { } + public new void AddEntries(IEnumerable entries) => base.AddEntries(entries); + public new void RemoveEntries(IEnumerable entries) => base.RemoveEntries(entries); + protected override Task InitializeEntriesAsync() => Task.CompletedTask; } } diff --git a/test/OrchardCore.Tests/Security/PermissionHandlerHelper.cs b/test/OrchardCore.Tests/Security/PermissionHandlerHelper.cs index a37386bb05f..015899f2f96 100644 --- a/test/OrchardCore.Tests/Security/PermissionHandlerHelper.cs +++ b/test/OrchardCore.Tests/Security/PermissionHandlerHelper.cs @@ -16,15 +16,11 @@ public static AuthorizationHandlerContext CreateTestAuthorizationHandlerContext( var permission = new Permission(permissionName); identity.AddClaim(permission); } - } var principal = new ClaimsPrincipal(identity); - return new AuthorizationHandlerContext( - new[] { new PermissionRequirement(required) }, - principal, - null); + return new AuthorizationHandlerContext(new[] { new PermissionRequirement(required) }, principal, null); } public static async Task SuccessAsync(this AuthorizationHandlerContext context, params string[] permissionNames) diff --git a/test/OrchardCore.Tests/Shell/RunningShellTableTests.cs b/test/OrchardCore.Tests/Shell/RunningShellTableTests.cs index ea9d54feadc..9dc555bfdf1 100644 --- a/test/OrchardCore.Tests/Shell/RunningShellTableTests.cs +++ b/test/OrchardCore.Tests/Shell/RunningShellTableTests.cs @@ -125,8 +125,18 @@ public void PathAndHostMustBothMatch() { var table = new RunningShellTable(); var settings = new ShellSettings { RequestUrlHost = "www.example.com" }.AsDefaultShell(); - var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "wiki.example.com", RequestUrlPrefix = "foo" }; - var settingsB = new ShellSettings { Name = "Beta", RequestUrlHost = "wiki.example.com", RequestUrlPrefix = "bar" }; + var settingsA = new ShellSettings + { + Name = "Alpha", + RequestUrlHost = "wiki.example.com", + RequestUrlPrefix = "foo" + }; + var settingsB = new ShellSettings + { + Name = "Beta", + RequestUrlHost = "wiki.example.com", + RequestUrlPrefix = "bar" + }; var settingsG = new ShellSettings { Name = "Gamma", RequestUrlHost = "wiki.example.com" }; var settingsD = new ShellSettings { Name = "Delta", RequestUrlPrefix = "Quux" }; table.Add(settings); @@ -157,7 +167,12 @@ public void PathAndHostMustMatchOnFullUrl() { var table = new RunningShellTable(); var settings = new ShellSettings { RequestUrlHost = "www.example.com" }.AsDefaultShell(); - var settingsB = new ShellSettings { Name = "Beta", RequestUrlHost = "wiki.example.com", RequestUrlPrefix = "bar" }; + var settingsB = new ShellSettings + { + Name = "Beta", + RequestUrlHost = "wiki.example.com", + RequestUrlPrefix = "bar" + }; var settingsG = new ShellSettings { Name = "Gamma", RequestUrlHost = "wiki.example.com" }; table.Add(settings); table.Add(settingsB); @@ -168,6 +183,7 @@ public void PathAndHostMustMatchOnFullUrl() Assert.Equal(settingsG, table.Match(new HostString("wiki.example.com"), "/baaz")); Assert.Equal(settingsG, table.Match(new HostString("wiki.example.com"), "/barbaz")); } + [Fact] public void PathAloneWillMatch() { diff --git a/test/OrchardCore.Tests/Shell/ShellContainerFactoryTests.cs b/test/OrchardCore.Tests/Shell/ShellContainerFactoryTests.cs index 50174c4b68d..8b1bf550380 100644 --- a/test/OrchardCore.Tests/Shell/ShellContainerFactoryTests.cs +++ b/test/OrchardCore.Tests/Shell/ShellContainerFactoryTests.cs @@ -11,9 +11,7 @@ namespace OrchardCore.Tests.Shell { public class ShellContainerFactoryTests { - private static readonly ShellSettings _uninitializedDefaultShell = new ShellSettings() - .AsDefaultShell() - .AsUninitialized(); + private static readonly ShellSettings _uninitializedDefaultShell = new ShellSettings().AsDefaultShell().AsUninitialized(); private readonly IShellContainerFactory _shellContainerFactory; private readonly IServiceProvider _applicationServiceProvider; @@ -48,10 +46,7 @@ public async Task CanRegisterDefaultServiceWithFeatureInfo() var expectedFeatureInfo = AddStartup(shellBlueprint, typeof(RegisterServiceStartup)); - var container = (await _shellContainerFactory - .CreateContainerAsync(_uninitializedDefaultShell, shellBlueprint)) - .CreateScope() - .ServiceProvider; + var container = (await _shellContainerFactory.CreateContainerAsync(_uninitializedDefaultShell, shellBlueprint)).CreateScope().ServiceProvider; var typeFeatureProvider = _applicationServiceProvider.GetService(); @@ -67,10 +62,7 @@ public async Task CanReplaceDefaultServiceWithCustomService() var expectedFeatureInfo = AddStartup(shellBlueprint, typeof(ReplaceServiceStartup)); AddStartup(shellBlueprint, typeof(RegisterServiceStartup)); - var container = (await _shellContainerFactory - .CreateContainerAsync(_uninitializedDefaultShell, shellBlueprint)) - .CreateScope() - .ServiceProvider; + var container = (await _shellContainerFactory.CreateContainerAsync(_uninitializedDefaultShell, shellBlueprint)).CreateScope().ServiceProvider; var typeFeatureProvider = _applicationServiceProvider.GetService(); @@ -83,10 +75,7 @@ public async Task CanReplaceDefaultServiceWithCustomService() public async Task HostServiceLifeTimesShouldBePreserved() { var shellBlueprint = CreateBlueprint(); - var container = (await _shellContainerFactory - .CreateContainerAsync(_uninitializedDefaultShell, shellBlueprint)) - .CreateScope() - .ServiceProvider; + var container = (await _shellContainerFactory.CreateContainerAsync(_uninitializedDefaultShell, shellBlueprint)).CreateScope().ServiceProvider; var singleton1 = container.GetRequiredService(); var singleton2 = container.GetRequiredService(); @@ -95,7 +84,8 @@ public async Task HostServiceLifeTimesShouldBePreserved() var scoped1 = container.GetRequiredService(); var scoped2 = container.GetRequiredService(); - ITestScoped scoped3, scoped4; + ITestScoped scoped3, + scoped4; using (var scope = container.CreateScope()) { scoped3 = scope.ServiceProvider.GetRequiredService(); @@ -121,10 +111,7 @@ public async Task WhenTwoHostSingletons_GetServices_Returns_HostAndShellServices var shellBlueprint = CreateBlueprint(); AddStartup(shellBlueprint, typeof(ServicesOfTheSameTypeStartup)); - var container = (await _shellContainerFactory - .CreateContainerAsync(_uninitializedDefaultShell, shellBlueprint)) - .CreateScope() - .ServiceProvider; + var container = (await _shellContainerFactory.CreateContainerAsync(_uninitializedDefaultShell, shellBlueprint)).CreateScope().ServiceProvider; var services = container.GetServices(); @@ -136,10 +123,7 @@ public async Task WhenHostSingletonAndScoped_GetServices_Returns_CorrectImplemen { var shellBlueprint = CreateBlueprint(); - var container = (await _shellContainerFactory - .CreateContainerAsync(_uninitializedDefaultShell, shellBlueprint)) - .CreateScope() - .ServiceProvider; + var container = (await _shellContainerFactory.CreateContainerAsync(_uninitializedDefaultShell, shellBlueprint)).CreateScope().ServiceProvider; var services = container.GetServices(); @@ -166,17 +150,11 @@ public static IFeatureInfo AddStartup(ShellBlueprint shellBlueprint, Type startu return featureInfo; } - private interface ITestService - { - } + private interface ITestService { } - private class TestService : ITestService - { - } + private class TestService : ITestService { } - private class CustomTestService : ITestService - { - } + private class CustomTestService : ITestService { } private class RegisterServiceStartup : StartupBase { diff --git a/test/OrchardCore.Tests/Shell/ShellHostTests.cs b/test/OrchardCore.Tests/Shell/ShellHostTests.cs index 23ca28f34bd..480904e5567 100644 --- a/test/OrchardCore.Tests/Shell/ShellHostTests.cs +++ b/test/OrchardCore.Tests/Shell/ShellHostTests.cs @@ -5,9 +5,7 @@ namespace OrchardCore.Tests.Shell; public class ShellHostTests : SiteContext { - static ShellHostTests() - { - } + static ShellHostTests() { } [Theory] [InlineData("Tenant1", "tenant1", "tEnAnT1")] @@ -16,13 +14,7 @@ public static async Task CanGetShellByCaseInsensitiveName(string name, string ur { await ShellHost.InitializeAsync(); - var shellContext = await ShellHost.GetOrCreateShellContextAsync( - new ShellSettings() - { - Name = name, - RequestUrlPrefix = urlPrefix, - } - .AsUninitialized()); + var shellContext = await ShellHost.GetOrCreateShellContextAsync(new ShellSettings() { Name = name, RequestUrlPrefix = urlPrefix, }.AsUninitialized()); ShellHost.TryGetSettings(searchName, out var foundShellSettings); ShellHost.TryGetShellContext(searchName, out var foundShellContext); diff --git a/test/OrchardCore.Tests/Stubs/MemoryFileBuilder.cs b/test/OrchardCore.Tests/Stubs/MemoryFileBuilder.cs index 43cb29b63b7..a56141a26e9 100644 --- a/test/OrchardCore.Tests/Stubs/MemoryFileBuilder.cs +++ b/test/OrchardCore.Tests/Stubs/MemoryFileBuilder.cs @@ -6,8 +6,7 @@ namespace OrchardCore.Tests.Stubs /// In memory file builder that uses a dictionary as virtual file system. /// Intended for unit testing. /// - public class MemoryFileBuilder - : IFileBuilder + public class MemoryFileBuilder : IFileBuilder { public Dictionary VirtualFiles { get; private set; } = []; diff --git a/test/OrchardCore.Tests/Stubs/TestShapeTableManager.cs b/test/OrchardCore.Tests/Stubs/TestShapeTableManager.cs index eff29a99c76..8ae57d6c374 100644 --- a/test/OrchardCore.Tests/Stubs/TestShapeTableManager.cs +++ b/test/OrchardCore.Tests/Stubs/TestShapeTableManager.cs @@ -8,11 +8,9 @@ public class TestShapeTableManager(ShapeTable defaultShapeTable) : IShapeTableMa { private readonly ShapeTable _defaultShapeTable = defaultShapeTable; - public ShapeTable GetShapeTable(string themeId) - => _defaultShapeTable; + public ShapeTable GetShapeTable(string themeId) => _defaultShapeTable; - public Task GetShapeTableAsync(string themeId) - => Task.FromResult(_defaultShapeTable); + public Task GetShapeTableAsync(string themeId) => Task.FromResult(_defaultShapeTable); } public class MockThemeManager(IExtensionInfo des) : IThemeManager diff --git a/test/OrchardCore.Tests/Utilities/SiteMockHelper.cs b/test/OrchardCore.Tests/Utilities/SiteMockHelper.cs index 012e4594e0f..46e29027a71 100644 --- a/test/OrchardCore.Tests/Utilities/SiteMockHelper.cs +++ b/test/OrchardCore.Tests/Utilities/SiteMockHelper.cs @@ -5,19 +5,15 @@ namespace OrchardCore.Tests.Utilities; public class SiteMockHelper { - public static Mock GetSite(T obj) where T : new() + public static Mock GetSite(T obj) + where T : new() { - var properties = new JsonObject - { - [obj.GetType().Name] = JObject.FromObject(obj) - }; + var properties = new JsonObject { [obj.GetType().Name] = JObject.FromObject(obj) }; var mockSite = new Mock(); - mockSite.Setup(x => x.Properties) - .Returns(properties); + mockSite.Setup(x => x.Properties).Returns(properties); - mockSite.Setup(x => x.As()) - .Returns(obj); + mockSite.Setup(x => x.As()).Returns(obj); return mockSite; } diff --git a/test/OrchardCore.Tests/Workflows/WorkflowManagerTests.cs b/test/OrchardCore.Tests/Workflows/WorkflowManagerTests.cs index 45a7842f869..7580ce7a501 100644 --- a/test/OrchardCore.Tests/Workflows/WorkflowManagerTests.cs +++ b/test/OrchardCore.Tests/Workflows/WorkflowManagerTests.cs @@ -38,19 +38,35 @@ public async Task CanExecuteSimpleWorkflow() ActivityId = "1", IsStart = true, Name = addTask.Name, - Properties = JObject.FromObject(new - { - A = new WorkflowExpression("input(\"A\")"), - B = new WorkflowExpression("input(\"B\")"), - }) + Properties = JObject.FromObject(new { A = new WorkflowExpression("input(\"A\")"), B = new WorkflowExpression("input(\"B\")"), }) }, - new() { ActivityId = "2", Name = writeLineTask.Name, Properties = JObject.FromObject(new { Text = new WorkflowExpression("lastResult().toString()") }) }, - new() { ActivityId = "3", Name = setOutputTask.Name, Properties = JObject.FromObject(new { Value = new WorkflowExpression("lastResult()"), OutputName = "Sum" }) } + new() + { + ActivityId = "2", + Name = writeLineTask.Name, + Properties = JObject.FromObject(new { Text = new WorkflowExpression("lastResult().toString()") }) + }, + new() + { + ActivityId = "3", + Name = setOutputTask.Name, + Properties = JObject.FromObject(new { Value = new WorkflowExpression("lastResult()"), OutputName = "Sum" }) + } ], Transitions = [ - new() { SourceActivityId = "1", SourceOutcomeName = "Done", DestinationActivityId = "2" }, - new() { SourceActivityId = "2", SourceOutcomeName = "Done", DestinationActivityId = "3" } + new() + { + SourceActivityId = "1", + SourceOutcomeName = "Done", + DestinationActivityId = "2" + }, + new() + { + SourceActivityId = "2", + SourceOutcomeName = "Done", + DestinationActivityId = "3" + } ] }; @@ -87,18 +103,10 @@ private static IWorkflowScriptEvaluator CreateWorkflowScriptEvaluator(IServicePr var globalMethodProviders = Array.Empty(); var scriptingManager = new DefaultScriptingManager(new[] { javaScriptEngine }, globalMethodProviders); - return new JavaScriptWorkflowScriptEvaluator( - scriptingManager, - workflowContextHandlers.Resolve(), - new Mock>().Object - ); + return new JavaScriptWorkflowScriptEvaluator(scriptingManager, workflowContextHandlers.Resolve(), new Mock>().Object); } - private static WorkflowManager CreateWorkflowManager( - IServiceProvider serviceProvider, - IEnumerable activities, - WorkflowType workflowType - ) + private static WorkflowManager CreateWorkflowManager(IServiceProvider serviceProvider, IEnumerable activities, WorkflowType workflowType) { var workflowValueSerializers = new Resolver>(serviceProvider); var activityLibrary = new Mock(); @@ -125,7 +133,7 @@ WorkflowType workflowType missingActivityLogger.Object, missingActivityLocalizer.Object, clock.Object - ); + ); foreach (var activity in activities) {