diff --git a/src/OrchardCore.Modules/OrchardCore.Admin/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Admin/Permissions.cs index d8ece2c7663..2cfc0db83a9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Admin/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Admin/Permissions.cs @@ -10,7 +10,7 @@ public class Permissions : IPermissionProvider public Task> GetPermissionsAsync() { - return Task.FromResult(GetPermissions()); + return Task.FromResult(_permissions); } public IEnumerable GetDefaultStereotypes() @@ -20,37 +20,34 @@ public IEnumerable GetDefaultStereotypes() new PermissionStereotype { Name = "Administrator", - Permissions = GetPermissions(), + Permissions = _permissions, }, new PermissionStereotype { Name = "Editor", - Permissions = GetPermissions(), + Permissions = _permissions, }, new PermissionStereotype { Name = "Moderator", - Permissions = GetPermissions(), + Permissions = _permissions, }, new PermissionStereotype { Name = "Author", - Permissions = GetPermissions(), + Permissions = _permissions, }, new PermissionStereotype { Name = "Contributor", - Permissions = GetPermissions(), + Permissions = _permissions, } }; } - private static IEnumerable GetPermissions() - { - return new[] - { - AccessAdminPanel, - }; - } + private readonly IEnumerable _permissions = + [ + AccessAdminPanel + ]; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Migrations.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Migrations.cs index 93c556cc3ff..c6848fbacce 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Migrations.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Migrations.cs @@ -62,7 +62,7 @@ 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 - //.CreateIndex("IDX_AliasPartIndex_DocumentId", + // .CreateIndex("IDX_AliasPartIndex_DocumentId", // "DocumentId", // "Alias", // "ContentItemId", diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Services/AliasPartContentHandleProvider.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Services/AliasPartContentHandleProvider.cs index fc0dd6ecc64..1f961b1440d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Services/AliasPartContentHandleProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Services/AliasPartContentHandleProvider.cs @@ -34,6 +34,6 @@ public async Task GetContentItemIdAsync(string handle) internal class AliasPartContentHandleHelper { internal static Task QueryAliasIndex(ISession session, string alias) => - session.Query(x => x.Alias == alias.ToLowerInvariant()).FirstOrDefaultAsync(); + session.Query(x => x.Alias.Equals(alias, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefaultAsync(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Alias/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Alias/Startup.cs index 7346fd590dd..de8be159574 100644 --- a/src/OrchardCore.Modules/OrchardCore.Alias/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Alias/Startup.cs @@ -39,7 +39,7 @@ public override void ConfigureServices(IServiceCollection services) var session = context.Services.GetRequiredService(); var contentItem = await session.Query(x => - x.Published && x.Alias == alias.ToLowerInvariant()) + x.Published && x.Alias.Equals(alias, System.StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefaultAsync(); if (contentItem == null) diff --git a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/OrchardFieldNameConverter.cs b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/OrchardFieldNameConverter.cs index 347bbe2852c..b8a7bc27986 100644 --- a/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/OrchardFieldNameConverter.cs +++ b/src/OrchardCore.Modules/OrchardCore.Apis.GraphQL/OrchardFieldNameConverter.cs @@ -6,7 +6,7 @@ namespace OrchardCore.Apis.GraphQL { public class OrchardFieldNameConverter : INameConverter { - private readonly INameConverter _defaultConverter = new CamelCaseNameConverter(); + private readonly CamelCaseNameConverter _defaultConverter = new(); // todo: custom argument name? public string NameForArgument(string argumentName, IComplexGraphType parentGraphType, FieldType field) diff --git a/src/OrchardCore.Modules/OrchardCore.AutoSetup/Options/AutoSetupOptions.cs b/src/OrchardCore.Modules/OrchardCore.AutoSetup/Options/AutoSetupOptions.cs index 1af48613966..4f648fed661 100644 --- a/src/OrchardCore.Modules/OrchardCore.AutoSetup/Options/AutoSetupOptions.cs +++ b/src/OrchardCore.Modules/OrchardCore.AutoSetup/Options/AutoSetupOptions.cs @@ -38,7 +38,7 @@ public class AutoSetupOptions : IValidatableObject /// The collection of errors. public IEnumerable Validate(ValidationContext validationContext) { - if (!string.IsNullOrWhiteSpace(AutoSetupPath) && !AutoSetupPath.StartsWith("/")) + if (!string.IsNullOrWhiteSpace(AutoSetupPath) && !AutoSetupPath.StartsWith('/')) { yield return new ValidationResult($"The field '{nameof(AutoSetupPath)}' should be empty or start with '/'."); } diff --git a/src/OrchardCore.Modules/OrchardCore.Autoroute/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Autoroute/Permissions.cs index 1edfe05d78e..2a303cbf83c 100644 --- a/src/OrchardCore.Modules/OrchardCore.Autoroute/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Autoroute/Permissions.cs @@ -9,7 +9,7 @@ public class Permissions : IPermissionProvider public static readonly Permission SetHomepage = new("SetHomepage", "Set homepage."); public Task> GetPermissionsAsync() { - return Task.FromResult(GetPermissions()); + return Task.FromResult>([SetHomepage]); } public IEnumerable GetDefaultStereotypes() @@ -19,17 +19,9 @@ public IEnumerable GetDefaultStereotypes() new PermissionStereotype { Name = "Administrator", - Permissions = GetPermissions(), + Permissions = [SetHomepage], }, }; } - - private static IEnumerable GetPermissions() - { - return new[] - { - SetHomepage, - }; - } } } diff --git a/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Permissions.cs index 2caa9361317..4f6a1fa9034 100644 --- a/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.BackgroundTasks/Permissions.cs @@ -10,7 +10,7 @@ public class Permissions : IPermissionProvider public Task> GetPermissionsAsync() { - return Task.FromResult(GetPermissions()); + return Task.FromResult>([ManageBackgroundTasks]); } public IEnumerable GetDefaultStereotypes() @@ -20,14 +20,9 @@ public IEnumerable GetDefaultStereotypes() new PermissionStereotype { Name = "Administrator", - Permissions = new[] { ManageBackgroundTasks }, + Permissions = [ManageBackgroundTasks], } }; } - - private static IEnumerable GetPermissions() - { - return new[] { ManageBackgroundTasks }; - } } } diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/LocalizationSetContentPickerAdminController.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/LocalizationSetContentPickerAdminController.cs index be638ff8b04..86a43cfcba3 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/LocalizationSetContentPickerAdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Controllers/LocalizationSetContentPickerAdminController.cs @@ -83,7 +83,7 @@ public async Task SearchLocalizationSets(string part, string fiel { results.Add(new VueMultiselectItemViewModel { - Id = contentItem.Key, //localization set + Id = contentItem.Key, // localization set DisplayText = contentItem.Value.ToString(), HasPublished = await _contentManager.HasPublishedVersionAsync(contentItem.Value) }); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LocalizationSetContentPickerFieldDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LocalizationSetContentPickerFieldDisplayDriver.cs index 64673d3f408..90d28901acd 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LocalizationSetContentPickerFieldDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/Drivers/LocalizationSetContentPickerFieldDisplayDriver.cs @@ -69,7 +69,7 @@ public override IDisplayResult Edit(LocalizationSetContentPickerField field, Bui model.SelectedItems.Add(new VueMultiselectItemViewModel { - Id = kvp.Key, //localization set + Id = kvp.Key, // localization set DisplayText = contentItem.ToString(), HasPublished = await _contentManager.HasPublishedVersionAsync(contentItem) }); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ContentFieldsProvider.cs b/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ContentFieldsProvider.cs index 59f55d66be8..410dc161988 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ContentFieldsProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Fields/ContentFieldsProvider.cs @@ -89,12 +89,12 @@ public class ContentFieldsProvider : IContentFieldProvider public FieldType GetField(ContentPartFieldDefinition field) { - if (!_contentFieldTypeMappings.ContainsKey(field.FieldDefinition.Name)) + if (!_contentFieldTypeMappings.TryGetValue(field.FieldDefinition.Name, out var value)) { return null; } - var fieldDescriptor = _contentFieldTypeMappings[field.FieldDefinition.Name]; + var fieldDescriptor = value; return new FieldType { Name = field.Name, diff --git a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/DefaultContentLocalizationManager.cs b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/DefaultContentLocalizationManager.cs index fa6795a4e2b..85c24505a43 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentLocalization/DefaultContentLocalizationManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentLocalization/DefaultContentLocalizationManager.cs @@ -160,14 +160,14 @@ public async Task> GetFirstItemIdForSetsAsync(IEnume /// OR null if nothing found. /// /// List of ContentItemId. - private static IEnumerable 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) + var currentCultureContentItem = set.FirstOrDefault(f => f.Culture == currentCulture); + if (currentCultureContentItem is not null) { - return currentcultureContentItem; + return currentCultureContentItem; } var defaultCultureContentItem = set.FirstOrDefault(f => f.Culture == defaultCulture); diff --git a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Permissions.cs index 48e9c2746dd..d08d14961b0 100644 --- a/src/OrchardCore.Modules/OrchardCore.ContentTypes/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.ContentTypes/Permissions.cs @@ -11,7 +11,7 @@ public class Permissions : IPermissionProvider public Task> GetPermissionsAsync() { - return Task.FromResult(GetPermissions()); + return Task.FromResult(_permissions); } public IEnumerable GetDefaultStereotypes() @@ -21,18 +21,15 @@ public IEnumerable GetDefaultStereotypes() new PermissionStereotype { Name = "Administrator", - Permissions = GetPermissions(), + Permissions = _permissions, }, }; } - private static IEnumerable GetPermissions() - { - return new[] - { - ViewContentTypes, - EditContentTypes, - }; - } + private readonly IEnumerable _permissions = + [ + ViewContentTypes, + EditContentTypes, + ]; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/ContentItemRecursionHelper.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/ContentItemRecursionHelper.cs index afb859592f6..c955912bfc5 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/ContentItemRecursionHelper.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Liquid/ContentItemRecursionHelper.cs @@ -19,9 +19,8 @@ public class ContentItemRecursionHelper : IContentItemRecursionHelper /// public bool IsRecursive(ContentItem contentItem, int maxRecursions = 1) { - if (_recursions.ContainsKey(contentItem)) + if (_recursions.TryGetValue(contentItem, out var counter)) { - var counter = _recursions[contentItem]; if (maxRecursions < 1) { maxRecursions = 1; diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/ViewModels/PublishContentViewModel.cs b/src/OrchardCore.Modules/OrchardCore.Contents/ViewModels/PublishContentViewModel.cs index f495d57ba93..6f9f03dac25 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/ViewModels/PublishContentViewModel.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/ViewModels/PublishContentViewModel.cs @@ -1,7 +1,7 @@ -//using OrchardCore.ContentManagement; +// using OrchardCore.ContentManagement; -//namespace OrchardCore.Contents.ViewModels -//{ +// namespace OrchardCore.Contents.ViewModels +// { // public class PublishContentViewModel // { // public PublishContentViewModel(ContentItem contentItem) @@ -9,10 +9,10 @@ // ContentItem = contentItem; // } -// public ContentItem ContentItem { get; private set; } +// public ContentItem ContentItem { get; private set; } // public bool HasDraft { get; } // public bool HasPublished { get; } -// //ContentItem.ContentManager.Get(ContentItem.Id, VersionOptions.Published) != null; +// //ContentItem.ContentManager.Get(ContentItem.Id, VersionOptions.Published) != null; // } -//} +// } diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Demo/Startup.cs index 0c68d779729..340d07f95cc 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/Startup.cs @@ -118,7 +118,7 @@ public override void ConfigureServices(IServiceCollection services) options.Conventions.AddAreaPageRoute("OrchardCore.Demo", "/Hello", "Hello"); // This declaration would define an home page - //options.Conventions.AddAreaPageRoute("OrchardCore.Demo", "/Hello", ""); + // options.Conventions.AddAreaPageRoute("OrchardCore.Demo", "/Hello", ""); }); services.AddTagHelpers(typeof(BazTagHelper).Assembly); diff --git a/src/OrchardCore.Modules/OrchardCore.Demo/TagHelpers/BazTagHelper.cs b/src/OrchardCore.Modules/OrchardCore.Demo/TagHelpers/BazTagHelper.cs index b49c0a51ce0..2b83139e5fd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Demo/TagHelpers/BazTagHelper.cs +++ b/src/OrchardCore.Modules/OrchardCore.Demo/TagHelpers/BazTagHelper.cs @@ -7,8 +7,8 @@ namespace OrchardCore.Demo.TagHelpers [HtmlTargetElement("baz")] public class BazTagHelper : BaseShapeTagHelper { - public BazTagHelper(IShapeFactory shapeFactory, IDisplayHelper displayHelper) : - base(shapeFactory, displayHelper) + public BazTagHelper(IShapeFactory shapeFactory, IDisplayHelper displayHelper) + : base(shapeFactory, displayHelper) { Type = "Baz"; } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteClientController.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteClientController.cs index e3fae17ba72..f81e3257fae 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteClientController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteClientController.cs @@ -253,7 +253,7 @@ public async Task IndexPost(ViewModels.ContentOptions options, IEn await _notifier.SuccessAsync(H["Remote clients successfully removed."]); break; default: - throw new ArgumentOutOfRangeException(nameof(options.BulkAction), "Invalid bulk action."); + return BadRequest(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteInstanceController.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteInstanceController.cs index 8187935c55d..2712b5cf118 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteInstanceController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Controllers/RemoteInstanceController.cs @@ -248,7 +248,7 @@ public async Task IndexPost(ViewModels.ContentOptions options, IEn await _notifier.SuccessAsync(H["Remote instances successfully removed."]); break; default: - throw new ArgumentOutOfRangeException(nameof(options.BulkAction), "Invalid bulk action."); + return BadRequest(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Startup.cs index 1f6f33c8a05..e6b293b9e06 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment.Remote/Startup.cs @@ -90,7 +90,7 @@ public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder ro defaults: new { controller = remoteInstanceControllerName, action = nameof(RemoteInstanceController.Edit) } ); - //ExportRemoteInstance + // ExportRemoteInstance routes.MapAreaControllerRoute( name: "DeploymentExportRemoteInstanceExecute", areaName: "OrchardCore.Deployment.Remote", diff --git a/src/OrchardCore.Modules/OrchardCore.Deployment/DeploymentPlanService.cs b/src/OrchardCore.Modules/OrchardCore.Deployment/DeploymentPlanService.cs index fcd981aeea4..bd79c533b3b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Deployment/DeploymentPlanService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Deployment/DeploymentPlanService.cs @@ -79,7 +79,7 @@ public async Task> GetDeploymentPlansAsync(params st return GetDeploymentPlans(deploymentPlans, deploymentPlanNames); } - private static IEnumerable GetDeploymentPlans(IDictionary deploymentPlans, params string[] deploymentPlanNames) + private static IEnumerable GetDeploymentPlans(Dictionary deploymentPlans, params string[] deploymentPlanNames) { foreach (var deploymentPlanName in deploymentPlanNames) { diff --git a/src/OrchardCore.Modules/OrchardCore.Features/Services/ModuleService.cs b/src/OrchardCore.Modules/OrchardCore.Features/Services/ModuleService.cs index 21d2dee2234..051791852df 100644 --- a/src/OrchardCore.Modules/OrchardCore.Features/Services/ModuleService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Features/Services/ModuleService.cs @@ -103,7 +103,7 @@ public async Task DisableFeaturesAsync(IEnumerable featureIds, bool forc ///// Determines if a module was recently installed by using the project's last written time. ///// ///// The extension descriptor. - //public bool IsRecentlyInstalled(ExtensionDescriptor extensionDescriptor) { + // public bool IsRecentlyInstalled(ExtensionDescriptor extensionDescriptor) { // DateTime lastWrittenUtc = _cacheManager.Get(extensionDescriptor, descriptor => { // string projectFile = GetManifestPath(extensionDescriptor); // if (!string.IsNullOrEmpty(projectFile)) { @@ -111,26 +111,26 @@ public async Task DisableFeaturesAsync(IEnumerable featureIds, bool forc // return _virtualPathProvider.GetFileLastWriteTimeUtc(projectFile); // } - // return DateTime.UtcNow; + // return DateTime.UtcNow; // }); - // return DateTime.UtcNow.Subtract(lastWrittenUtc) < new TimeSpan(1, 0, 0, 0); - //} + // return DateTime.UtcNow.Subtract(lastWrittenUtc) < new TimeSpan(1, 0, 0, 0); + // } ///// ///// Retrieves the full path of the manifest file for a module's extension descriptor. ///// ///// The module's extension descriptor. ///// The full path to the module's manifest file. - //private string GetManifestPath(ExtensionDescriptor extensionDescriptor) { + // private string GetManifestPath(ExtensionDescriptor extensionDescriptor) { // string projectPath = _virtualPathProvider.Combine(extensionDescriptor.Location, extensionDescriptor.Id, "module.txt"); - // if (!_virtualPathProvider.FileExists(projectPath)) { + // if (!_virtualPathProvider.FileExists(projectPath)) { // return null; // } - // return projectPath; - //} + // return projectPath; + // } private static ModuleFeature AssembleModuleFromDescriptor(IFeatureInfo featureInfo, bool isEnabled) { @@ -141,11 +141,11 @@ private static ModuleFeature AssembleModuleFromDescriptor(IFeatureInfo featureIn }; } - //private void GenerateWarning(string messageFormat, string featureName, IEnumerable featuresInQuestion) { + // private void GenerateWarning(string messageFormat, string featureName, IEnumerable featuresInQuestion) { // if (featuresInQuestion.Count() < 1) // return; - // Services.Notifier.Warning(T( + // Services.Notifier.Warning(T( // messageFormat, // featureName, // featuresInQuestion.Count() > 1 @@ -158,6 +158,6 @@ private static ModuleFeature AssembleModuleFromDescriptor(IFeatureInfo featureIn // ? "{0} and " // : "{0}, "), fn).ToString()).ToArray()) // : featuresInQuestion.First())); - //} + // } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Forms/GraphQL/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Forms/GraphQL/Startup.cs index 28c079351c4..98abf757870 100644 --- a/src/OrchardCore.Modules/OrchardCore.Forms/GraphQL/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Forms/GraphQL/Startup.cs @@ -20,7 +20,7 @@ public override void ConfigureServices(IServiceCollection services) services.AddObjectGraphType(); // Broken - //services.AddGraphQLQueryType(); + // services.AddGraphQLQueryType(); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.GitHub/Startup.cs b/src/OrchardCore.Modules/OrchardCore.GitHub/Startup.cs index 0aeebd5ce12..fefe09b0c3f 100644 --- a/src/OrchardCore.Modules/OrchardCore.GitHub/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.GitHub/Startup.cs @@ -43,7 +43,7 @@ public override void ConfigureServices(IServiceCollection services) ServiceDescriptor.Transient, GitHubOptionsConfiguration>(), ServiceDescriptor.Transient, GitHubOptionsConfiguration>(), // Built-in initializers: - ServiceDescriptor.Transient, OAuthPostConfigureOptions>() + ServiceDescriptor.Transient, OAuthPostConfigureOptions>() }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationStartup.cs b/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationStartup.cs index 38ef76841f9..2bfce2c74d4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationStartup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Google/GoogleAuthenticationStartup.cs @@ -41,7 +41,7 @@ public override void ConfigureServices(IServiceCollection services) ServiceDescriptor.Transient, GoogleOptionsConfiguration>(), ServiceDescriptor.Transient, GoogleOptionsConfiguration>(), // Built-in initializers: - ServiceDescriptor.Transient, OAuthPostConfigureOptions>() + ServiceDescriptor.Transient, OAuthPostConfigureOptions>() }); services.AddTransient, GoogleAuthenticationSettingsConfiguration>(); diff --git a/src/OrchardCore.Modules/OrchardCore.Indexing/Permissions.cs b/src/OrchardCore.Modules/OrchardCore.Indexing/Permissions.cs index 1a1c321709c..82794f44d9e 100644 --- a/src/OrchardCore.Modules/OrchardCore.Indexing/Permissions.cs +++ b/src/OrchardCore.Modules/OrchardCore.Indexing/Permissions.cs @@ -10,15 +10,7 @@ public class Permissions : IPermissionProvider public Task> GetPermissionsAsync() { - return Task.FromResult(GetPermissions()); - } - - private static IEnumerable GetPermissions() - { - return new[] - { - ManageIndexes, - }; + return Task.FromResult(_permissions); } public IEnumerable GetDefaultStereotypes() @@ -28,9 +20,14 @@ public IEnumerable GetDefaultStereotypes() new PermissionStereotype { Name = "Administrator", - Permissions = new[] { ManageIndexes }, + Permissions = _permissions, }, }; } + + private readonly IEnumerable _permissions = + [ + ManageIndexes + ]; } } diff --git a/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/AdminController.cs index cec331ea3d0..c8381d9738f 100644 --- a/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Layers/Controllers/AdminController.cs @@ -340,7 +340,7 @@ public async Task UpdatePosition(string contentItemId, double pos // The state will be updated once the ambient session is committed. await _layerStateManager.UpdateAsync(new LayerState()); - if (Request.Headers != null && Request.Headers["X-Requested-With"] == "XMLHttpRequest") + if (Request.Headers != null && Request.Headers.XRequestedWith == "XMLHttpRequest") { return Ok(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeNavigationBuilder.cs b/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeNavigationBuilder.cs index 045019f3bd5..fcc524e549a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeNavigationBuilder.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/AdminNodes/ListsAdminNodeNavigationBuilder.cs @@ -94,7 +94,7 @@ private async Task AddContentItemsAsync(NavigationBuilder listTypeMenu) { var cim = await _contentManager.PopulateAspectAsync(ci); - if (cim.AdminRouteValues.Any() && ci.DisplayText != null) + if (cim.AdminRouteValues.Count > 0 && ci.DisplayText != null) { listTypeMenu.Add(new LocalizedString(ci.DisplayText, ci.DisplayText), m => { diff --git a/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/OrderController.cs b/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/OrderController.cs index 1a76d99379f..6a9a1d6b6ba 100644 --- a/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/OrderController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Lists/Controllers/OrderController.cs @@ -60,7 +60,7 @@ public async Task UpdateContentItemOrders(string containerId, int new ContainedItemOptions { Status = ContentsStatus.Latest })) .ToList(); - if (pageOfContentItems == null || !pageOfContentItems.Any()) + if (pageOfContentItems == null || pageOfContentItems.Count == 0) { return NotFound(); } diff --git a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Startup.cs index 10e235d7837..3a30f3a99de 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media.AmazonS3/Startup.cs @@ -42,7 +42,7 @@ public override void ConfigureServices(IServiceCollection services) var validationErrors = storeOptions.Validate().ToList(); var stringBuilder = new StringBuilder(); - if (validationErrors.Any()) + if (validationErrors.Count > 0) { foreach (var error in validationErrors) { diff --git a/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaProfilesController.cs b/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaProfilesController.cs index 78cce1f431d..0983ad35641 100644 --- a/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaProfilesController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Media/Controllers/MediaProfilesController.cs @@ -195,12 +195,11 @@ public async Task Edit(string name) var mediaProfilesDocument = await _mediaProfilesManager.GetMediaProfilesDocumentAsync(); - if (!mediaProfilesDocument.MediaProfiles.ContainsKey(name)) + if (!mediaProfilesDocument.MediaProfiles.TryGetValue(name, out var mediaProfile)) { return RedirectToAction(nameof(Create), new { name }); } - var mediaProfile = mediaProfilesDocument.MediaProfiles[name]; // Is a custom width if the width is not 0 and it is not in the array of supported sizes. var isCustomWidth = mediaProfile.Width != 0 && Array.BinarySearch(_mediaOptions.SupportedSizes, mediaProfile.Width) < 0; var isCustomHeight = mediaProfile.Height != 0 && Array.BinarySearch(_mediaOptions.SupportedSizes, mediaProfile.Height) < 0; diff --git a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/MicrosoftAccountStartup.cs b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/MicrosoftAccountStartup.cs index f9cc1326d0b..5ea511e78f9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/MicrosoftAccountStartup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/MicrosoftAccountStartup.cs @@ -42,7 +42,7 @@ public override void ConfigureServices(IServiceCollection services) ServiceDescriptor.Transient, MicrosoftAccountOptionsConfiguration>(), ServiceDescriptor.Transient, MicrosoftAccountOptionsConfiguration>(), // Built-in initializers: - ServiceDescriptor.Transient, OAuthPostConfigureOptions>() + ServiceDescriptor.Transient, OAuthPostConfigureOptions>() }); } } diff --git a/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdApplicationSettings.cs b/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdApplicationSettings.cs index 3816045ebbc..7c634610ada 100644 --- a/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdApplicationSettings.cs +++ b/src/OrchardCore.Modules/OrchardCore.OpenId/OpenIdApplicationSettings.cs @@ -32,6 +32,8 @@ public class OpenIdApplicationSettings internal static class OpenIdApplicationExtensions { + internal static readonly string[] _separator = [" ", ","]; + public static async Task UpdateDescriptorFromSettings(this IOpenIdApplicationManager _applicationManager, OpenIdApplicationSettings model, object application = null) { var descriptor = new OpenIdApplicationDescriptor(); @@ -224,7 +226,7 @@ public static async Task UpdateDescriptorFromSettings(this IOpenIdApplicationMan descriptor.PostLogoutRedirectUris.Clear(); foreach (var uri in - (from uri in model.PostLogoutRedirectUris?.Split(new[] { " ", "," }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty() + (from uri in model.PostLogoutRedirectUris?.Split(_separator, StringSplitOptions.RemoveEmptyEntries) ?? [] select new Uri(uri, UriKind.Absolute))) { descriptor.PostLogoutRedirectUris.Add(uri); @@ -232,7 +234,7 @@ public static async Task UpdateDescriptorFromSettings(this IOpenIdApplicationMan descriptor.RedirectUris.Clear(); foreach (var uri in - (from uri in model.RedirectUris?.Split(new[] { " ", "," }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty() + (from uri in model.RedirectUris?.Split(_separator, StringSplitOptions.RemoveEmptyEntries) ?? [] select new Uri(uri, UriKind.Absolute))) { descriptor.RedirectUris.Add(uri); diff --git a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlGrammar.cs b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlGrammar.cs index 6054da5cd10..eb48ec77bae 100644 --- a/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlGrammar.cs +++ b/src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlGrammar.cs @@ -12,7 +12,7 @@ public SqlGrammar() : base(false) NonGrammarTerminals.Add(lineComment); var number = new NumberLiteral("number"); var string_literal = new StringLiteral("string", "'", StringOptions.AllowsDoubledQuote); - var Id_simple = TerminalFactory.CreateSqlExtIdentifier(this, "id_simple"); //covers normal identifiers (abc) and quoted id's ([abc d], "abc d") + var Id_simple = TerminalFactory.CreateSqlExtIdentifier(this, "id_simple"); // covers normal identifiers (abc) and quoted id's ([abc d], "abc d") var comma = ToTerm(","); var dot = ToTerm("."); #pragma warning disable IDE0059 // Unnecessary assignment of a value diff --git a/src/OrchardCore.Modules/OrchardCore.Recipes/RecipeSteps/RecipesStep.cs b/src/OrchardCore.Modules/OrchardCore.Recipes/RecipeSteps/RecipesStep.cs index 2ab4673e51d..675b97f2516 100644 --- a/src/OrchardCore.Modules/OrchardCore.Recipes/RecipeSteps/RecipesStep.cs +++ b/src/OrchardCore.Modules/OrchardCore.Recipes/RecipeSteps/RecipesStep.cs @@ -34,12 +34,12 @@ public async Task ExecuteAsync(RecipeExecutionContext context) var innerRecipes = new List(); foreach (var recipe in step.Values) { - if (!recipes.ContainsKey(recipe.Name)) + if (!recipes.TryGetValue(recipe.Name, out var value)) { throw new ArgumentException($"No recipe named '{recipe.Name}' was found."); } - innerRecipes.Add(recipes[recipe.Name]); + innerRecipes.Add(value); } context.InnerRecipes = innerRecipes; diff --git a/src/OrchardCore.Modules/OrchardCore.Roles/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Roles/Controllers/AdminController.cs index 7369c58a1af..726caebe324 100644 --- a/src/OrchardCore.Modules/OrchardCore.Roles/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Roles/Controllers/AdminController.cs @@ -248,9 +248,9 @@ private async Task>> Get { var groupKey = GetGroupKey(feature, permission.Category); - if (installedPermissions.ContainsKey(groupKey)) + if (installedPermissions.TryGetValue(groupKey, out var value)) { - installedPermissions[groupKey] = installedPermissions[groupKey].Concat(new[] { permission }); + installedPermissions[groupKey] = value.Concat(new[] { permission }); continue; } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/AllConditionEvaluator.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/AllConditionEvaluator.cs index 07c7b17ae25..d4732bc472d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/AllConditionEvaluator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/AllConditionEvaluator.cs @@ -24,7 +24,7 @@ public async override ValueTask EvaluateAsync(AllConditionGroup condition) } } - if (condition.Conditions.Any()) + if (condition.Conditions.Count > 0) { return true; } diff --git a/src/OrchardCore.Modules/OrchardCore.Rules/Services/RuleService.cs b/src/OrchardCore.Modules/OrchardCore.Rules/Services/RuleService.cs index 05d8aaf3c33..a53ddbc81d1 100644 --- a/src/OrchardCore.Modules/OrchardCore.Rules/Services/RuleService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Rules/Services/RuleService.cs @@ -23,7 +23,7 @@ public async ValueTask EvaluateAsync(Rule rule) } } - if (rule.Conditions.Any()) + if (rule.Conditions.Count > 0) { return true; } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Controllers/AdminController.cs index 6c7510581ed..8e312925f0d 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.AzureAI/Controllers/AdminController.cs @@ -493,7 +493,7 @@ public async Task Reset(string indexName) return RedirectToAction(nameof(Index)); } - private IActionResult NotConfigured() + private ViewResult NotConfigured() => View("NotConfigured"); private static Task AsyncContentItemsAsync(string indexName) diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs index dc01190dbbf..15bb4428ab9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs @@ -633,7 +633,7 @@ private async Task PopulateMenuOptionsAsync(ElasticIndexSettingsViewModel model) .Select(x => new SelectListItem { Text = x.Key, Value = x.Key }); } - private IActionResult NotConfigured() + private ViewResult NotConfigured() => View("NotConfigured"); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexManager.cs b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexManager.cs index 39481ebd0a0..af41d25e452 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexManager.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Lucene/Services/LuceneIndexManager.cs @@ -354,7 +354,7 @@ private Document CreateLuceneDocument(DocumentIndex documentIndex, LuceneIndexSe return doc; } - private BaseDirectory CreateDirectory(string indexName) + private FSDirectory CreateDirectory(string indexName) { lock (this) { diff --git a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/TemplateShortcodeProvider.cs b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/TemplateShortcodeProvider.cs index 94009520bac..b9a0d869299 100644 --- a/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/TemplateShortcodeProvider.cs +++ b/src/OrchardCore.Modules/OrchardCore.Shortcodes/Services/TemplateShortcodeProvider.cs @@ -37,14 +37,10 @@ public async ValueTask EvaluateAsync(string identifier, Arguments argume } // Check if a shortcode template is recursively called. - if (_identifiers.Contains(identifier)) + if (!_identifiers.Add(identifier)) { return null; } - else - { - _identifiers.Add(identifier); - } var model = new ShortcodeViewModel { diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/AdminController.cs index ee08ef52a73..781a08801d3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/AdminController.cs @@ -354,7 +354,7 @@ public async Task ListPost(ViewModels.ContentOptions options, IEnu await _notifier.SuccessAsync(H["Sitemaps successfully removed."]); break; default: - throw new ArgumentOutOfRangeException(nameof(options.BulkAction), "Invalid bulk action."); + return BadRequest(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapIndexController.cs b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapIndexController.cs index f70a1f7afe6..7fa223103d9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapIndexController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Sitemaps/Controllers/SitemapIndexController.cs @@ -357,7 +357,7 @@ public async Task ListPost(ViewModels.ContentOptions options, IEnu await _notifier.SuccessAsync(H["Sitemap indices successfully removed."]); break; default: - throw new ArgumentOutOfRangeException(nameof(options.BulkAction), "Invalid bulk action."); + return BadRequest(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/TemplateController.cs b/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/TemplateController.cs index 7bdadc05089..137be939643 100644 --- a/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/TemplateController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Templates/Controllers/TemplateController.cs @@ -377,7 +377,7 @@ public async Task ListPost(ContentOptions options, IEnumerable> ValidateAsync(TenantModelBase model) } } - if (!string.IsNullOrEmpty(model.Name) && !Regex.IsMatch(model.Name, @"^\w+$")) + if (!string.IsNullOrEmpty(model.Name) && !TenantNameRuleRegex().IsMatch(model.Name)) { errors.Add(new ModelError(nameof(model.Name), S["Invalid tenant name. Must contain characters only and no spaces."])); } @@ -150,5 +151,8 @@ private async Task ValidateConnectionAsync(DbConnectionValidatorContext validati break; } } + + [GeneratedRegex(@"^\w+$")] + private static partial Regex TenantNameRuleRegex(); } } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountController.cs index fbf0d86af09..68939d50549 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/AccountController.cs @@ -672,7 +672,7 @@ public async Task ExternalLogins() .Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider)) .ToList(); model.ShowRemoveButton = await _userManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1; - //model.StatusMessage = StatusMessage; + // model.StatusMessage = StatusMessage; CopyTempDataErrorsToModelState(); @@ -724,7 +724,7 @@ public async Task LinkLoginCallback() await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); // Perform External Login SignIn. await ExternalLoginSignInAsync(user, info); - //StatusMessage = "The external login was added."; + // StatusMessage = "The external login was added."; return RedirectToAction(nameof(ExternalLogins)); } @@ -759,7 +759,7 @@ public async Task RemoveLogin(RemoveLoginViewModel model) } await _signInManager.SignInAsync(user, isPersistent: false); - //StatusMessage = "The external login was removed."; + // StatusMessage = "The external login was removed."; return RedirectToAction(nameof(ExternalLogins)); } diff --git a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ResetPasswordController.cs b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ResetPasswordController.cs index 860c973876c..b92554b75fa 100644 --- a/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ResetPasswordController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Users/Controllers/ResetPasswordController.cs @@ -112,7 +112,7 @@ public async Task ResetPassword(string code = null) } if (code == null) { - //"A code must be supplied for password reset."; + // "A code must be supplied for password reset."; } return View(new ResetPasswordViewModel { ResetToken = code }); } diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/ContentCardShapes.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/ContentCardShapes.cs index 92344505c8d..e52feb0c7dd 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/ContentCardShapes.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/ContentCardShapes.cs @@ -5,13 +5,13 @@ namespace OrchardCore.Widgets { public class ContentCardShapes : ShapeTableProvider { - //Card Shape + // Card Shape private const string ContentCardEdit = "ContentCard_Edit"; - //Frame shape + // Frame shape private const string ContentCardFrame = "ContentCard_Frame"; - //Card Editor Fields + // Card Editor Fields private const string ContentCardFieldsEdit = "ContentCard_Fields_Edit"; public override ValueTask DiscoverAsync(ShapeTableBuilder builder) diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/Controllers/AdminController.cs index 4069a1b5821..f1aa8441be7 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/Controllers/AdminController.cs @@ -42,35 +42,35 @@ public async Task BuildEditor(string id, string prefix, string pr var cardCollectionType = nameof(WidgetsListPart); - //Create a Card Shape + // Create a Card Shape dynamic contentCard = await _shapeFactory.New.ContentCard( - //Updater is the controller for AJAX Requests + // Updater is the controller for AJAX Requests Updater: _updateModelAccessor.ModelUpdater, - //Shape Specific + // Shape Specific CollectionShapeType: cardCollectionType, ContentItem: contentItem, BuildEditor: true, ParentContentType: parentContentType, CollectionPartName: partName, - //WidgetListPart Specific + // WidgetListPart Specific ZoneValue: zone, - //Card Specific Properties + // Card Specific Properties TargetId: targetId, Inline: true, CanMove: true, CanDelete: true, - //Input hidden - //Prefixes + // Input hidden + // Prefixes PrefixValue: prefix, PrefixesId: prefixesName.Replace('.', '_'), PrefixesName: prefixesName, - //ContentTypes + // ContentTypes ContentTypesId: contentTypesName.Replace('.', '_'), ContentTypesName: contentTypesName, - //ContentItems + // ContentItems ContentItemsId: contentItemsName.Replace('.', '_'), ContentItemsName: contentItemsName, - //Zones + // Zones ZonesId: zonesName.Replace('.', '_'), ZonesName: zonesName ); diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/Drivers/WidgetsListPartDisplayDriver.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/Drivers/WidgetsListPartDisplayDriver.cs index 80e0b34b1ef..4fc8b47c001 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/Drivers/WidgetsListPartDisplayDriver.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/Drivers/WidgetsListPartDisplayDriver.cs @@ -120,12 +120,13 @@ public override async Task UpdateAsync(WidgetsListPart part, Upd var widgetModel = await contentItemDisplayManager.UpdateEditorAsync(contentItem, context.Updater, context.IsNew, htmlFieldPrefix: prefix); - if (!zonedContentItems.ContainsKey(zone)) + if (!zonedContentItems.TryGetValue(zone, out var value)) { - zonedContentItems.Add(zone, []); + value = ([]); + zonedContentItems.Add(zone, value); } - zonedContentItems[zone].Add(contentItem); + value.Add(contentItem); } part.Widgets = zonedContentItems; diff --git a/src/OrchardCore.Modules/OrchardCore.Widgets/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Widgets/Startup.cs index c6c41b83e50..95e468b50b8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Widgets/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Widgets/Startup.cs @@ -29,7 +29,7 @@ public Startup(IOptions adminOptions) public override void ConfigureServices(IServiceCollection services) { - //Add Widget Card Shapes + // Add Widget Card Shapes services.AddScoped(); // Widgets List Part services.AddContentPart() diff --git a/src/OrchardCore.Modules/OrchardCore.Workflows/Expressions/LiquidWorkflowExpressionEvaluator.cs b/src/OrchardCore.Modules/OrchardCore.Workflows/Expressions/LiquidWorkflowExpressionEvaluator.cs index 6835ff60502..44112b3bedb 100644 --- a/src/OrchardCore.Modules/OrchardCore.Workflows/Expressions/LiquidWorkflowExpressionEvaluator.cs +++ b/src/OrchardCore.Modules/OrchardCore.Workflows/Expressions/LiquidWorkflowExpressionEvaluator.cs @@ -52,12 +52,12 @@ public async Task EvaluateAsync(WorkflowExpression expression, Workflow public static Task ToFluidValue(IDictionary dictionary, string key, TemplateContext context) { - if (!dictionary.ContainsKey(key)) + if (!dictionary.TryGetValue(key, out var value)) { return Task.FromResult(NilValue.Instance); } - return Task.FromResult(FluidValue.Create(dictionary[key], context.Options)); + return Task.FromResult(FluidValue.Create(value, context.Options)); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcReader.cs b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcReader.cs index 56a8001ecf7..9403c0d8b34 100644 --- a/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcReader.cs +++ b/src/OrchardCore.Modules/OrchardCore.XmlRpc/Services/XmlRpcReader.cs @@ -15,7 +15,7 @@ public class XmlRpcReader : IXmlRpcReader /// /// Provides the mapping function based on a type name. /// - private readonly IDictionary> _dispatch; + private readonly Dictionary> _dispatch; /// /// Initializes a new instance of the class. diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs index 873c3ee5f6d..e4af891e4c8 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs @@ -39,7 +39,7 @@ private void EnsureInitialized() } } - private IEnumerable GetModules() + private ConcurrentBag GetModules() { var modules = new ConcurrentBag { diff --git a/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Models/AdminNode.cs b/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Models/AdminNode.cs index 0691854c763..91ed547a9bf 100644 --- a/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Models/AdminNode.cs +++ b/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Models/AdminNode.cs @@ -14,7 +14,7 @@ public AdminNode GetMenuItemById(string id) { var tempStack = new Stack(new AdminNode[] { this }); - while (tempStack.Any()) + while (tempStack.Count > 0) { // Evaluate first node. var item = tempStack.Pop(); @@ -39,7 +39,7 @@ public bool RemoveMenuItem(AdminNode nodeToRemove) { var tempStack = new Stack(new AdminNode[] { this }); - while (tempStack.Any()) + while (tempStack.Count > 0) { // Evaluate first. var item = tempStack.Pop(); @@ -63,7 +63,7 @@ public bool RemoveMenuItem(AdminNode nodeToRemove) public bool InsertMenuItem(AdminNode nodeToInsert, MenuItem destinationNode, int position) { var tempStack = new Stack(new AdminNode[] { this }); - while (tempStack.Any()) + while (tempStack.Count > 0) { // Evaluate first. var node = tempStack.Pop(); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs index 9a8daee4196..ab0d81097b5 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs @@ -345,9 +345,9 @@ public static string Translate(this string subject, char[] from, char[] to) for (var i = 0; i < subject.Length; i++) { var current = subject[i]; - if (map.ContainsKey(current)) + if (map.TryGetValue(current, out var value)) { - result[i] = map[current]; + result[i] = value; } else { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Junction.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Junction.cs index b9881ed76b6..01d79ad4809 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Junction.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Junction.cs @@ -9,7 +9,7 @@ namespace OrchardCore.ContentManagement.GraphQL.Queries.Predicates /// public abstract class Junction : IPredicate { - private readonly IList _predicates = new List(); + private readonly List _predicates = []; /// /// Get the Sql operator to put between multiple s. diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs index b6c641f209e..44d9020bb82 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs @@ -19,8 +19,8 @@ private class DefaultRequiredAttributeParser { private const char RequiredAttributeWildcardSuffix = '*'; - private static readonly IReadOnlyDictionary _cssValueComparisons = - new Dictionary + private static readonly Dictionary _cssValueComparisons = + new() { { '=', RequiredAttributeDescriptor.ValueComparisonMode.FullMatch }, { '^', RequiredAttributeDescriptor.ValueComparisonMode.PrefixMatch }, @@ -88,8 +88,8 @@ public void AddRequiredAttributes(TagMatchingRuleDescriptorBuilder ruleBuilder) } else if (!AtEnd) { - //var diagnostic = RazorDiagnosticFactory.CreateTagHelper_InvalidRequiredAttributeCharacter(Current, _requiredAttributes); - //attributeBuilder.Diagnostics.Add(diagnostic); + // var diagnostic = RazorDiagnosticFactory.CreateTagHelper_InvalidRequiredAttributeCharacter(Current, _requiredAttributes); + // attributeBuilder.Diagnostics.Add(diagnostic); successfulParse = false; return; } @@ -162,16 +162,16 @@ private bool TryParseCssValueComparison(RequiredAttributeDescriptorBuilder build } else if (op != '=') // We're at an incomplete operator (ex: [foo^] { - //var diagnostic = RazorDiagnosticFactory.CreateTagHelper_PartialRequiredAttributeOperator(op, _requiredAttributes); - //builder.Diagnostics.Add(diagnostic); + // var diagnostic = RazorDiagnosticFactory.CreateTagHelper_PartialRequiredAttributeOperator(op, _requiredAttributes); + // builder.Diagnostics.Add(diagnostic); return false; } } else if (!At(']')) { - //var diagnostic = RazorDiagnosticFactory.CreateTagHelper_InvalidRequiredAttributeOperator(Current, _requiredAttributes); - //builder.Diagnostics.Add(diagnostic); + // var diagnostic = RazorDiagnosticFactory.CreateTagHelper_InvalidRequiredAttributeOperator(Current, _requiredAttributes); + // builder.Diagnostics.Add(diagnostic); return false; } @@ -196,8 +196,8 @@ private bool TryParseCssValue(RequiredAttributeDescriptorBuilder builder) valueEnd = _requiredAttributes.IndexOf(quote, _index); if (valueEnd == -1) { - //var diagnostic = RazorDiagnosticFactory.CreateTagHelper_InvalidRequiredAttributeMismatchedQuotes(quote, _requiredAttributes); - //builder.Diagnostics.Add(diagnostic); + // var diagnostic = RazorDiagnosticFactory.CreateTagHelper_InvalidRequiredAttributeMismatchedQuotes(quote, _requiredAttributes); + // builder.Diagnostics.Add(diagnostic); return false; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs index 23d7e48ab44..f34934c6a40 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs @@ -190,7 +190,7 @@ bool IDictionary.TryGetValue(string key, out T value) return pair.Key != null; } - //TBD + // TBD T IDictionary.this[string key] { get diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Html/TheAdminThemeOptions.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Html/TheAdminThemeOptions.cs index 673f0f1234d..fcb362f9be3 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Html/TheAdminThemeOptions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Html/TheAdminThemeOptions.cs @@ -12,7 +12,7 @@ public class TheAdminThemeOptions /// public string LimitedWidthWrapperClasses { get; set; } = "row"; - //GroupWrapperClasses + // GroupWrapperClasses /// /// Space separated CSS classes used to control the width of input elements like numeric, date, etc. /// diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/LocationExpander/ThemeViewLocationExpanderProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement/LocationExpander/ThemeViewLocationExpanderProvider.cs index d4522d3c502..8ea6177fc16 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/LocationExpander/ThemeViewLocationExpanderProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/LocationExpander/ThemeViewLocationExpanderProvider.cs @@ -38,13 +38,11 @@ public void PopulateValues(ViewLocationExpanderContext context) public virtual IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable viewLocations) { - if (!context.Values.ContainsKey("Theme")) + if (!context.Values.TryGetValue("Theme", out var currentThemeId)) { return viewLocations; } - var currentThemeId = context.Values["Theme"]; - var currentThemeAndBaseThemesOrdered = _extensionManager .GetFeatures([currentThemeId]) .Where(f => f.IsTheme()) diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ValidationMessageTagHelper.cs b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ValidationMessageTagHelper.cs index 15a3e72ce6c..0c3d12fe50a 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ValidationMessageTagHelper.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/ValidationMessageTagHelper.cs @@ -51,7 +51,7 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu if (For != null) { - //contextualize IHtmlHelper + // contextualize IHtmlHelper var viewContextAware = _htmlHelper as IViewContextAware; viewContextAware?.Contextualize(ViewContext); diff --git a/src/OrchardCore/OrchardCore.Email.Core/Services/SmtpService.cs b/src/OrchardCore/OrchardCore.Email.Core/Services/SmtpService.cs index d8511e328a0..147da710ab1 100644 --- a/src/OrchardCore/OrchardCore.Email.Core/Services/SmtpService.cs +++ b/src/OrchardCore/OrchardCore.Email.Core/Services/SmtpService.cs @@ -109,7 +109,7 @@ public async Task SendAsync(MailMessage message) return result; } - private MimeMessage FromMailMessage(MailMessage message, IList errors) + private MimeMessage FromMailMessage(MailMessage message, List errors) { var submitterAddress = string.IsNullOrWhiteSpace(message.Sender) ? _options.DefaultSender diff --git a/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs b/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs index 4bcc4edb893..16cf5ce1071 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs @@ -69,7 +69,7 @@ public async Task GetDirectoryInfoAsync(string path) FetchOwner = false }); - return awsDirectory.S3Objects.Any() ? new AwsDirectory(path, _clock.UtcNow) : null; + return awsDirectory.S3Objects.Count > 0 ? new AwsDirectory(path, _clock.UtcNow) : null; } public async IAsyncEnumerable GetDirectoryContentAsync(string path = null, @@ -206,7 +206,7 @@ await _amazonS3Client.GetObjectMetadataAsync(new GetObjectMetadataRequest Prefix = this.Combine(_basePrefix, dstPath) }); - if (listObjects.S3Objects.Any()) + if (listObjects.S3Objects.Count > 0) { throw new FileStoreException($"Cannot copy file '{srcPath}' because a file already exists in the new path '{dstPath}'."); } @@ -261,7 +261,7 @@ public async Task CreateFileFromStreamAsync(string path, Stream inputStr Prefix = this.Combine(_basePrefix, path) }); - if (listObjects.S3Objects.Any()) + if (listObjects.S3Objects.Count > 0) { throw new FileStoreException($"Cannot create file '{path}' because it already exists."); } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs b/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs index 79e53ef2e91..130a6b8c303 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs @@ -24,7 +24,7 @@ public async Task ExecuteAsync(CommandParameters parameters) { var matches = MatchCommands(parameters) ?? []; - if (matches.Count() == 1) + if (matches.Count == 1) { var match = matches.Single(); await match.CommandHandler.ExecuteAsync(match.Context); @@ -33,7 +33,7 @@ public async Task ExecuteAsync(CommandParameters parameters) { var commandMatch = string.Join(" ", parameters.Arguments.ToArray()); var commandList = string.Join(",", GetCommandDescriptors().SelectMany(d => d.Names).ToArray()); - if (matches.Any()) + if (matches.Count > 0) { throw new Exception(S["Multiple commands found matching arguments \"{0}\". Commands available: {1}.", commandMatch, commandList]); diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Security/DefaultPermissionGrantingService.cs b/src/OrchardCore/OrchardCore.Infrastructure/Security/DefaultPermissionGrantingService.cs index 59facde86bc..71073926ef6 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Security/DefaultPermissionGrantingService.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Security/DefaultPermissionGrantingService.cs @@ -30,7 +30,7 @@ public bool IsGranted(PermissionRequirement requirement, IEnumerable clai && grantingNames.Contains(claim.Value)); } - private void GetGrantingNamesInternal(Permission permission, HashSet stack) + private static void GetGrantingNamesInternal(Permission permission, HashSet stack) { // The given name is tested stack.Add(permission.Name); diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs index 06b5d187801..79120b6ec16 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs @@ -119,7 +119,7 @@ private IEnumerable GetAllStrings(CultureInfo culture) } } - private IEnumerable GetAllStringsFromCultureHierarchy(CultureInfo culture) + private List GetAllStringsFromCultureHierarchy(CultureInfo culture) { var currentCulture = culture; var allLocalizedStrings = new List(); diff --git a/src/OrchardCore/OrchardCore.Media.Core/Services/MediaSizeLimitAttribute.cs b/src/OrchardCore/OrchardCore.Media.Core/Services/MediaSizeLimitAttribute.cs index 0c211b18a45..ba1414cb3ef 100644 --- a/src/OrchardCore/OrchardCore.Media.Core/Services/MediaSizeLimitAttribute.cs +++ b/src/OrchardCore/OrchardCore.Media.Core/Services/MediaSizeLimitAttribute.cs @@ -57,7 +57,7 @@ public void OnAuthorization(AuthorizationFilterContext context) var effectiveRequestSizePolicy = context.FindEffectivePolicy(); if (effectiveRequestSizePolicy == null || effectiveRequestSizePolicy == this) { - // Will only be available when running OutOfProcess with Kestrel + // Will only be available when running OutOfProcess with Kestrel. var maxRequestBodySizeFeature = context.HttpContext.Features.Get(); if (maxRequestBodySizeFeature != null && !maxRequestBodySizeFeature.IsReadOnly) diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs index a6834be8940..1748e49f916 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs @@ -162,7 +162,7 @@ public IFileInfo GetFileInfo(string subpath) if (File.Exists(filePath)) { - //Serve the file from the physical file system. + // Serve the file from the physical file system. return new PhysicalFileInfo(new FileInfo(filePath)); } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/StringExtensions.cs b/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/StringExtensions.cs index 1f9229ac73a..524d883aa0a 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/StringExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/StringExtensions.cs @@ -380,9 +380,9 @@ public static string Translate(this string subject, char[] from, char[] to) for (var i = 0; i < subject.Length; i++) { var current = subject[i]; - if (map.ContainsKey(current)) + if (map.TryGetValue(current, out var value)) { - result[i] = map[current]; + result[i] = value; } else { diff --git a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs index 82563943a70..a810d5767cb 100644 --- a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs +++ b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs @@ -216,7 +216,7 @@ private async Task> AuthorizeAsync(IEnumerable items, C { filtered.Add(item); } - else if (!item.Permissions.Any()) + else if (item.Permissions.Count == 0) { filtered.Add(item); } @@ -249,7 +249,7 @@ private async Task> AuthorizeAsync(IEnumerable items, C /// /// Retains only menu items with an Href, or that have child items with an Href. /// - private List Reduce(IEnumerable items) + private static List Reduce(IEnumerable items) { var filtered = items.ToList(); foreach (var item in items) diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs b/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs index 4b3ab598221..37d132dce40 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs @@ -6,7 +6,7 @@ namespace OrchardCore.Notifications.Indexes; -public class NotificationIndex : MapIndex +public partial class NotificationIndex : MapIndex { public string NotificationId { get; set; } @@ -24,7 +24,7 @@ public class NotificationIndex : MapIndex public string Content { get; set; } } -public class NotificationIndexProvider : IndexProvider +public partial class NotificationIndexProvider : IndexProvider { public NotificationIndexProvider() { @@ -66,10 +66,13 @@ public override void Describe(DescribeContext context) }); } - private static readonly Regex _htmlRegex = new("<.*?>", RegexOptions.Compiled); + private static readonly Regex _htmlRegex = GetHtmlBlockRegex(); public static string StripHTML(string html) { return _htmlRegex.Replace(html, string.Empty); } + + [GeneratedRegex("<.*?>", RegexOptions.Compiled)] + private static partial Regex GetHtmlBlockRegex(); } diff --git a/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/ResourceManifest.cs b/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/ResourceManifest.cs index a9d66669513..ac7bc824ea3 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/ResourceManifest.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/ResourceManifest.cs @@ -11,12 +11,13 @@ public virtual ResourceDefinition DefineResource(string resourceType, string res { var definition = new ResourceDefinition(this, resourceType, resourceName); var resources = GetResources(resourceType); - if (!resources.ContainsKey(resourceName)) + if (!resources.TryGetValue(resourceName, out var value)) { - resources[resourceName] = new List(); + value = new List(); + resources[resourceName] = value; } - resources[resourceName].Add(definition); + value.Add(definition); return definition; } diff --git a/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ScriptTagHelper.cs b/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ScriptTagHelper.cs index 2d876de3f50..acedeec426f 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ScriptTagHelper.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement/TagHelpers/ScriptTagHelper.cs @@ -11,6 +11,8 @@ namespace OrchardCore.ResourceManagement.TagHelpers [HtmlTargetElement("script", Attributes = AtAttributeName)] public class ScriptTagHelper : TagHelper { + private static readonly char[] _separator = [',', ' ']; + private const string NameAttributeName = "asp-name"; private const string SrcAttributeName = "asp-src"; private const string AtAttributeName = "at"; @@ -82,12 +84,12 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu if (!string.IsNullOrEmpty(Culture)) { - definition.SetCultures(Culture.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)); + definition.SetCultures(Culture.Split(_separator, StringSplitOptions.RemoveEmptyEntries)); } if (!string.IsNullOrEmpty(DependsOn)) { - definition.SetDependencies(DependsOn.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)); + definition.SetDependencies(DependsOn.Split(_separator, StringSplitOptions.RemoveEmptyEntries)); } if (AppendVersion.HasValue) @@ -185,7 +187,7 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu // This allows additions to the pre registered scripts dependencies. if (!string.IsNullOrEmpty(DependsOn)) { - setting.SetDependencies(DependsOn.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)); + setting.SetDependencies(DependsOn.Split(_separator, StringSplitOptions.RemoveEmptyEntries)); } foreach (var attribute in output.Attributes) @@ -238,12 +240,12 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu if (!string.IsNullOrEmpty(Culture)) { - definition.SetCultures(Culture.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)); + definition.SetCultures(Culture.Split(_separator, StringSplitOptions.RemoveEmptyEntries)); } if (!string.IsNullOrEmpty(DependsOn)) { - definition.SetDependencies(DependsOn.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)); + definition.SetDependencies(DependsOn.Split(_separator, StringSplitOptions.RemoveEmptyEntries)); } if (AppendVersion.HasValue) diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexManager.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexManager.cs index 1349e5d8214..f9ed65c5335 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexManager.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticIndexManager.cs @@ -91,7 +91,7 @@ ILogger logger /// . public async Task CreateIndexAsync(ElasticIndexSettings elasticIndexSettings) { - //Get Index name scoped by ShellName + // Get Index name scoped by ShellName if (await ExistsAsync(elasticIndexSettings.IndexName)) { return true; @@ -411,7 +411,7 @@ public async Task StoreDocumentsAsync(string indexName, IEnumerable 0) { var descriptor = new BulkDescriptor(); diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQuerySource.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQuerySource.cs index 106c37d8285..1c85f70c511 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQuerySource.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticQuerySource.cs @@ -77,7 +77,7 @@ public async Task ExecuteQueryAsync(Query query, IDictionary data) var fileInfo = await _shellsFileStore.GetFileInfoAsync(appsettings); +#pragma warning disable CA1859 // Use concrete types when possible for improved performance IDictionary configData; +#pragma warning restore CA1859 // Use concrete types when possible for improved performance if (fileInfo != null) { using var stream = await _shellsFileStore.GetFileStreamAsync(appsettings); diff --git a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Options/WorkflowOptions.cs b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Options/WorkflowOptions.cs index 6143024cf5d..ce17b9c3c38 100644 --- a/src/OrchardCore/OrchardCore.Workflows.Abstractions/Options/WorkflowOptions.cs +++ b/src/OrchardCore/OrchardCore.Workflows.Abstractions/Options/WorkflowOptions.cs @@ -8,25 +8,25 @@ public class WorkflowOptions { public WorkflowOptions() { - ActivityDictionary = new Dictionary(); + ActivityDictionary = []; } /// /// The set of activities available to workflows. /// Modules can register and unregister activities. /// - private IDictionary ActivityDictionary { get; } + private Dictionary ActivityDictionary { get; } public IEnumerable ActivityTypes => ActivityDictionary.Values.Select(x => x.ActivityType).ToList().AsReadOnly(); public IEnumerable ActivityDisplayDriverTypes => ActivityDictionary.Values.SelectMany(x => x.DriverTypes).ToList().AsReadOnly(); public WorkflowOptions RegisterActivity(Type activityType, Type driverType = null) { - if (ActivityDictionary.ContainsKey(activityType)) + if (ActivityDictionary.TryGetValue(activityType, out var value)) { if (driverType != null) { - ActivityDictionary[activityType].DriverTypes.Add(driverType); + value.DriverTypes.Add(driverType); } } else diff --git a/src/OrchardCore/OrchardCore/Modules/Extensions/ServiceCollectionExtensions.cs b/src/OrchardCore/OrchardCore/Modules/Extensions/ServiceCollectionExtensions.cs index a11496194d8..1bad54deb11 100644 --- a/src/OrchardCore/OrchardCore/Modules/Extensions/ServiceCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore/Modules/Extensions/ServiceCollectionExtensions.cs @@ -442,8 +442,8 @@ private static void AddSameSiteCookieBackwardsCompatibility(OrchardCoreBuilder b services.Configure(options => { options.MinimumSameSitePolicy = SameSiteMode.Unspecified; - options.OnAppendCookie = cookieContext => CheckSameSiteBackwardsCompatiblity(cookieContext.Context, cookieContext.CookieOptions); - options.OnDeleteCookie = cookieContext => CheckSameSiteBackwardsCompatiblity(cookieContext.Context, cookieContext.CookieOptions); + options.OnAppendCookie = cookieContext => CheckSameSiteBackwardsCompatibility(cookieContext.Context, cookieContext.CookieOptions); + options.OnDeleteCookie = cookieContext => CheckSameSiteBackwardsCompatibility(cookieContext.Context, cookieContext.CookieOptions); }); }) .Configure(app => @@ -452,9 +452,9 @@ private static void AddSameSiteCookieBackwardsCompatibility(OrchardCoreBuilder b }); } - private static void CheckSameSiteBackwardsCompatiblity(HttpContext httpContext, CookieOptions options) + private static void CheckSameSiteBackwardsCompatibility(HttpContext httpContext, CookieOptions options) { - var userAgent = httpContext.Request.Headers["User-Agent"].ToString(); + var userAgent = httpContext.Request.Headers.UserAgent.ToString(); if (options.SameSite == SameSiteMode.None) { diff --git a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.cs b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.cs index 8f232631740..25e59bd5123 100644 --- a/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.cs +++ b/test/OrchardCore.Abstractions.Tests/Modules/Manifest/ModuleAttributeTests.cs @@ -644,7 +644,7 @@ public virtual void Csproj_OrchardCoreModules_MSBuild_ItemLists() Assert.Contains(features, _ => _.Id == string.Join(".", baseId, One) && _.Name == _.Id && - _.Category == Two.ToLower() && + _.Category.Equals(Two, StringComparison.CurrentCultureIgnoreCase) && _.InternalPriority == _3 && _.Description == four && _.Dependencies.SequenceEqual(GetValues(five, six, seven)) && diff --git a/test/OrchardCore.Tests.Pages/OrchardCore.Modules.Pages/Module.Pages/Startup.cs b/test/OrchardCore.Tests.Pages/OrchardCore.Modules.Pages/Module.Pages/Startup.cs index 55078e8793e..27d206f28d2 100644 --- a/test/OrchardCore.Tests.Pages/OrchardCore.Modules.Pages/Module.Pages/Startup.cs +++ b/test/OrchardCore.Tests.Pages/OrchardCore.Modules.Pages/Module.Pages/Startup.cs @@ -15,10 +15,10 @@ public override void ConfigureServices(IServiceCollection services) options.Conventions.AddAreaFolderRoute("Module.Pages", "/", ""); // Add a custom page route - //options.Conventions.AddAreaPageRoute("Module.Pages", "/Foo", "Foo"); + // options.Conventions.AddAreaPageRoute("Module.Pages", "/Foo", "Foo"); // This declaration would define an home page - //options.Conventions.AddAreaPageRoute("Module.Pages", "/Foo", ""); + // options.Conventions.AddAreaPageRoute("Module.Pages", "/Foo", ""); }); } } diff --git a/test/OrchardCore.Tests/Apis/GraphQL/ContentItemsFieldTypeTests.cs b/test/OrchardCore.Tests/Apis/GraphQL/ContentItemsFieldTypeTests.cs index cb8f974b256..954d3238df0 100644 --- a/test/OrchardCore.Tests/Apis/GraphQL/ContentItemsFieldTypeTests.cs +++ b/test/OrchardCore.Tests/Apis/GraphQL/ContentItemsFieldTypeTests.cs @@ -367,7 +367,7 @@ public async Task ShouldFilterByCollapsedWhereInputForCollapsedParts() } - private static IResolveFieldContext CreateAnimalFieldContext(IServiceProvider services, string fieldName = null, bool collapsed = false) + private static ResolveFieldContext CreateAnimalFieldContext(IServiceProvider services, string fieldName = null, bool collapsed = false) { IGraphType where; @@ -555,7 +555,7 @@ public IEnumerable GetAliases() public class FakeServiceCollection : IServiceProvider, IDisposable { - private IServiceProvider _inner; + private ServiceProvider _inner; private IServiceCollection _services; public IServiceCollection Services => _services; @@ -570,7 +570,7 @@ public object GetService(Type serviceType) public void Populate(IServiceCollection services) { _services = services; - _services.AddSingleton(this); + _services.AddSingleton(this); } public void Build() diff --git a/test/OrchardCore.Tests/Commands/CommandHandlerTests.cs b/test/OrchardCore.Tests/Commands/CommandHandlerTests.cs index 80c0da1161f..db8a9328b40 100644 --- a/test/OrchardCore.Tests/Commands/CommandHandlerTests.cs +++ b/test/OrchardCore.Tests/Commands/CommandHandlerTests.cs @@ -5,7 +5,7 @@ namespace OrchardCore.Tests.Commands { public class CommandsTests { - private readonly ICommandHandler _handler; + private readonly StubCommandHandler _handler; public CommandsTests() { diff --git a/test/OrchardCore.Tests/DisplayManagement/Decriptors/DefaultShapeTableManagerTests.cs b/test/OrchardCore.Tests/DisplayManagement/Decriptors/DefaultShapeTableManagerTests.cs index 5d241ba1d6e..a0f09291c87 100644 --- a/test/OrchardCore.Tests/DisplayManagement/Decriptors/DefaultShapeTableManagerTests.cs +++ b/test/OrchardCore.Tests/DisplayManagement/Decriptors/DefaultShapeTableManagerTests.cs @@ -22,7 +22,7 @@ public TestModuleExtensionInfo(string name) var dic1 = new Dictionary() { {"name", name}, - {"desciption", name}, + {"description", name}, {"type", "module"}, }; @@ -56,7 +56,7 @@ public TestThemeExtensionInfo(string name) var dic1 = new Dictionary() { {"name", name}, - {"desciption", name}, + {"description", name}, {"type", "theme"}, }; @@ -82,7 +82,7 @@ public TestThemeExtensionInfo(string name, IFeatureInfo baseTheme) var dic1 = new Dictionary() { {"name", name}, - {"desciption", name}, + {"description", name}, {"type", "theme"}, {"basetheme", baseTheme.Id } }; @@ -135,13 +135,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"} }, + { 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(); serviceCollection.AddScoped(sp => (TestShapeProvider)sp.GetService()); @@ -152,7 +154,7 @@ public DefaultShapeTableManagerTests() typeFeatureProvider.TryAdd(typeof(TestShapeProvider), TestFeature()); } - private static IFeatureInfo TestFeature() + private static FeatureInfo TestFeature() { return new FeatureInfo("Testing", new TestModuleExtensionInfo("Testing")); } diff --git a/test/OrchardCore.Tests/Email/EmailTests.cs b/test/OrchardCore.Tests/Email/EmailTests.cs index 1440ed8e4b1..d54cb406982 100644 --- a/test/OrchardCore.Tests/Email/EmailTests.cs +++ b/test/OrchardCore.Tests/Email/EmailTests.cs @@ -263,7 +263,7 @@ private static async Task SendEmailAsync(MailMessage message, string def return content; } - private static ISmtpService CreateSmtpService(SmtpSettings settings) + private static SmtpService CreateSmtpService(SmtpSettings settings) { var options = new Mock>(); options.Setup(o => o.Value).Returns(settings); diff --git a/test/OrchardCore.Tests/Extensions/ExtensionManagerTests.cs b/test/OrchardCore.Tests/Extensions/ExtensionManagerTests.cs index 4befc6aee99..4c29bc0f89d 100644 --- a/test/OrchardCore.Tests/Extensions/ExtensionManagerTests.cs +++ b/test/OrchardCore.Tests/Extensions/ExtensionManagerTests.cs @@ -24,9 +24,9 @@ private static readonly IApplicationContext _applicationContext private static readonly IFeaturesProvider _themeFeatureProvider = new FeaturesProvider(new[] { new ThemeFeatureBuilderEvents() }); - private readonly IExtensionManager _moduleScopedExtensionManager; - private readonly IExtensionManager _themeScopedExtensionManager; - private readonly IExtensionManager _moduleThemeScopedExtensionManager; + private readonly ExtensionManager _moduleScopedExtensionManager; + private readonly ExtensionManager _themeScopedExtensionManager; + private readonly ExtensionManager _moduleThemeScopedExtensionManager; public ExtensionManagerTests() { diff --git a/test/OrchardCore.Tests/Localization/DefaultPluralRuleProviderTests.cs b/test/OrchardCore.Tests/Localization/DefaultPluralRuleProviderTests.cs index 44cd40976af..f180a60e594 100644 --- a/test/OrchardCore.Tests/Localization/DefaultPluralRuleProviderTests.cs +++ b/test/OrchardCore.Tests/Localization/DefaultPluralRuleProviderTests.cs @@ -17,7 +17,7 @@ public void TryGetRuleShouldReturnRuleForTopCulture(string culture, string expec var expectedCulture = CultureInfo.GetCultureInfo(expected); var testCulture = CultureInfo.GetCultureInfo(culture); - IPluralRuleProvider pluralProvider = new DefaultPluralRuleProvider(); + var pluralProvider = new DefaultPluralRuleProvider(); pluralProvider.TryGetRule(expectedCulture, out var expectedPlural); pluralProvider.TryGetRule(testCulture, out var testPlural);