From db1607557aca0395b65e2f281801f6e9524cef9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jean-Thierry=20K=C3=A9chichian?= Date: Wed, 19 Jul 2023 04:11:53 +0200 Subject: [PATCH] Fixes Analyzer Rules (Core Projects) (#13964) --- .../Indexing/BagPartIndexHandler.cs | 7 +- .../Indexing/FlowPartIndexHandler.cs | 7 +- .../Caching/ISignal.cs | 2 +- .../Utility/DependencyOrderingUtility.cs | 10 +-- .../Modules/Application.cs | 5 +- .../OrchardCore.Abstractions/Modules/Asset.cs | 10 ++- .../FileProviders/FileInfoExtensions.cs | 15 ++-- .../Modules/FileProviders/NormalizedPaths.cs | 8 +- .../Modules/Manifest/FeatureAttribute.cs | 26 +++--- .../Modules/Manifest/ModuleAttribute.cs | 26 +++--- .../Modules/ModularApplicationContext.cs | 13 ++- .../Modules/Module.cs | 6 +- .../Modules/ModuleEmbeddedFileProvider.cs | 25 ++---- .../ModuleEmbeddedStaticFileProvider.cs | 19 ++-- .../ModuleProjectStaticFileProvider.cs | 17 ++-- .../Modules/Services/ClockExtension.cs | 38 +++----- .../Pooling/ZStringWriter.cs | 10 ++- .../Routing/FormValueRequiredAttribute.cs | 5 +- .../Routing/FormValueRequiredMatcherPolicy.cs | 5 +- .../Routing/PathStringExtensions.cs | 8 +- .../Internal/UpdatableDataProvider.cs | 6 +- .../Shell/Configuration/ShellConfiguration.cs | 4 +- .../Shell/Models/FeatureProfile.cs | 2 +- .../Models/FeatureProfilesRuleOptions.cs | 2 +- .../Shell/Scope/ShellScope.cs | 2 +- .../Services/IAdminNodeProviderFactory.cs | 4 +- .../Extensions/PermissionsExtensions.cs | 2 +- .../ResolveFieldContextExtensions.cs | 4 +- .../Queries/WhereInputObjectGraphType.cs | 24 ++--- .../ContentPartBuilder.cs | 7 +- .../ContentResource.cs | 2 +- .../ContentTypeCreateResourceBuilder.cs | 11 ++- .../ContentTypeQueryResourceBuilder.cs | 9 +- .../Extensions/HttpContentExtensions.cs | 39 ++++---- .../Extensions/HttpRequestExtensions.cs | 26 +++--- .../Extensions/StringExtensions.cs | 7 +- .../OrchardGraphQLClient.cs | 7 +- .../AuditTrailPermissions.cs | 4 +- .../Models/AuditTrailAdminListOption.cs | 4 +- .../Models/AuditTrailCategoryDescriptor.cs | 21 +++-- .../AuditTrailCategoryDescriptorBuilder.cs | 5 +- .../Models/AuditTrailEventDescriptor.cs | 16 ++-- .../Indexes/AutoroutePartIndex.cs | 2 +- .../Model/AutoroutePart.cs | 3 +- .../Services/AutorouteEntries.cs | 2 +- .../Services/AutorouteHandleProvider.cs | 7 +- ...tentLocalizationOrchardHelperExtensions.cs | 2 + .../Records/LocalizedContentItemIndex.cs | 4 +- .../ContentElement.cs | 2 +- .../ContentExtensions.cs | 13 +-- .../ContentFieldOption.cs | 2 +- .../ContentItemConverter.cs | 37 ++++---- .../ContentPartOption.cs | 2 +- .../Handlers/ContentValidateResult.cs | 2 +- .../Parts/ValidateContentPartContext.cs | 4 +- .../Builders/ContentBuilderSettings.cs | 11 ++- .../Builders/ContentTypeDefinitionBuilder.cs | 13 ++- .../ContentTypePartDefinitionBuilder.cs | 2 +- .../Metadata/Models/ContentDefinition.cs | 15 ++-- .../Utilities/StringExtensions.cs | 71 ++++++++------- .../ContentDisplay/ContentDisplayOptions.cs | 4 +- .../ContentFieldDisplayOption.cs | 2 +- .../ContentPartDisplayOption.cs | 2 +- .../ContentItemDisplayManager.cs | 24 ++--- .../ContentPlacementNodeFilterProviders.cs | 8 +- .../Razor/OrchardRazorHelperExtensions.cs | 34 +++---- .../Permissions.cs | 27 +++--- .../Queries/ContentItemQuery.cs | 2 +- .../Queries/ContentItemsFieldType.cs | 90 +++++++++---------- .../Queries/ContentTypeQuery.cs | 2 +- .../Queries/IndexPropertyProvider.cs | 4 +- .../Queries/Types/ContentItemType.cs | 2 +- .../Types/DynamicContentTypeBuilder.cs | 2 +- .../ContentFieldFactory.cs | 4 +- .../ContentPartFactory.cs | 4 +- .../DefaultContentManager.cs | 34 ++++--- .../DefaultContentManagerSession.cs | 4 +- .../Handlers/ContentsHandler.cs | 1 - .../Records/ContentItemIndex.cs | 8 +- .../ContentTypePermissionsHelper.cs | 67 +++++++------- .../ContentLinkTagHelper.cs | 8 +- .../Documents/DocumentStore.cs | 6 +- .../Migration/DataMigrationManager.cs | 9 +- .../Options/SqliteOptionsConfiguration.cs | 4 +- .../PoolingJsonContentSerializer.cs | 2 +- .../Removing/ShellDbTablesInfo.cs | 1 + .../Removing/ShellDbTablesRemovingHandler.cs | 2 +- .../Documents/FileDocumentStore.cs | 2 +- .../DeploymentPlanResult.cs | 23 ++--- .../IDeploymentStepFactory.cs | 4 +- .../IFileBuilder.cs | 6 +- .../CommonPermissions.cs | 6 +- .../Services/TemporaryFileBuilder.cs | 8 +- .../Cache/CacheDependencyTag.cs | 2 +- .../Cache/CacheExpiresAfterTag.cs | 2 +- .../Cache/CacheExpiresOnTag.cs | 5 +- .../Cache/CacheExpiresSlidingTag.cs | 2 +- .../Cache/CacheTag.cs | 6 +- .../Filters/LiquidViewFilters.cs | 2 +- .../Filters/ResourceUrlFilter.cs | 2 +- .../LiquidViewTemplate.cs | 16 ++-- .../LiquidViewsFeatureProvider.cs | 6 +- .../ModuleProjectLiquidFileProvider.cs | 7 +- .../TagHelpers/LiquidTagHelperActivator.cs | 25 +++--- .../TagHelpers/LiquidTagHelperFactory.cs | 6 +- .../TagHelpers/LiquidTagHelperMatching.cs | 3 +- .../TagHelpers/RequiredAttributeParser.cs | 49 +++++----- .../Tags/AddAlternatesTag.cs | 2 +- .../Tags/AddAttributesTag.cs | 2 +- .../Tags/AddClassesTag.cs | 2 +- .../Tags/AddWrappersTag.cs | 2 +- .../Tags/AnchorTag.cs | 5 +- .../Tags/ClearAlternatesTag.cs | 2 +- .../Tags/ClearAttributesTag.cs | 2 +- .../Tags/ClearClassesTag.cs | 2 +- .../Tags/ClearWrappersTag.cs | 2 +- .../Tags/FluidTagHelper.cs | 4 +- .../Tags/HttpContextAddItemTag.cs | 2 +- .../Tags/HttpContextRemoveItemTag.cs | 5 +- .../Tags/LayoutTag.cs | 2 +- .../Tags/ShapeAddPropertyTag.cs | 2 +- .../Tags/ShapeCacheTag.cs | 8 +- .../Tags/ShapeDisplayTypeTag.cs | 2 +- .../Tags/ShapePagerTag.cs | 4 +- .../Tags/ShapePositionTag.cs | 2 +- .../Tags/ShapeRemoveItemTag.cs | 2 +- .../Tags/ShapeRemovePropertyTag.cs | 4 +- .../Tags/ShapeTabTag.cs | 2 +- .../Tags/ShapeTag.cs | 10 ++- .../Tags/ShapeTypeTag.cs | 2 +- .../Arguments.cs | 12 +-- .../BaseDisplayManager.cs | 2 +- .../Descriptors/DefaultShapeTableManager.cs | 11 ++- .../Descriptors/PlacementInfo.cs | 42 ++++----- .../Descriptors/PlacementInfoExtensions.cs | 13 ++- .../Descriptors/ShapeAlterationBuilder.cs | 9 +- .../ShapeAttributeBindingStrategy.cs | 4 +- .../PathPlacementNodeFilterProvider.cs | 11 +-- .../ShapePlacementParsingStrategy.cs | 29 +++--- .../BasicShapeTemplateHarvester.cs | 17 ++-- .../ShapeTemplateBindingStrategy.cs | 3 +- .../Extensions/RazorHelperExtensions.cs | 6 +- .../Handlers/DisplayDriverBase.cs | 10 +-- .../IDisplayManager.cs | 4 +- .../OrchardCore.DisplayManagement/IShape.cs | 13 +-- .../IShapeFactory.cs | 10 +-- .../Implementation/DefaultHtmlDisplay.cs | 49 +++++----- .../Implementation/DefaultShapeFactory.cs | 22 +++-- .../Layout/LayoutAccessor.cs | 11 ++- .../ModelBinding/LocalModelBinderAccessor.cs | 6 +- .../Notify/NotifyEntryConverter.cs | 6 +- .../Notify/NotifyFilter.cs | 4 +- .../ObjectPool.cs | 17 ++-- .../PositionWrapper.cs | 3 +- .../Razor/RazorPage.cs | 81 +++-------------- .../Razor/RazorShapeTemplateViewEngine.cs | 8 +- .../RazorPages/Page.cs | 70 ++------------- .../ShapeAttribute.cs | 1 + .../Shapes/AlternatesCollection.cs | 7 +- .../Shapes/Composite.cs | 32 ++++--- .../Shapes/CoreShapes.cs | 10 ++- .../Shapes/DateTimeShapes.cs | 57 +++++++++--- .../Shapes/GroupShapes.cs | 2 + .../Shapes/PageTitleShapes.cs | 13 +-- .../Shapes/Shape.cs | 21 ++--- .../Shapes/ShapeDebugView.cs | 8 +- .../Shapes/ShapeSerializer.cs | 14 +-- .../TagHelpers/BaseShapeTagHelper.cs | 29 +++--- .../Theming/ThemingViewsFeatureProvider.cs | 2 +- .../Title/PageTitleBuilder.cs | 7 +- .../Views/ShapeResult.cs | 43 ++++----- .../Views/ShapeViewModel.cs | 8 +- .../Zones/ZoneHoldingBehavior.cs | 20 ++--- .../Zones/ZoneShapes.cs | 34 ++++--- .../SmtpResult.cs | 2 +- .../Services/SmtpService.cs | 45 +++++----- .../IFileStore.cs | 4 +- .../AwsFileStorage.cs | 4 +- .../BlobDirectory.cs | 5 +- .../BlobFile.cs | 5 +- .../BlobFileStore.cs | 25 +++--- .../FileSystemStore.cs | 4 +- .../FileSystemStoreEntry.cs | 2 +- .../ContentFieldIndexHandler.cs | 5 +- .../ContentPartIndexHandler.cs | 7 +- .../Cache/CacheContext.cs | 20 +---- .../Commands/DefaultCommandHandler.cs | 40 ++++----- .../Commands/Parameters/ICommandParser.cs | 6 +- .../Files/PathExtensions.cs | 3 +- .../Security/SecurityHeaderNames.cs | 8 +- .../Security/StandardPermissions.cs | 2 +- .../FeaturesCacheContextProvider.cs | 6 +- .../QueryCacheContextProvider.cs | 4 +- .../Cache/CacheScopeManager.cs | 8 +- .../Commands/Builtin/HelpCommand.cs | 6 +- .../CommandHandlerDescriptorBuilder.cs | 12 +-- .../Commands/DefaultCommandManager.cs | 19 ++-- .../Parameters/CommandParametersParser.cs | 10 +-- .../Documents/DefaultDocumentSerializer.cs | 12 +-- .../Documents/Options/DocumentOptionsSetup.cs | 2 +- .../Entities/DefaultIdGenerator.cs | 2 +- .../Entities/Scripting/IdGeneratorMethod.cs | 9 +- .../Html/HtmlSanitizerRazorExtensions.cs | 2 + .../Html/HtmlSanitizerService.cs | 7 +- .../Scripting/CommonGeneratorMethods.cs | 37 ++++---- .../Scripting/DefaultScriptingManager.cs | 5 +- .../Scripting/Files/FilesScriptEngine.cs | 26 ++---- .../DatabaseShellConfigurationSources.cs | 12 ++- .../DatabaseShellsSettingsSources.cs | 9 +- .../LiquidFilterDelegateResolver.cs | 7 +- .../CultureDictionaryRecordKey.cs | 6 +- .../LanguageDirection.cs | 4 +- .../DataAnnotationsDefaultErrorMessages.cs | 7 +- .../LocalizationManager.cs | 6 +- .../PoFilesTranslationsProvider.cs | 10 +-- .../PortableObject/PoParser.cs | 53 ++++++----- .../PortableObjectHtmlLocalizer.cs | 2 +- .../PortableObjectHtmlLocalizerFactory.cs | 32 ++----- .../PortableObjectStringLocalizer.cs | 32 +++---- .../PortableObjectStringLocalizerFactory.cs | 6 +- .../TenantLayoutRenderer.cs | 9 +- .../ApplicationBuilderExtensions.cs | 2 +- .../WebHostBuilderExtensions.cs | 2 +- .../Indexing/MediaFileIndexingOptions.cs | 3 +- .../DefaultMediaFileStore.cs | 18 ++-- .../DefaultMediaFileStoreCacheFileProvider.cs | 19 ++-- .../ApplicationViewFileProvider.cs | 11 +-- .../ComponentViewLocationExpanderProvider.cs | 16 ++-- .../CompositeViewLocationExpanderProvider.cs | 2 +- .../SharedViewLocationExpanderProvider.cs | 16 ++-- .../ModuleProjectRazorFileProvider.cs | 37 ++++---- .../RazorCompilationFileProviderAccessor.cs | 5 +- .../PageConventionCollectionExtensions.cs | 2 +- .../SharedViewCompilerProvider.cs | 2 +- .../ShellFeatureApplicationPart.cs | 2 +- .../ShellFileVersionProvider.cs | 26 +++--- .../ShellViewFeatureProvider.cs | 9 +- .../Utilities/ControllerTypeExtensions.cs | 2 +- .../Utilities/StringExtensions.cs | 84 +++++++++-------- .../NavigationManager.cs | 3 +- .../Indexes/NotificationIndex.cs | 4 +- .../Services/EmailNotificationProvider.cs | 2 +- .../Services/Managers/OpenIdScopeManager.cs | 2 +- .../Services/Managers/OpenIdTokenManager.cs | 2 +- .../YesSql/Stores/OpenIdApplicationStore.cs | 16 ++-- .../YesSql/Stores/OpenIdAuthorizationStore.cs | 37 ++++---- .../YesSql/Stores/OpenIdScopeStore.cs | 14 +-- .../YesSql/Stores/OpenIdTokenStore.cs | 49 +++++----- .../ActionFilters/Detection/IDetectRobots.cs | 8 +- .../Detection/IpAddressRobotDetector.cs | 2 +- .../ActionFilters/ReCaptchaMode.cs | 4 +- .../Configuration/ReCaptchaSettings.cs | 6 +- .../Services/ReCaptchaClient.cs | 12 +-- .../Services/ReCaptchaService.cs | 18 ++-- .../TagHelpers/ReCaptchaTagHelper.cs | 23 +++-- .../ConfigurationMethodProvider.cs | 2 +- .../ParametersMethodProvider.cs | 2 +- .../Services/RecipeExecutor.cs | 19 ++-- .../Services/RecipeReader.cs | 25 +++--- .../VariablesMethodProvider.cs | 6 +- .../LinkEntry.cs | 5 +- .../MetaEntry.cs | 2 +- .../RequireSettings.cs | 12 +-- .../ResourceDefinition.cs | 28 +++--- .../ResourceManifest.cs | 2 +- .../Razor/ResourceCdnHelperExtensions.cs | 4 +- .../ResourceDictionary.cs | 2 +- .../ResourceManager.cs | 77 ++++++---------- .../TagHelpers/LinkTagHelper.cs | 10 +-- .../TagHelpers/StyleTagHelper.cs | 6 +- .../CommonPermissions.cs | 20 ++--- .../ConditionEvaluator.cs | 4 +- .../ConditionOperatorOptions.cs | 2 +- .../ConditionOptions.cs | 2 +- .../IConditionFactory.cs | 6 +- .../IConditionOperatorFactory.cs | 4 +- .../IRuleMigrator.cs | 2 +- .../ElasticIndexDeploymentSource.cs | 9 +- .../ElasticIndexRebuildDeploymentSource.cs | 16 ++-- .../ElasticIndexResetDeploymentSource.cs | 15 ++-- .../ElasticsearchConstants.cs | 4 +- .../Handlers/ElasticIndexingContentHandler.cs | 5 +- .../Models/ElasticSettings.cs | 2 +- .../Recipes/ElasticSettingsStep.cs | 7 +- .../ElasticIndexInitializerService.cs | 2 +- .../Services/ElasticIndexManager.cs | 40 ++++----- .../Services/ElasticIndexSettingsService.cs | 4 + .../Services/ElasticIndexingService.cs | 2 +- .../ElasticContentPickerShapeProvider.cs | 3 +- .../LuceneQueryService.cs | 8 +- .../Filters/GeoDistanceFilterProvider.cs | 6 +- .../Filters/MatchFilterProvider.cs | 1 - .../QueryProviders/PrefixQueryProvider.cs | 4 +- ...teSettingsPropertyDeploymentStepFactory.cs | 4 +- .../OrchardCore.Setup.Core/SetupService.cs | 2 +- .../BlobShellConfigurationSources.cs | 42 ++++----- .../BlobShellsConfigurationSources.cs | 6 +- .../BlobShellsSettingsSources.cs | 42 ++++----- .../BlobShellsOrchardCoreBuilderExtensions.cs | 10 +-- .../ShortcodeOptions.cs | 4 +- .../Models/ContentTypesSitemapSource.cs | 4 +- .../Models/CustomPathSitemapSource.cs | 2 +- .../Services/ISitemapSourceFactory.cs | 4 +- .../SitemapsRazorPagesOptions.cs | 2 +- .../Events/PasswordRecoveryContext.cs | 2 +- .../Authentication/CacheTicketStore.cs | 4 +- .../Razor/UserRazorHelperExtensions.cs | 2 + .../Services/UserService.cs | 40 ++++----- .../Services/UserStore.cs | 1 + .../Activities/Activity.cs | 22 ++--- .../Activities/ActivityExecutionResult.cs | 4 +- .../Activities/IActivity.cs | 6 +- .../Display/ActivityDisplayDriver.cs | 12 +-- .../Helpers/DictionaryExtensions.cs | 2 +- .../Models/WorkflowExecutionContext.cs | 2 +- .../Models/XRpcStruct.cs | 8 +- src/OrchardCore/OrchardCore/Caching/Signal.cs | 2 +- .../Extensions/ExtensionManager.cs | 9 +- .../Features/TypeFeatureProvider.cs | 2 +- .../OrchardCore/Localization/BclCalendars.cs | 39 ++++---- .../DefaultLocalizationService.cs | 8 +- .../Localization/NullHtmlLocalizerFactory.cs | 2 +- .../NullStringLocalizerFactory.cs | 2 +- .../OrchardCore/Locking/LocalLock.cs | 4 +- .../Modules/ModularTenantRouterMiddleware.cs | 2 +- .../OrchardCore/Modules/Services/Clock.cs | 4 +- .../Modules/Services/LocalClock.cs | 12 +-- .../Extensions/ServiceProviderExtensions.cs | 24 +++-- .../Builders/FeatureAwareServiceCollection.cs | 2 +- .../Shell/Builders/ShellContainerFactory.cs | 5 +- .../ShellConfigurationSources.cs | 20 ++--- .../Configuration/ShellsSettingsSources.cs | 34 +++---- .../AllFeaturesShellDescriptorManager.cs | 9 +- ...onfiguredFeaturesShellDescriptorManager.cs | 3 +- .../Shell/Distributed/DistributedContext.cs | 2 +- .../DistributedShellHostedService.cs | 10 +-- .../FeatureProfilesValidationProvider.cs | 2 +- .../Shell/Removing/ShellRemovalManager.cs | 2 +- .../Removing/ShellSettingsRemovingHandler.cs | 2 +- .../ShellSiteFolderRemovingHandler.cs | 2 +- .../Removing/ShellWebRootRemovingHandler.cs | 2 +- .../OrchardCore/Shell/ShellHost.cs | 2 +- .../OrchardCore/Shell/ShellSettingsManager.cs | 4 +- 343 files changed, 1804 insertions(+), 2069 deletions(-) diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/BagPartIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/BagPartIndexHandler.cs index 962afc4ee3d..5a007880ee8 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/BagPartIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/BagPartIndexHandler.cs @@ -33,8 +33,11 @@ public override async Task BuildIndexAsync(BagPart bagPart, BuildPartIndexContex { foreach (var contentItem in bagPart.ContentItems) { - var keys = new List(); - keys.Add(contentItem.ContentType); + var keys = new List + { + contentItem.ContentType, + }; + foreach (var key in context.Keys) { keys.Add($"{key}.{contentItem.ContentType}"); diff --git a/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/FlowPartIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/FlowPartIndexHandler.cs index 8acb2519d55..3e8c1a502a4 100644 --- a/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/FlowPartIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Flows/Indexing/FlowPartIndexHandler.cs @@ -33,8 +33,11 @@ public override async Task BuildIndexAsync(FlowPart FlowPart, BuildPartIndexCont { foreach (var contentItem in FlowPart.Widgets) { - var keys = new List(); - keys.Add(contentItem.ContentType); + var keys = new List + { + contentItem.ContentType, + }; + foreach (var key in context.Keys) { keys.Add($"{key}.{contentItem.ContentType}"); diff --git a/src/OrchardCore/OrchardCore.Abstractions/Caching/ISignal.cs b/src/OrchardCore/OrchardCore.Abstractions/Caching/ISignal.cs index 01d9ddede34..38e675567bb 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Caching/ISignal.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Caching/ISignal.cs @@ -16,7 +16,7 @@ public static class SignalExtensions /// /// Adds a Signal (if not already present) to be sent at the end of the shell scope. /// - public static void DeferredSignalToken(this ISignal signal, string key) + public static void DeferredSignalToken(this ISignal _, string key) { ShellScope.AddDeferredSignal(key); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Extensions/Utility/DependencyOrderingUtility.cs b/src/OrchardCore/OrchardCore.Abstractions/Extensions/Utility/DependencyOrderingUtility.cs index 3105e6495fa..09200a7b256 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Extensions/Utility/DependencyOrderingUtility.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Extensions/Utility/DependencyOrderingUtility.cs @@ -28,7 +28,7 @@ public static IEnumerable OrderByDependenciesAndPriorities(this IEnumerabl Add(node, result, nodes, hasDependency); } - for (int index = 1; index < result.Count; index++) + for (var index = 1; index < result.Count; index++) { MoveUp(result, index, LowestIndex(result, index, hasDependency, getPriority)); } @@ -55,8 +55,8 @@ private static int LowestIndex(List list, int index, Func hasD { double priority = getPriority(list[index]); - int lowestIndex = index; - for (int i = index - 1; i >= 0; i--) + var lowestIndex = index; + for (var i = index - 1; i >= 0; i--) { if (hasDependency(list[index], list[i])) { @@ -77,12 +77,12 @@ private static void MoveUp(List list, int index, int lowerIndex) { if (index < lowerIndex) { - throw new ArgumentException("lowerIndex"); + throw new ArgumentException("Should be higher or equal to 'lowerIndex'.", nameof(index)); } if (index != lowerIndex) { - T temp = list[index]; + var temp = list[index]; for (; index > lowerIndex; index--) { diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Application.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Application.cs index 6d3f6237f65..88417c5d85c 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Application.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Application.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -15,7 +16,7 @@ public class Application public const string ModuleName = "Application Main Feature"; public const string ModuleDescription = "Provides components defined at the application level."; - public static readonly string ModulePriority = int.MinValue.ToString(); + public static readonly string ModulePriority = Int32.MinValue.ToString(); public const string ModuleCategory = "Application"; public const string DefaultFeatureId = "Application.Default"; @@ -48,7 +49,7 @@ public Module GetModule(string name) { if (!_modulesByName.TryGetValue(name, out var module)) { - return new Module(string.Empty); + return new Module(String.Empty); } return module; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Asset.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Asset.cs index 849d55a957f..a04e59c43bc 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Asset.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Asset.cs @@ -1,3 +1,5 @@ +using System; + namespace OrchardCore.Modules { public class Asset @@ -9,13 +11,13 @@ public Asset(string asset) if (index == -1) { - ModuleAssetPath = string.Empty; - ProjectAssetPath = string.Empty; + ModuleAssetPath = String.Empty; + ProjectAssetPath = String.Empty; } else { - ModuleAssetPath = asset.Substring(0, index); - ProjectAssetPath = asset.Substring(index + 1); + ModuleAssetPath = asset[..index]; + ProjectAssetPath = asset[(index + 1)..]; } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/FileInfoExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/FileInfoExtensions.cs index fa8ab4c9df0..05495079278 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/FileInfoExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/FileInfoExtensions.cs @@ -12,16 +12,13 @@ public static IEnumerable ReadAllLines(this IFileInfo fileInfo) if (fileInfo?.Exists ?? false) { - using (var reader = fileInfo.CreateReadStream()) + using var reader = fileInfo.CreateReadStream(); + using var sr = new StreamReader(reader); + + string line; + while ((line = sr.ReadLine()) != null) { - using (var sr = new StreamReader(reader)) - { - string line; - while ((line = sr.ReadLine()) != null) - { - lines.Add(line); - } - } + lines.Add(line); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/NormalizedPaths.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/NormalizedPaths.cs index 85d5bbcee14..61aea12344b 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/NormalizedPaths.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/FileProviders/NormalizedPaths.cs @@ -17,15 +17,15 @@ public static class NormalizedPaths var folders = new HashSet(StringComparer.Ordinal); // Ensure a trailing slash. - if (folder[folder.Length - 1] != '/') + if (folder[^1] != '/') { - folder = folder + '/'; + folder += '/'; } foreach (var path in normalizedPaths.Where(a => a.StartsWith(folder, StringComparison.Ordinal))) { // Resolve the subpath relative to the folder. - var subPath = path.Substring(folder.Length); + var subPath = path[folder.Length..]; var index = subPath.IndexOf('/'); // If no more slash. @@ -37,7 +37,7 @@ public static class NormalizedPaths else { // Otherwise add the 1st subfolder path. - folders.Add(subPath.Substring(0, index)); + folders.Add(subPath[..index]); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/FeatureAttribute.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/FeatureAttribute.cs index b84c7c0091c..4bb00e90635 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/FeatureAttribute.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/FeatureAttribute.cs @@ -6,8 +6,6 @@ namespace OrchardCore.Modules.Manifest { using static StringSplitOptions; -#pragma warning disable IDE0049 // Use framework type - // #pragma warning restore IDE0049 /// /// Defines a Feature in a Module, can be used multiple times. /// If at least one Feature is defined, the Module default feature is ignored. @@ -69,7 +67,7 @@ public FeatureAttribute() /// Whether considered default tenant only. /// Whether feature is always enabled. /// Whether feature is enabled by dependency only. - /// Supported types are and only. + /// Supported types are and only. public FeatureAttribute( string id , string description @@ -101,11 +99,11 @@ string id /// Zero or more delimited feature dependencies, /// corresponding to each of the feature properties. /// Whether considered default tenant only. - /// Supported types are and only. + /// Supported types are and only. /// Whether feature is always enabled. - /// Supported types are and only. + /// Supported types are and only. /// Whether feature is enabled by dependency only. - /// Supported types are and only. + /// Supported types are and only. public FeatureAttribute( string id , string name @@ -140,11 +138,11 @@ string id /// Zero or more delimited feature dependencies, /// corresponding to each of the feature properties. /// Whether considered default tenant only. - /// Supported types are and only. + /// Supported types are and only. /// Whether feature is always enabled. - /// Supported types are and only. + /// Supported types are and only. /// Whether feature is enabled by dependency only. - /// Supported types are and only. + /// Supported types are and only. public FeatureAttribute( string id , string name @@ -203,12 +201,12 @@ public virtual string Id private string _name; /// - /// Returns the as is, or null when that + /// Returns the as is, or null when that /// or . /// /// The string value to consider. /// The value as is, or Null when either that or Empty. - /// + /// internal static string StringOrNull(string s) => String.IsNullOrEmpty(s) ? null : s; /// @@ -267,7 +265,7 @@ internal virtual string Describe(params FeatureAttribute[] additionalFeatures) /// perspective. Also common are comma (',') and space (' ') /// delimiters. /// - /// + /// internal protected static char[] ListDelims { get; } = GetValues(';', ',', ' ').ToArray(); /// @@ -306,9 +304,9 @@ public virtual string[] Dependencies /// /// Gets the , parsed and ready to go for Internal use. May yield - /// null when failing to . + /// null when failing to . /// - internal virtual int? InternalPriority => int.TryParse(Priority, out var result) ? result : null; + internal virtual int? InternalPriority => Int32.TryParse(Priority, out var result) ? result : null; /// /// Prioritizes the Features starting with This one, concatenating diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleAttribute.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleAttribute.cs index d9f1d16e100..4f68a9b8143 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleAttribute.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Manifest/ModuleAttribute.cs @@ -52,14 +52,14 @@ public ModuleAttribute() : base() /// properties. /// Tags associated with the Module. /// Whether considered default tenant only. - /// Supported types are and only. + /// Supported types are and only. /// Whether feature is always enabled. - /// Supported types are and only. + /// Supported types are and only. /// Semantic Versioning /// At least expected herein to differentiate with /// parameterless ctor. /// Whether feature is enabled by dependency only. - /// Supported types are and only. + /// Supported types are and only. public ModuleAttribute( string id , string description @@ -105,14 +105,14 @@ string id /// properties. /// Tags associated with the Module. /// Whether considered default tenant only. - /// Supported types are and only. + /// Supported types are and only. /// Whether feature is always enabled. - /// Supported types are and only. + /// Supported types are and only. /// Semantic Versioning /// At least expected herein to differentiate with /// parameterless ctor. /// Whether feature is enabled by dependency only. - /// Supported types are and only. + /// Supported types are and only. public ModuleAttribute( string id , string name @@ -161,14 +161,14 @@ string id /// The module website URL. /// Tags associated with the Module. /// Whether considered default tenant only. - /// Supported types are and only. + /// Supported types are and only. /// Whether feature is always enabled. - /// Supported types are and only. + /// Supported types are and only. /// Semantic Versioning /// At least expected herein to differentiate with /// parameterless ctor. /// Whether feature is enabled by dependency only. - /// Supported types are and only. + /// Supported types are and only. public ModuleAttribute( string id , string name @@ -220,14 +220,14 @@ string id /// The module website URL. /// Tags associated with the Module. /// Whether considered default tenant only. - /// Supported types are and only. + /// Supported types are and only. /// Whether feature is always enabled. - /// Supported types are and only. + /// Supported types are and only. /// Semantic Versioning /// At least expected herein to differentiate with /// parameterless ctor. /// Whether feature is enabled by dependency only. - /// Supported types are and only. + /// Supported types are and only. public ModuleAttribute( string id , string name @@ -276,7 +276,7 @@ protected internal static string GetAttributePrefix(Type attributeType) // Drops the 'Attribute' suffix from the conventional abbreviation, or leaves it alone static string GetTypeNamePrefix(string typeName) => typeName.EndsWith(attributeSuffix) - ? typeName.Substring(0, typeName.Length - attributeSuffix.Length) + ? typeName[..^attributeSuffix.Length] : typeName ; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs index b3d1520bc4d..167985ee528 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModularApplicationContext.cs @@ -16,7 +16,7 @@ public class ModularApplicationContext : IApplicationContext private readonly IHostEnvironment _environment; private readonly IEnumerable _moduleNamesProviders; private Application _application; - private static readonly object _initLock = new object(); + private static readonly object _initLock = new(); public ModularApplicationContext(IHostEnvironment environment, IEnumerable moduleNamesProviders) { @@ -39,18 +39,17 @@ private void EnsureInitialized() { lock (_initLock) { - if (_application == null) - { - _application = new Application(_environment, GetModules()); - } + _application ??= new Application(_environment, GetModules()); } } } private IEnumerable GetModules() { - var modules = new ConcurrentBag(); - modules.Add(new Module(_environment.ApplicationName, true)); + var modules = new ConcurrentBag + { + new Module(_environment.ApplicationName, true), + }; var names = _moduleNamesProviders .SelectMany(p => p.GetModuleNames()) diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Module.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Module.cs index 5d3f10d6fb9..47ab490d4c5 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Module.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Module.cs @@ -13,7 +13,7 @@ namespace OrchardCore.Modules public class Module { public const string WebRootPath = "wwwroot"; - public static string WebRoot = WebRootPath + "/"; + public const string WebRoot = WebRootPath + "/"; private readonly string _baseNamespace; private readonly DateTimeOffset _lastModified; @@ -29,7 +29,7 @@ public class Module /// Whether the Module may be considered to be the "Application". public Module(string assyName, bool isApplication = false) { - if (!string.IsNullOrWhiteSpace(assyName)) + if (!String.IsNullOrWhiteSpace(assyName)) { Assembly = Assembly.Load(new AssemblyName(assyName)); @@ -107,7 +107,7 @@ public Module(string assyName, bool isApplication = false) _baseNamespace = Name + '.'; _lastModified = DateTimeOffset.UtcNow; - if (!string.IsNullOrEmpty(Assembly?.Location)) + if (!String.IsNullOrEmpty(Assembly?.Location)) { try { diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleEmbeddedFileProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleEmbeddedFileProvider.cs index 9414480be5c..7f481b9c235 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleEmbeddedFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleEmbeddedFileProvider.cs @@ -17,10 +17,7 @@ public class ModuleEmbeddedFileProvider : IFileProvider { private readonly IApplicationContext _applicationContext; - public ModuleEmbeddedFileProvider(IApplicationContext applicationContext) - { - _applicationContext = applicationContext; - } + public ModuleEmbeddedFileProvider(IApplicationContext applicationContext) => _applicationContext = applicationContext; private Application Application => _applicationContext.Application; @@ -51,11 +48,11 @@ public IDirectoryContents GetDirectoryContents(string subpath) else if (folder.StartsWith(Application.ModulesRoot, StringComparison.Ordinal)) { // Skip "Areas/" from the folder path. - var path = folder.Substring(Application.ModulesRoot.Length); + var path = folder[Application.ModulesRoot.Length..]; var index = path.IndexOf('/'); // Resolve the module id and get all its asset paths. - var name = index == -1 ? path : path.Substring(0, index); + var name = index == -1 ? path : path[..index]; var paths = Application.GetModule(name).AssetPaths; // Resolve all files and folders directly under this given folder. @@ -82,17 +79,17 @@ public IFileInfo GetFileInfo(string subpath) if (path.StartsWith(Application.ModulesRoot, StringComparison.Ordinal)) { // Skip the "Areas/" root. - path = path.Substring(Application.ModulesRoot.Length); + path = path[Application.ModulesRoot.Length..]; var index = path.IndexOf('/'); // "{ModuleId}/**/*.*". if (index != -1) { // Resolve the module id. - var module = path.Substring(0, index); + var module = path[..index]; // Skip the module id to resolve the subpath. - var fileSubPath = path.Substring(index + 1); + var fileSubPath = path[(index + 1)..]; // If it is the app's module. if (module == Application.Name) @@ -109,14 +106,8 @@ public IFileInfo GetFileInfo(string subpath) return new NotFoundFileInfo(subpath); } - public IChangeToken Watch(string filter) - { - return NullChangeToken.Singleton; - } + public IChangeToken Watch(string filter) => NullChangeToken.Singleton; - private string NormalizePath(string path) - { - return path.Replace('\\', '/').Trim('/').Replace("//", "/"); - } + private static string NormalizePath(string path) => path.Replace('\\', '/').Trim('/').Replace("//", "/"); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleEmbeddedStaticFileProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleEmbeddedStaticFileProvider.cs index f1524af4b0e..7d726f41f10 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleEmbeddedStaticFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleEmbeddedStaticFileProvider.cs @@ -14,10 +14,7 @@ public class ModuleEmbeddedStaticFileProvider : IModuleStaticFileProvider { private readonly IApplicationContext _applicationContext; - public ModuleEmbeddedStaticFileProvider(IApplicationContext applicationContext) - { - _applicationContext = applicationContext; - } + public ModuleEmbeddedStaticFileProvider(IApplicationContext applicationContext) => _applicationContext = applicationContext; public IDirectoryContents GetDirectoryContents(string subpath) { @@ -41,13 +38,13 @@ public IFileInfo GetFileInfo(string subpath) var application = _applicationContext.Application; // Resolve the module id. - var module = path.Substring(0, index); + var module = path[..index]; // Check if it is an existing module. if (application.Modules.Any(m => m.Name == module)) { // Resolve the embedded file subpath: "wwwroot/**/*.*" - var fileSubPath = Module.WebRoot + path.Substring(index + 1); + var fileSubPath = Module.WebRoot + path[(index + 1)..]; if (module != application.Name) { @@ -65,14 +62,8 @@ public IFileInfo GetFileInfo(string subpath) return new NotFoundFileInfo(subpath); } - public IChangeToken Watch(string filter) - { - return NullChangeToken.Singleton; - } + public IChangeToken Watch(string filter) => NullChangeToken.Singleton; - private string NormalizePath(string path) - { - return path.Replace('\\', '/').Trim('/').Replace("//", "/"); - } + private static string NormalizePath(string path) => path.Replace('\\', '/').Trim('/').Replace("//", "/"); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleProjectStaticFileProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleProjectStaticFileProvider.cs index af07b45e80c..6d8aea13989 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleProjectStaticFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/ModuleProjectStaticFileProvider.cs @@ -15,7 +15,7 @@ namespace OrchardCore.Modules public class ModuleProjectStaticFileProvider : IModuleStaticFileProvider { private static Dictionary _roots; - private static readonly object _synLock = new object(); + private static readonly object _synLock = new(); public ModuleProjectStaticFileProvider(IApplicationContext applicationContext) { @@ -53,7 +53,7 @@ public ModuleProjectStaticFileProvider(IApplicationContext applicationContext) var index = asset.ProjectAssetPath.IndexOf('/' + Module.WebRoot, StringComparison.Ordinal); // Add the module project "wwwroot" folder. - roots[module.Name] = asset.ProjectAssetPath.Substring(0, index + Module.WebRoot.Length + 1); + roots[module.Name] = asset.ProjectAssetPath[..(index + Module.WebRoot.Length + 1)]; } } @@ -81,13 +81,13 @@ public IFileInfo GetFileInfo(string subpath) if (index != -1) { // Resolve the module id. - var module = path.Substring(0, index); + var module = path[..index]; // Get the module project "wwwroot" folder. if (_roots.TryGetValue(module, out var root)) { // Resolve "{ModuleProjectDirectory}wwwroot/**/*.*" - var filePath = root + path.Substring(module.Length + 1); + var filePath = root + path[(module.Length + 1)..]; if (File.Exists(filePath)) { @@ -114,13 +114,13 @@ public IChangeToken Watch(string filter) if (index != -1) { // Resolve the module id. - var module = path.Substring(0, index); + var module = path[..index]; // Get the module project "wwwroot" folder. if (_roots.TryGetValue(module, out var root)) { // Resolve "{ModuleProjectDirectory}wwwroot/**/*.*" - var filePath = root + path.Substring(module.Length + 1); + var filePath = root + path[(module.Length + 1)..]; if (File.Exists(filePath)) { @@ -133,9 +133,6 @@ public IChangeToken Watch(string filter) return NullChangeToken.Singleton; } - private string NormalizePath(string path) - { - return path.Replace('\\', '/').Trim('/').Replace("//", "/"); - } + private static string NormalizePath(string path) => path.Replace('\\', '/').Trim('/').Replace("//", "/"); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Modules/Services/ClockExtension.cs b/src/OrchardCore/OrchardCore.Abstractions/Modules/Services/ClockExtension.cs index 6a03c4ab2c8..e3b07de78e0 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Modules/Services/ClockExtension.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Modules/Services/ClockExtension.cs @@ -10,19 +10,14 @@ public static class ClockExtensions /// public static DateTimeOffset ConvertToTimeZone(this IClock clock, DateTime dateTime, ITimeZone timeZone) { - DateTime dateTimeUtc; - switch (dateTime.Kind) + var dateTimeUtc = dateTime.Kind switch { - case DateTimeKind.Utc: - dateTimeUtc = dateTime; - break; - case DateTimeKind.Local: - dateTimeUtc = dateTime.ToUniversalTime(); - break; - default: //DateTimeKind.Unspecified - dateTimeUtc = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); - break; - } + DateTimeKind.Utc => dateTime, + DateTimeKind.Local => dateTime.ToUniversalTime(), + + // 'DateTimeKind.Unspecified'. + _ => DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), + }; return clock.ConvertToTimeZone(new DateTimeOffset(dateTimeUtc), timeZone); } @@ -32,19 +27,14 @@ public static DateTimeOffset ConvertToTimeZone(this IClock clock, DateTime dateT /// public static Task ConvertToLocalAsync(this ILocalClock localClock, DateTime dateTime) { - DateTime dateTimeUtc; - switch (dateTime.Kind) + var dateTimeUtc = dateTime.Kind switch { - case DateTimeKind.Utc: - dateTimeUtc = dateTime; - break; - case DateTimeKind.Local: - dateTimeUtc = dateTime.ToUniversalTime(); - break; - default: //DateTimeKind.Unspecified - dateTimeUtc = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); - break; - } + DateTimeKind.Utc => dateTime, + DateTimeKind.Local => dateTime.ToUniversalTime(), + + // 'DateTimeKind.Unspecified'. + _ => DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), + }; return localClock.ConvertToLocalAsync(new DateTimeOffset(dateTimeUtc)); } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Pooling/ZStringWriter.cs b/src/OrchardCore/OrchardCore.Abstractions/Pooling/ZStringWriter.cs index fc92066bce1..dbc76ed3325 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Pooling/ZStringWriter.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Pooling/ZStringWriter.cs @@ -15,7 +15,7 @@ internal sealed class ZStringWriter : TextWriter { private Utf16ValueStringBuilder _sb; private bool _isOpen; - private UnicodeEncoding s_encoding; + private UnicodeEncoding _encoding; public ZStringWriter() : this(CultureInfo.CurrentCulture) { @@ -39,7 +39,7 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } - public override Encoding Encoding => s_encoding ??= new UnicodeEncoding(false, false); + public override Encoding Encoding => _encoding ??= new UnicodeEncoding(false, false); // Writes a character to the underlying string buffer. // @@ -59,18 +59,22 @@ public override void Write(char[] buffer, int index, int count) { throw new ArgumentNullException(nameof(buffer)); } + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } + if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } + if (buffer.Length - index < count) { - throw new ArgumentException(); + throw new ArgumentException("Buffer overflow."); } + if (!_isOpen) { throw new ObjectDisposedException(nameof(_sb)); diff --git a/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredAttribute.cs b/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredAttribute.cs index d58f9b3e247..1fa2af3ca94 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredAttribute.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredAttribute.cs @@ -1,6 +1,9 @@ +using System; + namespace OrchardCore.Routing { - public class FormValueRequiredAttribute : System.Attribute + [AttributeUsage(AttributeTargets.Method)] + public class FormValueRequiredAttribute : Attribute { public FormValueRequiredAttribute(string formKey) { diff --git a/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredMatcherPolicy.cs b/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredMatcherPolicy.cs index 6d082488154..0a0d0d64252 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredMatcherPolicy.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Routing/FormValueRequiredMatcherPolicy.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; @@ -13,7 +14,7 @@ public FormValueRequiredMatcherPolicy() { } - public override int Order => int.MinValue + 100; + public override int Order => Int32.MinValue + 100; public bool AppliesToEndpoints(IReadOnlyList endpoints) { @@ -59,7 +60,7 @@ public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) var value = httpContext.Request.Form[required.FormKey]; - candidates.SetValidity(i, !string.IsNullOrEmpty(value)); + candidates.SetValidity(i, !String.IsNullOrEmpty(value)); } return Task.CompletedTask; diff --git a/src/OrchardCore/OrchardCore.Abstractions/Routing/PathStringExtensions.cs b/src/OrchardCore/OrchardCore.Abstractions/Routing/PathStringExtensions.cs index 170ea6eb1e6..6b2c0f19acf 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Routing/PathStringExtensions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Routing/PathStringExtensions.cs @@ -9,7 +9,7 @@ public static bool StartsWithNormalizedSegments(this PathString path, PathString { if (other.HasValue && other.Value.EndsWith('/')) { - return path.StartsWithSegments(other.Value.Substring(0, other.Value.Length - 1)); + return path.StartsWithSegments(other.Value[..^1]); } return path.StartsWithSegments(other); @@ -19,7 +19,7 @@ public static bool StartsWithNormalizedSegments(this PathString path, PathString { if (other.HasValue && other.Value.EndsWith('/')) { - return path.StartsWithSegments(other.Value.Substring(0, other.Value.Length - 1), comparisonType); + return path.StartsWithSegments(other.Value[..^1], comparisonType); } return path.StartsWithSegments(other, comparisonType); @@ -29,7 +29,7 @@ public static bool StartsWithNormalizedSegments(this PathString path, PathString { if (other.HasValue && other.Value.EndsWith('/')) { - return path.StartsWithSegments(other.Value.Substring(0, other.Value.Length - 1), out remaining); + return path.StartsWithSegments(other.Value[..^1], out remaining); } return path.StartsWithSegments(other, out remaining); @@ -39,7 +39,7 @@ public static bool StartsWithNormalizedSegments(this PathString path, PathString { if (other.HasValue && other.Value.EndsWith('/')) { - return path.StartsWithSegments(other.Value.Substring(0, other.Value.Length - 1), comparisonType, out remaining); + return path.StartsWithSegments(other.Value[..^1], comparisonType, out remaining); } return path.StartsWithSegments(other, comparisonType, out remaining); diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/UpdatableDataProvider.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/UpdatableDataProvider.cs index d40bf9c62e8..298267ade3e 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/UpdatableDataProvider.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/Internal/UpdatableDataProvider.cs @@ -11,7 +11,7 @@ namespace OrchardCore.Environment.Shell.Configuration.Internal { internal class UpdatableDataProvider : IConfigurationProvider, IEnumerable> { - private ConfigurationReloadToken _reloadToken = new ConfigurationReloadToken(); + private ConfigurationReloadToken _reloadToken = new(); public UpdatableDataProvider(IEnumerable> initialData) { @@ -36,7 +36,7 @@ public virtual void Load() public virtual IEnumerable GetChildKeys(IEnumerable earlierKeys, string parentPath) { - var prefix = parentPath == null ? string.Empty : parentPath + ConfigurationPath.KeyDelimiter; + var prefix = parentPath == null ? String.Empty : parentPath + ConfigurationPath.KeyDelimiter; return Data .Where(kv => kv.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) @@ -48,7 +48,7 @@ public virtual IEnumerable GetChildKeys(IEnumerable earlierKeys, private static string Segment(string key, int prefixLength) { var indexOf = key.IndexOf(ConfigurationPath.KeyDelimiter, prefixLength, StringComparison.OrdinalIgnoreCase); - return indexOf < 0 ? key.Substring(prefixLength) : key.Substring(prefixLength, indexOf - prefixLength); + return indexOf < 0 ? key[prefixLength..] : key[prefixLength..indexOf]; } public IChangeToken GetReloadToken() diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/ShellConfiguration.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/ShellConfiguration.cs index 85d1e680f5d..86be2631f19 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/ShellConfiguration.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Configuration/ShellConfiguration.cs @@ -21,9 +21,9 @@ public class ShellConfiguration : IShellConfiguration private readonly IEnumerable> _initialData; private readonly string _name; - private Func> _configBuilderFactory; + private readonly Func> _configBuilderFactory; private readonly IEnumerable _configurationProviders; - private SemaphoreSlim _semaphore = new SemaphoreSlim(1); + private readonly SemaphoreSlim _semaphore = new(1); public ShellConfiguration() { diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Models/FeatureProfile.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Models/FeatureProfile.cs index f180d428161..5bc1ae79fb7 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Models/FeatureProfile.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Models/FeatureProfile.cs @@ -9,7 +9,7 @@ public class FeatureProfile public string Name { get; set; } - public List FeatureRules = new List(); + public List FeatureRules = new(); } public class FeatureRule diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Models/FeatureProfilesRuleOptions.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Models/FeatureProfilesRuleOptions.cs index c512306759a..a8ca2d9cf30 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Models/FeatureProfilesRuleOptions.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Models/FeatureProfilesRuleOptions.cs @@ -8,6 +8,6 @@ namespace OrchardCore.Environment.Shell.Models /// public class FeatureProfilesRuleOptions { - public Dictionary> Rules = new Dictionary>(StringComparer.OrdinalIgnoreCase); + public Dictionary> Rules = new(StringComparer.OrdinalIgnoreCase); } } diff --git a/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScope.cs b/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScope.cs index 7c11da6a1bc..d1d83578654 100644 --- a/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScope.cs +++ b/src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScope.cs @@ -14,7 +14,7 @@ namespace OrchardCore.Environment.Shell.Scope /// /// Custom 'IServiceScope' managing the shell state and the execution flow. /// - public class ShellScope : IServiceScope + public sealed class ShellScope : IServiceScope { private static readonly AsyncLocal _current = new(); diff --git a/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Services/IAdminNodeProviderFactory.cs b/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Services/IAdminNodeProviderFactory.cs index e502ab691a1..720c3936d43 100644 --- a/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Services/IAdminNodeProviderFactory.cs +++ b/src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Services/IAdminNodeProviderFactory.cs @@ -10,9 +10,9 @@ public interface IAdminNodeProviderFactory public class AdminNodeProviderFactory : IAdminNodeProviderFactory where TAdminNode : AdminNode, new() { - private static readonly string TypeName = typeof(TAdminNode).Name; + private static readonly string _typeName = typeof(TAdminNode).Name; - public string Name => TypeName; + public string Name => _typeName; public AdminNode Create() { diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/PermissionsExtensions.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/PermissionsExtensions.cs index a04e3070831..8ad6aa36724 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/PermissionsExtensions.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/PermissionsExtensions.cs @@ -8,7 +8,7 @@ namespace OrchardCore.Apis.GraphQL { public static class PermissionsExtensions { - private static readonly string MetaDataKey = "Permissions"; + private const string MetaDataKey = "Permissions"; public static void RequirePermission(this IProvideMetadata type, Permission permission, object resource = null) { diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/ResolveFieldContextExtensions.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/ResolveFieldContextExtensions.cs index 2904d33bf78..0755d571ed8 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/ResolveFieldContextExtensions.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Abstractions/Extensions/ResolveFieldContextExtensions.cs @@ -15,7 +15,7 @@ public static bool HasPopulatedArgument(this IResolveFieldContext source, string { if (source.Arguments?.ContainsKey(argumentName) ?? false) { - return !string.IsNullOrEmpty(source.Arguments[argumentName].Value?.ToString()); + return !String.IsNullOrEmpty(source.Arguments[argumentName].Value?.ToString()); }; return false; @@ -25,7 +25,7 @@ public static bool HasPopulatedArgument(this IResolveFieldContext value) return value; } - // Applies to all types - public static Dictionary EqualityOperators = new Dictionary + // Applies to all types. + public static readonly Dictionary EqualityOperators = new() { { "", "is equal to" }, - { "_not", "is not equal to" } + { "_not", "is not equal to" }, }; - // Applies to all types - public static Dictionary MultiValueComparisonOperators = new Dictionary + // Applies to all types. + public static readonly Dictionary MultiValueComparisonOperators = new() { { "_in", "is in collection" }, - { "_not_in", "is not in collection" } + { "_not_in", "is not in collection" }, }; - // Applies to non strings - public static Dictionary NonStringValueComparisonOperators = new Dictionary + // 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" } + { "_lte", "is less than or equal" }, }; - // Applies to strings - public static Dictionary StringComparisonOperators = new Dictionary + // 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"} + {"_not_ends_with", "does not end with the string"}, }; public void AddScalarFilterFields(string fieldName, string description) diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentPartBuilder.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentPartBuilder.cs index 7c6d501cbb0..6c113470818 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentPartBuilder.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentPartBuilder.cs @@ -6,10 +6,9 @@ namespace OrchardCore.Apis.GraphQL.Client { public class ContentPartBuilder { - private string _contentPartName; - - private Dictionary _keysWithValues = new Dictionary(); - private List _keys = new List(); + private readonly string _contentPartName; + private readonly Dictionary _keysWithValues = new(); + private readonly List _keys = new(); public ContentPartBuilder(string contentPartName) { diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentResource.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentResource.cs index 3cbe3b22fb7..e8b7c09083a 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentResource.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentResource.cs @@ -7,7 +7,7 @@ namespace OrchardCore.Apis.GraphQL.Client { public class ContentResource { - private HttpClient _client; + private readonly HttpClient _client; public ContentResource(HttpClient client) { diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeCreateResourceBuilder.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeCreateResourceBuilder.cs index 9b2c273b91f..356271a9851 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeCreateResourceBuilder.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeCreateResourceBuilder.cs @@ -5,9 +5,8 @@ namespace OrchardCore.Apis.GraphQL.Client { public class ContentTypeCreateResourceBuilder { - private IDictionary _values = new Dictionary(); - - private List contentPartBuilders = new List(); + private readonly Dictionary _values = new(); + private readonly List _contentPartBuilders = new(); private string ContentType { get; set; } @@ -19,7 +18,7 @@ public ContentTypeCreateResourceBuilder(string contentType) public ContentPartBuilder WithContentPart(string contentPartName) { var builder = new ContentPartBuilder(contentPartName.ToGraphQLStringFormat()); - contentPartBuilders.Add(builder); + _contentPartBuilders.Add(builder); return builder; } @@ -54,9 +53,9 @@ internal string Build() } } - for (var i = 0; i < contentPartBuilders.Count; i++) + for (var i = 0; i < _contentPartBuilders.Count; i++) { - sbo.Append(contentPartBuilders[i].Build()).AppendLine((i == (contentPartBuilders.Count - 1)) ? "" : ","); + sbo.Append(_contentPartBuilders[i].Build()).AppendLine((i == (_contentPartBuilders.Count - 1)) ? "" : ","); } sbo.Append('}').AppendLine(); diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeQueryResourceBuilder.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeQueryResourceBuilder.cs index d0b3b6733c0..9d3179ebe22 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeQueryResourceBuilder.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/ContentTypeQueryResourceBuilder.cs @@ -7,11 +7,10 @@ namespace OrchardCore.Apis.GraphQL.Client { public class ContentTypeQueryResourceBuilder { - private string _contentType; - - private List _keys = new List(); - private IDictionary _queries = new Dictionary(); - private List _nested = new List(); + private readonly string _contentType; + private readonly List _keys = new(); + private readonly Dictionary _queries = new(); + private readonly List _nested = new(); public ContentTypeQueryResourceBuilder(string contentType) { diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpContentExtensions.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpContentExtensions.cs index dc6be8b9d56..b858e95ab15 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpContentExtensions.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpContentExtensions.cs @@ -10,37 +10,34 @@ internal static class HttpContentExtensions { public static async Task ReadAsAsync(this HttpContent content, JsonConverter jsonConverter) { - using (var stream = await content.ReadAsStreamAsync()) - using (var reader = new StreamReader(stream)) - using (var jsonReader = new JsonTextReader(reader)) - { - var ser = new JsonSerializer(); - ser.Converters.Insert(0, jsonConverter); - return ser.Deserialize(jsonReader); - } + using var stream = await content.ReadAsStreamAsync(); + using var reader = new StreamReader(stream); + using var jsonReader = new JsonTextReader(reader); + + var ser = new JsonSerializer(); + ser.Converters.Insert(0, jsonConverter); + + return ser.Deserialize(jsonReader); } public static async Task ReadAsAsync(this HttpContent content) { - using (var data = await content.ReadAsStreamAsync()) - { - return data.ReadAs(); - } + using var data = await content.ReadAsStreamAsync(); + return data.ReadAs(); } public static T ReadAs(this Stream stream) { - using (var reader = new StreamReader(stream)) - using (var jsonReader = new JsonTextReader(reader)) + using var reader = new StreamReader(stream); + using var jsonReader = new JsonTextReader(reader); + + var jsonSerializer = new JsonSerializer { - var jsonSerializer = new JsonSerializer - { - NullValueHandling = NullValueHandling.Ignore, - Converters = { new StringEnumConverter() } - }; + NullValueHandling = NullValueHandling.Ignore, + Converters = { new StringEnumConverter() }, + }; - return jsonSerializer.Deserialize(jsonReader); - } + return jsonSerializer.Deserialize(jsonReader); } } } diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpRequestExtensions.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpRequestExtensions.cs index 16bea59b132..ff720e1bf96 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpRequestExtensions.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/HttpRequestExtensions.cs @@ -12,7 +12,7 @@ namespace OrchardCore.Apis.GraphQL.Client /// internal static class HttpRequestExtensions { - private readonly static JsonSerializerSettings JsonSettings = new JsonSerializerSettings() + private readonly static JsonSerializerSettings _jsonSettings = new() { NullValueHandling = NullValueHandling.Ignore }; @@ -44,7 +44,7 @@ internal static class HttpRequestExtensions JsonSerializerSettings settings = null) { var content = new StringContent( - JsonConvert.SerializeObject(value, settings ?? JsonSettings), + JsonConvert.SerializeObject(value, settings ?? _jsonSettings), Encoding.UTF8, "application/json"); @@ -109,7 +109,7 @@ internal static class HttpRequestExtensions JsonSerializerSettings settings = null) { var content = new StringContent( - JsonConvert.SerializeObject(value, settings ?? JsonSettings), + JsonConvert.SerializeObject(value, settings ?? _jsonSettings), Encoding.UTF8, "application/json"); @@ -143,12 +143,14 @@ internal static class HttpRequestExtensions JsonSerializerSettings settings = null) { var content = new StringContent( - JsonConvert.SerializeObject(value, settings ?? JsonSettings), + JsonConvert.SerializeObject(value, settings ?? _jsonSettings), Encoding.UTF8, "application/json"); - var request = new HttpRequestMessage(HttpMethod.Post, requestUri); - request.Content = content; + var request = new HttpRequestMessage(HttpMethod.Post, requestUri) + { + Content = content, + }; request.Headers .Accept @@ -167,8 +169,10 @@ internal static class HttpRequestExtensions Encoding.UTF8, "application/json"); - var request = new HttpRequestMessage(HttpMethod.Post, requestUri); - request.Content = content; + var request = new HttpRequestMessage(HttpMethod.Post, requestUri) + { + Content = content, + }; request.Headers .Accept @@ -187,8 +191,10 @@ internal static class HttpRequestExtensions Encoding.UTF8, "application/vnd.api+json"); - var request = new HttpRequestMessage(HttpMethod.Post, requestUri); - request.Content = content; + var request = new HttpRequestMessage(HttpMethod.Post, requestUri) + { + Content = content, + }; request.Headers .Accept diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/StringExtensions.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/StringExtensions.cs index 5b45c10126d..53305edad15 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/StringExtensions.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/Extensions/StringExtensions.cs @@ -1,10 +1,9 @@ +using System; + namespace OrchardCore.Apis.GraphQL.Client { internal static class StringExtensions { - public static string ToGraphQLStringFormat(this string value) - { - return char.ToLower(value[0]) + value.Substring(1); - } + public static string ToGraphQLStringFormat(this string value) => Char.ToLower(value[0]) + value[1..]; } } diff --git a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/OrchardGraphQLClient.cs b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/OrchardGraphQLClient.cs index 0196f4cea24..f021bdede5f 100644 --- a/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/OrchardGraphQLClient.cs +++ b/src/OrchardCore/OrchardCore.Apis.GraphQL.Client/OrchardGraphQLClient.cs @@ -4,12 +4,9 @@ namespace OrchardCore.Apis.GraphQL.Client { public class OrchardGraphQLClient { - public OrchardGraphQLClient(HttpClient client) - { - Client = client; - } + public OrchardGraphQLClient(HttpClient client) => Client = client; - public ContentResource Content => new ContentResource(Client); + public ContentResource Content => new(Client); public HttpClient Client { get; } } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/AuditTrailPermissions.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/AuditTrailPermissions.cs index 5ec758ffe36..aaea1964d46 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/AuditTrailPermissions.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/AuditTrailPermissions.cs @@ -4,8 +4,8 @@ namespace OrchardCore.AuditTrail { public static class AuditTrailPermissions { - public static readonly Permission ViewAuditTrail = new Permission(nameof(ViewAuditTrail), "View audit trail"); + public static readonly Permission ViewAuditTrail = new(nameof(ViewAuditTrail), "View audit trail"); - public static readonly Permission ManageAuditTrailSettings = new Permission(nameof(ManageAuditTrailSettings), "Manage audit trail settings"); + public static readonly Permission ManageAuditTrailSettings = new(nameof(ManageAuditTrailSettings), "Manage audit trail settings"); } } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOption.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOption.cs index f638416eaa3..2f83376eb0e 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOption.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailAdminListOption.cs @@ -16,8 +16,8 @@ public class AuditTrailAdminListOption Func selectListItem, bool isDefault) { - Value = value ?? throw new ArgumentNullException(nameof(Value)); - Query = query ?? throw new ArgumentNullException(nameof(Query)); + Value = value ?? throw new ArgumentNullException(nameof(value)); + Query = query ?? throw new ArgumentNullException(nameof(query)); SelectListItem = selectListItem; IsDefault = isDefault; } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptor.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptor.cs index 653b235fe07..ca2dced161e 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptor.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptor.cs @@ -6,7 +6,10 @@ 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; @@ -17,12 +20,14 @@ public AuditTrailCategoryDescriptor(string name, Func LocalizedName { get; } public IReadOnlyDictionary Events { get; } - private static IReadOnlyDictionary _empty = new Dictionary(); - public static AuditTrailCategoryDescriptor Default(string name) - => new AuditTrailCategoryDescriptor( - name, - (sp) => new LocalizedString(name, name), - _empty - ); + private static readonly IReadOnlyDictionary _empty = + new Dictionary(); + + 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 f95e191bf40..c3e268261b5 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptorBuilder.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailCategoryDescriptorBuilder.cs @@ -20,7 +20,7 @@ public class AuditTrailCategoryDescriptorBuilder private readonly Type _localizerType; private readonly Func _localizedCategoryName; - private readonly Dictionary _events = new Dictionary(); + private readonly Dictionary _events = new(); public AuditTrailCategoryDescriptorBuilder(string categoryName, Type localizerType, Func localizedName) { @@ -56,7 +56,6 @@ public AuditTrailCategoryDescriptorBuilder RemoveEvent(string name) return this; } - internal AuditTrailCategoryDescriptor Build() - => new AuditTrailCategoryDescriptor(_categoryName, _localizedCategoryName, _events); + internal AuditTrailCategoryDescriptor Build() => new(_categoryName, _localizedCategoryName, _events); } } diff --git a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailEventDescriptor.cs b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailEventDescriptor.cs index 9fec2d3ccfc..06620fdc319 100644 --- a/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailEventDescriptor.cs +++ b/src/OrchardCore/OrchardCore.AuditTrail.Abstractions/Services/Models/AuditTrailEventDescriptor.cs @@ -25,13 +25,13 @@ public AuditTrailEventDescriptor(string name, string category, Func new AuditTrailEventDescriptor( - auditTrailEvent.Name, - auditTrailEvent.Category, - (sp) => new LocalizedString(auditTrailEvent.Name, auditTrailEvent.Name), - (sp) => new LocalizedString(auditTrailEvent.Category, auditTrailEvent.Category), - (sp) => new LocalizedString(auditTrailEvent.Name, auditTrailEvent.Name) - ); + public static AuditTrailEventDescriptor Default(AuditTrailEvent auditTrailEvent) => + new( + auditTrailEvent.Name, + auditTrailEvent.Category, + (sp) => new LocalizedString(auditTrailEvent.Name, auditTrailEvent.Name), + (sp) => new LocalizedString(auditTrailEvent.Category, auditTrailEvent.Category), + (sp) => new LocalizedString(auditTrailEvent.Name, auditTrailEvent.Name) + ); } } diff --git a/src/OrchardCore/OrchardCore.Autoroute.Core/Indexes/AutoroutePartIndex.cs b/src/OrchardCore/OrchardCore.Autoroute.Core/Indexes/AutoroutePartIndex.cs index da2f27bbe0d..0e6d61d7d03 100644 --- a/src/OrchardCore/OrchardCore.Autoroute.Core/Indexes/AutoroutePartIndex.cs +++ b/src/OrchardCore/OrchardCore.Autoroute.Core/Indexes/AutoroutePartIndex.cs @@ -164,7 +164,7 @@ private async Task PopulateContainedContentItemIndexesAsync(List()) { var contentItem = jItem.ToObject(); var handlerAspect = await _contentManager.PopulateAspectAsync(contentItem); diff --git a/src/OrchardCore/OrchardCore.Autoroute.Core/Model/AutoroutePart.cs b/src/OrchardCore/OrchardCore.Autoroute.Core/Model/AutoroutePart.cs index 9a07e36e93d..1ae3dadea00 100644 --- a/src/OrchardCore/OrchardCore.Autoroute.Core/Model/AutoroutePart.cs +++ b/src/OrchardCore/OrchardCore.Autoroute.Core/Model/AutoroutePart.cs @@ -4,9 +4,10 @@ namespace OrchardCore.Autoroute.Models { public class AutoroutePart : ContentPart { - public static char[] InvalidCharactersForPath = ":?#[]@!$&'()*+,.;=<>\\|%".ToCharArray(); public const int MaxPathLength = 1024; + public static readonly char[] InvalidCharactersForPath = ":?#[]@!$&'()*+,.;=<>\\|%".ToCharArray(); + public string Path { get; set; } /// diff --git a/src/OrchardCore/OrchardCore.Autoroute.Core/Services/AutorouteEntries.cs b/src/OrchardCore/OrchardCore.Autoroute.Core/Services/AutorouteEntries.cs index ec02231bce4..591566f37b6 100644 --- a/src/OrchardCore/OrchardCore.Autoroute.Core/Services/AutorouteEntries.cs +++ b/src/OrchardCore/OrchardCore.Autoroute.Core/Services/AutorouteEntries.cs @@ -20,7 +20,7 @@ public class AutorouteEntries : IAutorouteEntries private ImmutableDictionary _paths = ImmutableDictionary.Empty; private ImmutableDictionary _contentItemIds = ImmutableDictionary.Empty; - private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); + private readonly SemaphoreSlim _semaphore = new(1); private long _lastIndexId; private string _stateIdentifier; diff --git a/src/OrchardCore/OrchardCore.Autoroute.Core/Services/AutorouteHandleProvider.cs b/src/OrchardCore/OrchardCore.Autoroute.Core/Services/AutorouteHandleProvider.cs index cdb17712cd7..3d7f444c165 100644 --- a/src/OrchardCore/OrchardCore.Autoroute.Core/Services/AutorouteHandleProvider.cs +++ b/src/OrchardCore/OrchardCore.Autoroute.Core/Services/AutorouteHandleProvider.cs @@ -8,10 +8,7 @@ public class AutorouteHandleProvider : IContentHandleProvider { private readonly IAutorouteEntries _autorouteEntries; - public AutorouteHandleProvider(IAutorouteEntries autorouteEntries) - { - _autorouteEntries = autorouteEntries; - } + public AutorouteHandleProvider(IAutorouteEntries autorouteEntries) => _autorouteEntries = autorouteEntries; public int Order => 10; @@ -19,7 +16,7 @@ public async Task GetContentItemIdAsync(string handle) { if (handle.StartsWith("slug:", System.StringComparison.OrdinalIgnoreCase)) { - handle = handle.Substring(5); + handle = handle[5..]; if (!handle.StartsWith('/')) { diff --git a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/ContentLocalizationOrchardHelperExtensions.cs b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/ContentLocalizationOrchardHelperExtensions.cs index 434da8102bd..ef2da4009de 100644 --- a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/ContentLocalizationOrchardHelperExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/ContentLocalizationOrchardHelperExtensions.cs @@ -8,7 +8,9 @@ /// /// Provides an extension methods for . /// +#pragma warning disable CA1050 // Declare types in namespaces public static class ContentLocalizationOrchardHelperExtensions +#pragma warning restore CA1050 // Declare types in namespaces { /// /// Gets the culture for a given . diff --git a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Records/LocalizedContentItemIndex.cs b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Records/LocalizedContentItemIndex.cs index d51d7e892a3..18c98d22c75 100644 --- a/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Records/LocalizedContentItemIndex.cs +++ b/src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Records/LocalizedContentItemIndex.cs @@ -25,8 +25,8 @@ public class LocalizedContentItemIndex : MapIndex public class LocalizedContentItemIndexProvider : ContentHandlerBase, IIndexProvider, IScopedIndexProvider { private readonly IServiceProvider _serviceProvider; - private readonly HashSet _itemRemoved = new HashSet(); - private readonly HashSet _partRemoved = new HashSet(); + private readonly HashSet _itemRemoved = new(); + private readonly HashSet _partRemoved = new(); private IContentDefinitionManager _contentDefinitionManager; public LocalizedContentItemIndexProvider(IServiceProvider serviceProvider) diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentElement.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentElement.cs index f58b2cc71b5..7b86a835e33 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentElement.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentElement.cs @@ -22,7 +22,7 @@ protected ContentElement(JObject data) } [JsonIgnore] - protected internal Dictionary Elements => _elements = _elements ?? new Dictionary(); + protected internal Dictionary Elements => _elements ??= new Dictionary(); [JsonIgnore] public dynamic Content { get { return Data; } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentExtensions.cs index e751c5b9c36..6005751cec7 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentExtensions.cs @@ -13,7 +13,7 @@ public static class ContentExtensions /// /// These settings instruct merge to replace current value, even for null values. /// - private static readonly JsonMergeSettings JsonMergeSettings = new JsonMergeSettings { 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. @@ -104,8 +104,11 @@ public static TElement GetOrCreate(this ContentElement contentElement, if (existing == null) { - var newElement = new TElement(); - newElement.ContentItem = contentElement.ContentItem; + var newElement = new TElement + { + ContentItem = contentElement.ContentItem, + }; + contentElement.Data[name] = newElement.Data; contentElement.Elements[name] = newElement; return newElement; @@ -179,7 +182,7 @@ public static ContentElement Apply(this ContentElement contentElement, string na if (elementData != null) { - elementData.Merge(JObject.FromObject(element), JsonMergeSettings); + elementData.Merge(JObject.FromObject(element), _jsonMergeSettings); } else { @@ -211,7 +214,7 @@ public static ContentElement Apply(this ContentElement contentElement, ContentEl { if (contentElement.Data != null) { - contentElement.Data.Merge(JObject.FromObject(element.Data), JsonMergeSettings); + contentElement.Data.Merge(JObject.FromObject(element.Data), _jsonMergeSettings); } else { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentFieldOption.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentFieldOption.cs index fd98b3a736d..d4f0b003101 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentFieldOption.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentFieldOption.cs @@ -5,7 +5,7 @@ namespace OrchardCore.ContentManagement { public class ContentFieldOption : ContentFieldOptionBase { - private readonly List _handlers = new List(); + private readonly List _handlers = new(); public ContentFieldOption(Type contentFieldType) : base(contentFieldType) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemConverter.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemConverter.cs index 88c4620a997..95fa3547560 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemConverter.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentItemConverter.cs @@ -6,30 +6,31 @@ namespace OrchardCore.ContentManagement { public class ContentItemConverter : JsonConverter { - private readonly JsonLoadSettings _jsonLoadSettings = new JsonLoadSettings + private readonly JsonLoadSettings _jsonLoadSettings = new() { - LineInfoHandling = LineInfoHandling.Ignore // defaults to loading which allocates quite a lot + LineInfoHandling = LineInfoHandling.Ignore, // Defaults to loading which allocates quite a lot. }; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var contentItem = (ContentItem)value; - var o = new JObject(); - - // Write all well-known properties - o.Add(new JProperty(nameof(ContentItem.ContentItemId), contentItem.ContentItemId)); - o.Add(new JProperty(nameof(ContentItem.ContentItemVersionId), contentItem.ContentItemVersionId)); - o.Add(new JProperty(nameof(ContentItem.ContentType), contentItem.ContentType)); - o.Add(new JProperty(nameof(ContentItem.DisplayText), contentItem.DisplayText)); - o.Add(new JProperty(nameof(ContentItem.Latest), contentItem.Latest)); - o.Add(new JProperty(nameof(ContentItem.Published), contentItem.Published)); - o.Add(new JProperty(nameof(ContentItem.ModifiedUtc), contentItem.ModifiedUtc)); - o.Add(new JProperty(nameof(ContentItem.PublishedUtc), contentItem.PublishedUtc)); - o.Add(new JProperty(nameof(ContentItem.CreatedUtc), contentItem.CreatedUtc)); - o.Add(new JProperty(nameof(ContentItem.Owner), contentItem.Owner)); - o.Add(new JProperty(nameof(ContentItem.Author), contentItem.Author)); + var o = new JObject + { + // Write all well-known properties. + new JProperty(nameof(ContentItem.ContentItemId), contentItem.ContentItemId), + new JProperty(nameof(ContentItem.ContentItemVersionId), contentItem.ContentItemVersionId), + new JProperty(nameof(ContentItem.ContentType), contentItem.ContentType), + new JProperty(nameof(ContentItem.DisplayText), contentItem.DisplayText), + new JProperty(nameof(ContentItem.Latest), contentItem.Latest), + new JProperty(nameof(ContentItem.Published), contentItem.Published), + new JProperty(nameof(ContentItem.ModifiedUtc), contentItem.ModifiedUtc), + new JProperty(nameof(ContentItem.PublishedUtc), contentItem.PublishedUtc), + new JProperty(nameof(ContentItem.CreatedUtc), contentItem.CreatedUtc), + new JProperty(nameof(ContentItem.Owner), contentItem.Owner), + new JProperty(nameof(ContentItem.Author), contentItem.Author), + }; - // Write all custom content properties + // Write all custom content properties. o.Merge(contentItem.Data); o.WriteTo(writer); @@ -95,7 +96,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist var customProperty = JProperty.Load(reader, _jsonLoadSettings); contentItem.Data.Add(customProperty); - // Skip reading a token as JProperty.Load already did the next one + // Skip reading a token as JProperty.Load already did the next one. skip = true; break; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPartOption.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPartOption.cs index 7f7412b20dc..b33ae933e6f 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPartOption.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/ContentPartOption.cs @@ -5,7 +5,7 @@ namespace OrchardCore.ContentManagement { public class ContentPartOption : ContentPartOptionBase { - private readonly List _handlers = new List(); + private readonly List _handlers = new(); public ContentPartOption(Type contentPartType) : base(contentPartType) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentValidateResult.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentValidateResult.cs index 5060383ecd9..356586f86fa 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentValidateResult.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/ContentValidateResult.cs @@ -5,7 +5,7 @@ namespace OrchardCore.ContentManagement.Handlers { public class ContentValidateResult { - private readonly List _errors = new List(); + private readonly List _errors = new(); public IReadOnlyList Errors => _errors; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Parts/ValidateContentPartContext.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Parts/ValidateContentPartContext.cs index e6a614ec6fe..4e294f117c8 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Parts/ValidateContentPartContext.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Handlers/Parts/ValidateContentPartContext.cs @@ -1,8 +1,8 @@ using System.ComponentModel.DataAnnotations; -using OrchardCore.ContentManagement; -using OrchardCore.ContentManagement.Handlers; using OrchardCore.ContentManagement.Metadata.Models; +namespace OrchardCore.ContentManagement.Handlers; + public class ValidateContentPartContext : ValidateContentContext { public ValidateContentPartContext(ContentItem contentItem) diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentBuilderSettings.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentBuilderSettings.cs index f24608cdb16..9bf0ac1147f 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentBuilderSettings.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentBuilderSettings.cs @@ -8,12 +8,19 @@ public static class ContentBuilderSettings /// /// Replace current value, even for null values, union arrays. /// - public static readonly JsonMergeSettings JsonMergeSettings = new JsonMergeSettings { 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 JsonSerializer IgnoreDefaultValuesSerializer = new JsonSerializer { DefaultValueHandling = DefaultValueHandling.Ignore }; + public static readonly JsonSerializer IgnoreDefaultValuesSerializer = new() + { + DefaultValueHandling = DefaultValueHandling.Ignore, + }; } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypeDefinitionBuilder.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypeDefinitionBuilder.cs index 76f85d79a7a..9aeb5f4de41 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypeDefinitionBuilder.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypeDefinitionBuilder.cs @@ -151,8 +151,10 @@ public ContentTypeDefinitionBuilder WithPart(string name, ContentPartDefinition } else { - existingPart = new ContentTypePartDefinition(name, partDefinition, new JObject()); - existingPart.ContentTypeDefinition = Current; + existingPart = new ContentTypePartDefinition(name, partDefinition, new JObject()) + { + ContentTypeDefinition = Current, + }; } var configurer = new PartConfigurerImpl(existingPart); @@ -181,8 +183,10 @@ public async Task WithPartAsync(string name, Conte } else { - existingPart = new ContentTypePartDefinition(name, partDefinition, new JObject()); - existingPart.ContentTypeDefinition = Current; + existingPart = new ContentTypePartDefinition(name, partDefinition, new JObject()) + { + ContentTypeDefinition = Current, + }; } var configurer = new PartConfigurerImpl(existingPart); @@ -211,6 +215,7 @@ public override ContentTypePartDefinition Build() { throw new ArgumentException("Content part name must start with a letter", "name"); } + if (!String.Equals(Current.Name, Current.Name.ToSafeName(), StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("Content part name contains invalid characters", "name"); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypePartDefinitionBuilder.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypePartDefinitionBuilder.cs index fc39b20aafb..787bdef5bac 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypePartDefinitionBuilder.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypePartDefinitionBuilder.cs @@ -18,7 +18,7 @@ protected ContentTypePartDefinitionBuilder(ContentTypePartDefinition part) Current = part; Name = part.Name; PartName = part.PartDefinition.Name; - TypeName = part.ContentTypeDefinition != null ? part.ContentTypeDefinition.Name : default(string); + TypeName = part.ContentTypeDefinition != null ? part.ContentTypeDefinition.Name : default; _settings = new JObject(part.Settings); } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentDefinition.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentDefinition.cs index c033f3d8b50..49a190f6842 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentDefinition.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Models/ContentDefinition.cs @@ -9,7 +9,7 @@ public abstract class ContentDefinition { public string Name { get; protected set; } - private Dictionary NamedSettings = new Dictionary(); + private Dictionary _namedSettings = new(); /// /// Do not access this property directly. Migrate to use GetSettings and PopulateSettings. @@ -23,7 +23,7 @@ public T GetSettings() where T : new() return new T(); } - var namedSettings = NamedSettings; + var namedSettings = _namedSettings; if (!namedSettings.TryGetValue(typeof(T), out var result)) { @@ -39,9 +39,12 @@ public T GetSettings() where T : new() result = new T(); } - namedSettings = new Dictionary(NamedSettings); - namedSettings[typeof(T)] = result; - NamedSettings = namedSettings; + namedSettings = new Dictionary(_namedSettings) + { + [typeof(T)] = result, + }; + + _namedSettings = namedSettings; } return (T)result; @@ -60,7 +63,7 @@ public void PopulateSettings(T target) if (Settings.TryGetValue(typeName, out value)) { JsonConvert.PopulateObject(value.ToString(), target); - NamedSettings = new Dictionary(); + _namedSettings = new Dictionary(); } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs index 1a5691144e8..1820baf350a 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Utilities/StringExtensions.cs @@ -14,7 +14,7 @@ public static class StringExtensions public static string CamelFriendly(this string camel) { // optimize common cases - if (string.IsNullOrWhiteSpace(camel)) + if (String.IsNullOrWhiteSpace(camel)) { return ""; } @@ -23,7 +23,7 @@ public static string CamelFriendly(this string camel) for (var i = 0; i < camel.Length; ++i) { var c = camel[i]; - if (i != 0 && char.IsUpper(c)) + if (i != 0 && Char.IsUpper(c)) { sb.Append(' '); } @@ -40,7 +40,7 @@ public static string Ellipsize(this string text, int characterCount) public static string Ellipsize(this string text, int characterCount, string ellipsis, bool wordBoundary = false) { - if (string.IsNullOrWhiteSpace(text)) + if (String.IsNullOrWhiteSpace(text)) return ""; if (characterCount < 0 || text.Length <= characterCount) @@ -65,13 +65,13 @@ public static string Ellipsize(this string text, int characterCount, string elli characterCount = backup; } - var trimmed = text.Substring(0, characterCount); + var trimmed = text[..characterCount]; return trimmed + ellipsis; } public static LocalizedString OrDefault(this string text, LocalizedString defaultValue) { - return string.IsNullOrEmpty(text) + return String.IsNullOrEmpty(text) ? defaultValue : new LocalizedString(null, text); } @@ -89,7 +89,7 @@ public static string RemoveTags(this string html, bool htmlDecode = false) var inside = false; for (var i = 0; i < html.Length; i++) { - char current = html[i]; + var current = html[i]; switch (current) { @@ -128,7 +128,7 @@ public static string ReplaceNewLinesWith(this string text, string replacement) .Replace("\r\r", String.Format(replacement, "\r\n")); } - private static readonly char[] validSegmentChars = "/?#[]@\"^{}|`<>\t\r\n\f ".ToCharArray(); + 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 @@ -142,7 +142,7 @@ public static bool IsValidUrlSegment(this string segment) // // rough blacklist regex == m/^[^/?#[]@"^{}|\s`<>]+$/ (leaving off % to keep the regex simple) - return !segment.Any(validSegmentChars); + return !segment.Any(_validSegmentChars); } /// @@ -153,13 +153,15 @@ public static bool IsValidUrlSegment(this string segment) /// public static string ToSafeName(this string name) { - if (string.IsNullOrWhiteSpace(name)) - return string.Empty; + if (String.IsNullOrWhiteSpace(name)) + { + return String.Empty; + } name = RemoveDiacritics(name); name = name.Strip(c => !c.IsLetter() - && !char.IsDigit(c) + && !Char.IsDigit(c) ); name = name.Trim(); @@ -167,16 +169,18 @@ public static string ToSafeName(this string name) // don't allow non A-Z chars as first letter, as they are not allowed in prefixes while (name.Length > 0 && !IsLetter(name[0])) { - name = name.Substring(1); + name = name[1..]; } if (name.Length > 128) - name = name.Substring(0, 128); + { + name = name[..128]; + } return name; } - private static HashSet _reservedNames = new HashSet(StringComparer.OrdinalIgnoreCase) + private static readonly HashSet _reservedNames = new(StringComparer.OrdinalIgnoreCase) { nameof(ContentItem.Id), nameof(ContentItem.ContentItemId), @@ -189,7 +193,7 @@ public static string ToSafeName(this string name) nameof(ContentItem.CreatedUtc), nameof(ContentItem.Owner), nameof(ContentItem.Author), - nameof(ContentItem.DisplayText) + nameof(ContentItem.DisplayText), }; public static bool IsReservedContentName(this string name) @@ -217,12 +221,12 @@ public static bool IsSpace(this char c) public static string RemoveDiacritics(this string name) { - string stFormD = name.Normalize(NormalizationForm.FormD); + var stFormD = name.Normalize(NormalizationForm.FormD); var sb = new StringBuilder(); - foreach (char t in stFormD) + foreach (var t in stFormD) { - UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(t); + var uc = CharUnicodeInfo.GetUnicodeCategory(t); if (uc != UnicodeCategory.NonSpacingMark) { sb.Append(t); @@ -234,7 +238,7 @@ public static string RemoveDiacritics(this string name) public static string Strip(this string subject, params char[] stripped) { - if (stripped == null || stripped.Length == 0 || string.IsNullOrEmpty(subject)) + if (stripped == null || stripped.Length == 0 || String.IsNullOrEmpty(subject)) { return subject; } @@ -244,7 +248,7 @@ public static string Strip(this string subject, params char[] stripped) var cursor = 0; for (var i = 0; i < subject.Length; i++) { - char current = subject[i]; + var current = subject[i]; if (Array.IndexOf(stripped, current) < 0) { result[cursor++] = current; @@ -261,7 +265,7 @@ public static string Strip(this string subject, Func predicate) var cursor = 0; for (var i = 0; i < subject.Length; i++) { - char current = subject[i]; + var current = subject[i]; if (!predicate(current)) { result[cursor++] = current; @@ -273,14 +277,14 @@ public static string Strip(this string subject, Func predicate) public static bool Any(this string subject, params char[] chars) { - if (string.IsNullOrEmpty(subject) || chars == null || chars.Length == 0) + if (String.IsNullOrEmpty(subject) || chars == null || chars.Length == 0) { return false; } for (var i = 0; i < subject.Length; i++) { - char current = subject[i]; + var current = subject[i]; if (Array.IndexOf(chars, current) >= 0) { return true; @@ -292,7 +296,7 @@ public static bool Any(this string subject, params char[] chars) public static bool All(this string subject, params char[] chars) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { return true; } @@ -304,7 +308,7 @@ public static bool All(this string subject, params char[] chars) for (var i = 0; i < subject.Length; i++) { - char current = subject[i]; + var current = subject[i]; if (Array.IndexOf(chars, current) < 0) { return false; @@ -316,14 +320,19 @@ public static bool All(this string subject, params char[] chars) public static string Translate(this string subject, char[] from, char[] to) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { return subject; } - if (from == null || to == null) + if (from == null) + { + throw new ArgumentNullException(nameof(from)); + } + + if (to == null) { - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(to)); } if (from.Length != to.Length) @@ -357,7 +366,7 @@ public static string Translate(this string subject, char[] from, char[] to) public static string ReplaceAll(this string original, IDictionary replacements) { - var pattern = $"{string.Join("|", replacements.Keys)}"; + var pattern = $"{String.Join("|", replacements.Keys)}"; return Regex.Replace(original, pattern, match => replacements[match.Value]); } @@ -367,13 +376,13 @@ public static string TrimEnd(this string rough, string trim = "") return null; return rough.EndsWith(trim, StringComparison.Ordinal) - ? rough.Substring(0, rough.Length - trim.Length) + ? rough[..^trim.Length] : rough; } public static string ReplaceLastOccurrence(this string source, string find, string replace) { - int place = source.LastIndexOf(find, StringComparison.Ordinal); + var place = source.LastIndexOf(find, StringComparison.Ordinal); return source.Remove(place, find.Length).Insert(place, replace); } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentDisplayOptions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentDisplayOptions.cs index 09809d7e498..0231951d330 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentDisplayOptions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentDisplayOptions.cs @@ -6,8 +6,8 @@ namespace OrchardCore.ContentManagement.Display.ContentDisplay { public class ContentDisplayOptions { - private readonly List _contentParts = new List(); - private readonly List _contentFields = new List(); + private readonly List _contentParts = new(); + private readonly List _contentFields = new(); private Dictionary _contentPartOptions; public IReadOnlyDictionary ContentPartOptions => _contentPartOptions ??= _contentParts.ToDictionary(k => k.Type.Name); diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayOption.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayOption.cs index 439da7217d0..d640ff2c15f 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayOption.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayOption.cs @@ -6,7 +6,7 @@ namespace OrchardCore.ContentManagement.Display.ContentDisplay { public class ContentFieldDisplayOption : ContentFieldOptionBase { - private readonly List _fieldDisplayDrivers = new List(); + private readonly List _fieldDisplayDrivers = new(); public ContentFieldDisplayOption(Type contentFieldType) : base(contentFieldType) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayOption.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayOption.cs index a7bd3902c3a..70bf674d3eb 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayOption.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentPartDisplayOption.cs @@ -6,7 +6,7 @@ namespace OrchardCore.ContentManagement.Display.ContentDisplay { public class ContentPartDisplayOption : ContentPartOptionBase { - private readonly List _partDisplayDrivers = new List(); + private readonly List _partDisplayDrivers = new(); public ContentPartDisplayOption(Type contentPartType) : base(contentPartType) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentItemDisplayManager.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentItemDisplayManager.cs index ddd58acb4ac..bcff6ee12e6 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentItemDisplayManager.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/ContentItemDisplayManager.cs @@ -56,12 +56,8 @@ public async Task BuildDisplayAsync(ContentItem contentItem, IUpdateMode throw new ArgumentNullException(nameof(contentItem)); } - var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType); - - if (contentTypeDefinition == null) - { - throw new NullReferenceException($"Content Type {contentItem.ContentType} does not exist."); - } + var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType) + ?? throw new NullReferenceException($"Content Type {contentItem.ContentType} does not exist."); var actualDisplayType = String.IsNullOrEmpty(displayType) ? "Detail" : displayType; var hasStereotype = contentTypeDefinition.TryGetStereotype(out var stereotype); @@ -132,12 +128,8 @@ public async Task BuildEditorAsync(ContentItem contentItem, IUpdateModel throw new ArgumentNullException(nameof(contentItem)); } - var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType); - - if (contentTypeDefinition == null) - { - throw new NullReferenceException($"Content Type {contentItem.ContentType} does not exist."); - } + var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType) + ?? throw new NullReferenceException($"Content Type {contentItem.ContentType} does not exist."); var hasStereotype = contentTypeDefinition.TryGetStereotype(out var stereotype); var actualShapeType = "Content_Edit"; @@ -187,12 +179,8 @@ public async Task UpdateEditorAsync(ContentItem contentItem, IUpdateMode throw new ArgumentNullException(nameof(contentItem)); } - var contentTypeDefinition = _contentDefinitionManager.LoadTypeDefinition(contentItem.ContentType); - - if (contentTypeDefinition == null) - { - throw new NullReferenceException($"Content Type {contentItem.ContentType} does not exist."); - } + var contentTypeDefinition = _contentDefinitionManager.LoadTypeDefinition(contentItem.ContentType) + ?? throw new NullReferenceException($"Content Type {contentItem.ContentType} does not exist."); var hasStereotype = contentTypeDefinition.TryGetStereotype(out var stereotype); var actualShapeType = "Content_Edit"; diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/Placement/ContentPlacementNodeFilterProviders.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/Placement/ContentPlacementNodeFilterProviders.cs index 4a65d1214d7..1c26e743b33 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/Placement/ContentPlacementNodeFilterProviders.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/Placement/ContentPlacementNodeFilterProviders.cs @@ -59,7 +59,7 @@ public bool IsMatch(ShapePlacementContext context, JToken expression) { if (ct.EndsWith('*')) { - var prefix = ct.Substring(0, ct.Length - 1); + var prefix = ct[..^1]; return (contentItem.ContentType ?? "").StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || (GetStereotype(context) ?? "").StartsWith(prefix, StringComparison.OrdinalIgnoreCase); } @@ -68,7 +68,7 @@ public bool IsMatch(ShapePlacementContext context, JToken expression) }); } - private string GetStereotype(ShapePlacementContext context) + private static string GetStereotype(ShapePlacementContext context) { var shape = context.ZoneShape as Shape; object stereotypeVal = null; @@ -79,13 +79,13 @@ private string GetStereotype(ShapePlacementContext context) public class ContentPlacementParseFilterProviderBase { - protected bool HasContent(ShapePlacementContext context) + protected static bool HasContent(ShapePlacementContext context) { var shape = context.ZoneShape as Shape; return shape != null && shape.TryGetProperty("ContentItem", out object contentItem) && contentItem != null; } - protected ContentItem GetContent(ShapePlacementContext context) + protected static ContentItem GetContent(ShapePlacementContext context) { if (!HasContent(context)) { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.Display/Razor/OrchardRazorHelperExtensions.cs b/src/OrchardCore/OrchardCore.ContentManagement.Display/Razor/OrchardRazorHelperExtensions.cs index a4d4763c4be..94e317bba16 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.Display/Razor/OrchardRazorHelperExtensions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.Display/Razor/OrchardRazorHelperExtensions.cs @@ -11,7 +11,9 @@ using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Razor; +#pragma warning disable CA1050 // Declare types in namespaces 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) { @@ -67,22 +69,22 @@ public static IHtmlContent ConsoleLog(this IOrchardHelper orchardHelper, object internal static JObject ConvertContentItem(ContentItem contentItem) { - var o = new JObject(); - - // Write all well-known properties - o.Add(new JProperty(nameof(ContentItem.ContentItemId), contentItem.ContentItemId)); - o.Add(new JProperty(nameof(ContentItem.ContentItemVersionId), contentItem.ContentItemVersionId)); - o.Add(new JProperty(nameof(ContentItem.ContentType), contentItem.ContentType)); - o.Add(new JProperty(nameof(ContentItem.DisplayText), contentItem.DisplayText)); - o.Add(new JProperty(nameof(ContentItem.Latest), contentItem.Latest)); - o.Add(new JProperty(nameof(ContentItem.Published), contentItem.Published)); - o.Add(new JProperty(nameof(ContentItem.ModifiedUtc), contentItem.ModifiedUtc)); - o.Add(new JProperty(nameof(ContentItem.PublishedUtc), contentItem.PublishedUtc)); - o.Add(new JProperty(nameof(ContentItem.CreatedUtc), contentItem.CreatedUtc)); - o.Add(new JProperty(nameof(ContentItem.Owner), contentItem.Owner)); - o.Add(new JProperty(nameof(ContentItem.Author), contentItem.Author)); - - o.Add(new JProperty(nameof(ContentItem.Content), (JObject)contentItem.Content)); + var o = new JObject + { + // Write all well-known properties. + new JProperty(nameof(ContentItem.ContentItemId), contentItem.ContentItemId), + new JProperty(nameof(ContentItem.ContentItemVersionId), contentItem.ContentItemVersionId), + new JProperty(nameof(ContentItem.ContentType), contentItem.ContentType), + new JProperty(nameof(ContentItem.DisplayText), contentItem.DisplayText), + new JProperty(nameof(ContentItem.Latest), contentItem.Latest), + new JProperty(nameof(ContentItem.Published), contentItem.Published), + new JProperty(nameof(ContentItem.ModifiedUtc), contentItem.ModifiedUtc), + new JProperty(nameof(ContentItem.PublishedUtc), contentItem.PublishedUtc), + new JProperty(nameof(ContentItem.CreatedUtc), contentItem.CreatedUtc), + new JProperty(nameof(ContentItem.Owner), contentItem.Owner), + new JProperty(nameof(ContentItem.Author), contentItem.Author), + new JProperty(nameof(ContentItem.Content), (JObject)contentItem.Content), + }; return o; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Permissions.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Permissions.cs index 933438e2d24..bd24695fce0 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Permissions.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Permissions.cs @@ -7,13 +7,13 @@ namespace OrchardCore.ContentManagement.GraphQL { public class Permissions : IPermissionProvider { - public static readonly Permission ApiViewContent = new Permission("ApiViewContent", "Access view content endpoints"); + public static readonly Permission ApiViewContent = new("ApiViewContent", "Access view content endpoints"); public Task> GetPermissionsAsync() { return Task.FromResult(new[] { - ApiViewContent + ApiViewContent, } .AsEnumerable()); } @@ -21,28 +21,35 @@ public Task> GetPermissionsAsync() public IEnumerable GetDefaultStereotypes() { return new[] { - new PermissionStereotype { + new PermissionStereotype + { Name = "Administrator", Permissions = new[] { ApiViewContent } }, - new PermissionStereotype { + new PermissionStereotype + { Name = "Editor" }, - new PermissionStereotype { + new PermissionStereotype + { Name = "Moderator" }, - new PermissionStereotype { + new PermissionStereotype + { Name = "Author" }, - new PermissionStereotype { + new PermissionStereotype + { Name = "Contributor" }, - new PermissionStereotype { + new PermissionStereotype + { Name = "Authenticated" }, - new PermissionStereotype { + new PermissionStereotype + { Name = "Anonymous" - } + }, }; } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemQuery.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemQuery.cs index 2853846f87b..5e0bbaeb997 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemQuery.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemQuery.cs @@ -14,7 +14,7 @@ namespace OrchardCore.ContentManagement.GraphQL.Queries public class ContentItemQuery : ISchemaBuilder { private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IStringLocalizer S; + protected readonly IStringLocalizer S; public ContentItemQuery(IHttpContextAccessor httpContextAccessor, IStringLocalizer localizer) diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemsFieldType.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemsFieldType.cs index 17aca956fd6..d13ee2ccd3b 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemsFieldType.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentItemsFieldType.cs @@ -21,20 +21,20 @@ namespace OrchardCore.ContentManagement.GraphQL.Queries { /// - /// This type is used by to represent a query on a content type + /// This type is used by to represent a query on a content type. /// public class ContentItemsFieldType : FieldType { - private static readonly List ContentItemProperties; + private static readonly List _contentItemProperties; private readonly int _defaultNumberOfItems; static ContentItemsFieldType() { - ContentItemProperties = new List(); + _contentItemProperties = new List(); foreach (var property in typeof(ContentItemIndex).GetProperties()) { - ContentItemProperties.Add(property.Name); + _contentItemProperties.Add(property.Name); } } @@ -76,7 +76,7 @@ private async Task> Resolve(IResolveFieldContext contex JObject where = null; if (context.HasArgument("where")) { - // context.Arguments[].Value is never null in GraphQL.NET 4 + // 'context.Arguments[].Value' is never null in GraphQL.NET 4. where = JObject.FromObject(context.Arguments["where"].Value); } @@ -121,17 +121,17 @@ private async Task> Resolve(IResolveFieldContext contex return query; } - string defaultTableAlias = query.GetTypeAlias(typeof(ContentItemIndex)); + var defaultTableAlias = query.GetTypeAlias(typeof(ContentItemIndex)); IPredicateQuery predicateQuery = new PredicateQuery( configuration: session.Store.Configuration, propertyProviders: fieldContext.RequestServices.GetServices()); - // Create the default table alias + // Create the default table alias. predicateQuery.CreateAlias("", nameof(ContentItemIndex)); predicateQuery.CreateTableAlias(nameof(ContentItemIndex), defaultTableAlias); - // Add all provided table alias to the current predicate query + // Add all provided table alias to the current predicate query. var providers = fieldContext.RequestServices.GetServices(); var indexes = new Dictionary(StringComparer.OrdinalIgnoreCase); var indexAliases = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -153,16 +153,15 @@ private async Task> Resolve(IResolveFieldContext contex BuildWhereExpressions(where, expressions, null, fieldContext, indexAliases); expressions.SearchUsedAlias(predicateQuery); - // Add all Indexes that were used in the predicate query - + // Add all Indexes that were used in the predicate query. IQuery contentQuery = query; foreach (var usedAlias in predicateQuery.GetUsedAliases()) { - if (indexes.ContainsKey(usedAlias)) + if (indexes.TryGetValue(usedAlias, out var indexAlias)) { - contentQuery = contentQuery.With(indexes[usedAlias].IndexType); - var tableAlias = query.GetTypeAlias(indexes[usedAlias].IndexType); - predicateQuery.CreateTableAlias(indexes[usedAlias].Index, tableAlias); + contentQuery = contentQuery.With(indexAlias.IndexType); + var tableAlias = query.GetTypeAlias(indexAlias.IndexType); + predicateQuery.CreateTableAlias(indexAlias.Index, tableAlias); } } @@ -171,7 +170,7 @@ private async Task> Resolve(IResolveFieldContext contex query = query.Where(whereSqlClause); - // Add all parameters that were used in the predicate query + // Add all parameters that were used in the predicate query. foreach (var parameter in predicateQuery.Parameters) { query = query.WithParameter(parameter.Key, parameter.Value); @@ -201,16 +200,16 @@ private IQuery PageQuery(IQuery contentItemsQuery, IRe return contentItemsQuery; } - private VersionOptions GetVersionOption(PublicationStatusEnum status) + private static VersionOptions GetVersionOption(PublicationStatusEnum status) { - switch (status) + return status switch { - case PublicationStatusEnum.Published: return VersionOptions.Published; - case PublicationStatusEnum.Draft: return VersionOptions.Draft; - case PublicationStatusEnum.Latest: return VersionOptions.Latest; - case PublicationStatusEnum.All: return VersionOptions.AllVersions; - default: return VersionOptions.Published; - } + PublicationStatusEnum.Published => VersionOptions.Published, + PublicationStatusEnum.Draft => VersionOptions.Draft, + PublicationStatusEnum.Latest => VersionOptions.Latest, + PublicationStatusEnum.All => VersionOptions.AllVersions, + _ => VersionOptions.Published, + }; } private static IQuery FilterContentType(IQuery query, IResolveFieldContext context) @@ -264,7 +263,7 @@ private void BuildExpressionsInternal(JObject where, Junction expressions, strin { foreach (var entry in where.Properties()) { - // new typed arguments return default null values + // New typed arguments return default null values. if (entry.Value.Type == JTokenType.Undefined || entry.Value.Type == JTokenType.Null) { continue; @@ -277,7 +276,7 @@ private void BuildExpressionsInternal(JObject where, Junction expressions, strin // Gets the full path name without the comparison e.g. aliasPart.alias, not aliasPart.alias_contains. var property = values[0]; - // figure out table aliases for collapsed parts and ones with the part suffix removed by the dsl + // Figure out table aliases for collapsed parts and ones with the part suffix removed by the dsl. if (tableAlias == null || !tableAlias.EndsWith("Part", StringComparison.OrdinalIgnoreCase)) { var whereArgument = fieldContext?.FieldDefinition.Arguments.FirstOrDefault(x => x.Name == "where"); @@ -306,17 +305,17 @@ private void BuildExpressionsInternal(JObject where, Junction expressions, strin if (values.Length == 1) { - if (string.Equals(values[0], "or", StringComparison.OrdinalIgnoreCase)) + if (String.Equals(values[0], "or", StringComparison.OrdinalIgnoreCase)) { expression = Expression.Disjunction(); BuildWhereExpressions(entry.Value, (Junction)expression, tableAlias, fieldContext, indexAliases); } - else if (string.Equals(values[0], "and", StringComparison.OrdinalIgnoreCase)) + else if (String.Equals(values[0], "and", StringComparison.OrdinalIgnoreCase)) { expression = Expression.Conjunction(); BuildWhereExpressions(entry.Value, (Junction)expression, tableAlias, fieldContext, indexAliases); } - else if (string.Equals(values[0], "not", StringComparison.OrdinalIgnoreCase)) + else if (String.Equals(values[0], "not", StringComparison.OrdinalIgnoreCase)) { expression = Expression.Conjunction(); BuildWhereExpressions(entry.Value, (Junction)expression, tableAlias, fieldContext, indexAliases); @@ -338,24 +337,23 @@ private void BuildExpressionsInternal(JObject where, Junction expressions, strin { var value = entry.Value.ToObject(); - switch (values[1]) + expression = values[1] switch { - case "not": expression = Expression.Not(Expression.Equal(property, value)); break; - case "gt": expression = Expression.GreaterThan(property, value); break; - case "gte": expression = Expression.GreaterThanOrEqual(property, value); break; - case "lt": expression = Expression.LessThan(property, value); break; - case "lte": expression = Expression.LessThanOrEqual(property, value); break; - case "contains": expression = Expression.Like(property, (string)value, MatchOptions.Contains); break; - case "not_contains": expression = Expression.Not(Expression.Like(property, (string)value, MatchOptions.Contains)); break; - case "starts_with": expression = Expression.Like(property, (string)value, MatchOptions.StartsWith); break; - case "not_starts_with": expression = Expression.Not(Expression.Like(property, (string)value, MatchOptions.StartsWith)); break; - case "ends_with": expression = Expression.Like(property, (string)value, MatchOptions.EndsWith); break; - case "not_ends_with": expression = Expression.Not(Expression.Like(property, (string)value, MatchOptions.EndsWith)); break; - case "in": expression = Expression.In(property, entry.Value.ToObject()); break; - case "not_in": expression = Expression.Not(Expression.In(property, entry.Value.ToObject())); break; - - default: expression = Expression.Equal(property, value); break; - } + "not" => Expression.Not(Expression.Equal(property, value)), + "gt" => Expression.GreaterThan(property, value), + "gte" => Expression.GreaterThanOrEqual(property, value), + "lt" => Expression.LessThan(property, value), + "lte" => Expression.LessThanOrEqual(property, value), + "contains" => Expression.Like(property, (string)value, MatchOptions.Contains), + "not_contains" => Expression.Not(Expression.Like(property, (string)value, MatchOptions.Contains)), + "starts_with" => Expression.Like(property, (string)value, MatchOptions.StartsWith), + "not_starts_with" => Expression.Not(Expression.Like(property, (string)value, MatchOptions.StartsWith)), + "ends_with" => Expression.Like(property, (string)value, MatchOptions.EndsWith), + "not_ends_with" => Expression.Not(Expression.Like(property, (string)value, MatchOptions.EndsWith)), + "in" => Expression.In(property, entry.Value.ToObject()), + "not_in" => Expression.Not(Expression.In(property, entry.Value.ToObject())), + _ => Expression.Equal(property, value), + }; } if (expression != null) @@ -365,7 +363,7 @@ private void BuildExpressionsInternal(JObject where, Junction expressions, strin } } - private IQuery OrderBy(IQuery query, + private static IQuery OrderBy(IQuery query, IResolveFieldContext context) { if (context.HasPopulatedArgument("orderBy")) diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentTypeQuery.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentTypeQuery.cs index 5a2e0714a45..82a498ec9ab 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentTypeQuery.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/ContentTypeQuery.cs @@ -21,7 +21,7 @@ public class ContentTypeQuery : ISchemaBuilder private readonly IHttpContextAccessor _httpContextAccessor; private readonly IOptions _contentOptionsAccessor; private readonly IOptions _settingsAccessor; - private readonly IStringLocalizer S; + protected readonly IStringLocalizer S; public ContentTypeQuery(IHttpContextAccessor httpContextAccessor, IOptions contentOptionsAccessor, diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexPropertyProvider.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexPropertyProvider.cs index 26471618adf..c2eec78ffc9 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexPropertyProvider.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/IndexPropertyProvider.cs @@ -7,8 +7,8 @@ namespace OrchardCore.ContentManagement.GraphQL.Queries { public class IndexPropertyProvider : IIndexPropertyProvider where T : MapIndex { - private static Dictionary _indexProperties = new Dictionary(StringComparer.OrdinalIgnoreCase); - private static string _indexName; + private static readonly Dictionary _indexProperties = new(StringComparer.OrdinalIgnoreCase); + private static readonly string _indexName; static IndexPropertyProvider() { diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/ContentItemType.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/ContentItemType.cs index f30183fe8a0..5dcc245cf10 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/ContentItemType.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/ContentItemType.cs @@ -65,7 +65,7 @@ private bool IsContentType(object obj) public override FieldType AddField(FieldType fieldType) { - if (!_options.ShouldSkip(this.GetType(), fieldType.Name)) + if (!_options.ShouldSkip(GetType(), fieldType.Name)) { return base.AddField(fieldType); } diff --git a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/DynamicContentTypeBuilder.cs b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/DynamicContentTypeBuilder.cs index 88f906f2e8c..b8fb8d9e79c 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/DynamicContentTypeBuilder.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/DynamicContentTypeBuilder.cs @@ -14,7 +14,7 @@ public class DynamicContentTypeBuilder : IContentTypeBuilder { private readonly IHttpContextAccessor _httpContextAccessor; private readonly GraphQLContentOptions _contentOptions; - private readonly IStringLocalizer S; + protected readonly IStringLocalizer S; private readonly Dictionary _dynamicPartFields; public DynamicContentTypeBuilder(IHttpContextAccessor httpContextAccessor, diff --git a/src/OrchardCore/OrchardCore.ContentManagement/ContentFieldFactory.cs b/src/OrchardCore/OrchardCore.ContentManagement/ContentFieldFactory.cs index 66d8d26287d..2b7a7b30a6c 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/ContentFieldFactory.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/ContentFieldFactory.cs @@ -10,7 +10,7 @@ namespace OrchardCore.ContentManagement /// public class ContentFieldFactory : ITypeActivatorFactory { - private readonly ITypeActivator ContentFieldActivator = new GenericTypeActivator(); + private readonly ITypeActivator _contentFieldActivator = new GenericTypeActivator(); private readonly Dictionary> _contentFieldActivators; @@ -35,7 +35,7 @@ public ITypeActivator GetTypeActivator(string fieldName) return activator; } - return ContentFieldActivator; + return _contentFieldActivator; } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement/ContentPartFactory.cs b/src/OrchardCore/OrchardCore.ContentManagement/ContentPartFactory.cs index 9762d24a3a9..e3d157708ff 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/ContentPartFactory.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/ContentPartFactory.cs @@ -10,7 +10,7 @@ namespace OrchardCore.ContentManagement /// public class ContentPartFactory : ITypeActivatorFactory { - private readonly ITypeActivator ContentPartActivator = new GenericTypeActivator(); + private readonly ITypeActivator _contentPartActivator = new GenericTypeActivator(); private readonly Dictionary> _contentPartActivators; @@ -35,7 +35,7 @@ public ITypeActivator GetTypeActivator(string partName) return activator; } - return ContentPartActivator; + return _contentPartActivator; } } } diff --git a/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManager.cs b/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManager.cs index 5327e4a105f..3312e9d87f8 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManager.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManager.cs @@ -55,10 +55,7 @@ public class DefaultContentManager : IContentManager public async Task NewAsync(string contentType) { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentType); - if (contentTypeDefinition == null) - { - contentTypeDefinition = new ContentTypeDefinitionBuilder().Named(contentType).Build(); - } + contentTypeDefinition ??= new ContentTypeDefinitionBuilder().Named(contentType).Build(); // Create a new kernel for the model instance. var context = new ActivatingContentContext(new ContentItem() { ContentType = contentTypeDefinition.Name }) @@ -516,14 +513,15 @@ protected async Task BuildNewVersionAsync(ContentItem existingConte // We are not invoking NewAsync as we are cloning an existing item // This will also prevent the Elements (parts) from being allocated unnecessarily - var buildingContentItem = new ContentItem(); - - buildingContentItem.ContentType = existingContentItem.ContentType; - buildingContentItem.ContentItemId = existingContentItem.ContentItemId; - buildingContentItem.ContentItemVersionId = _idGenerator.GenerateUniqueId(existingContentItem); - buildingContentItem.DisplayText = existingContentItem.DisplayText; - buildingContentItem.Latest = true; - buildingContentItem.Data = new JObject(existingContentItem.Data); + var buildingContentItem = new ContentItem + { + ContentType = existingContentItem.ContentType, + ContentItemId = existingContentItem.ContentItemId, + ContentItemVersionId = _idGenerator.GenerateUniqueId(existingContentItem), + DisplayText = existingContentItem.DisplayText, + Latest = true, + Data = new JObject(existingContentItem.Data), + }; var context = new VersionContentContext(existingContentItem, buildingContentItem); @@ -579,7 +577,7 @@ protected async Task> BuildNewVersionsAsync(IEnumerable ContentItemVersionId = _idGenerator.GenerateUniqueId(existingContentItem), DisplayText = existingContentItem.DisplayText, Latest = true, - Data = new JObject(existingContentItem.Data) + Data = new JObject(existingContentItem.Data), }; var context = new VersionContentContext(existingContentItem, buildingContentItem); @@ -703,10 +701,10 @@ 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)); + throw new ValidationException(String.Join(", ", result.Errors)); } // Imported handlers will only be fired if the validation has been successful. @@ -754,10 +752,10 @@ 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)); + throw new ValidationException(String.Join(", ", result.Errors)); } // Imported handlers will only be fired if the validation has been successful. @@ -926,7 +924,7 @@ private async Task CreateContentItemVersionAsync(ContentI if (String.IsNullOrEmpty(contentItem.ContentItemId)) { // NewAsync should be used to create new content items. - throw new ArgumentNullException(nameof(ContentItem.ContentItemId)); + throw new InvalidOperationException($"The content item is missing a '{nameof(ContentItem.ContentItemId)}'."); } // Initializes the Id as it could be interpreted as an updated object when added back to YesSql diff --git a/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManagerSession.cs b/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManagerSession.cs index 7804512b5cd..a4a31daf4e8 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManagerSession.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/DefaultContentManagerSession.cs @@ -4,8 +4,8 @@ namespace OrchardCore.ContentManagement { public class DefaultContentManagerSession : IContentManagerSession { - private readonly Dictionary _itemByVersionId = new Dictionary(); - private readonly Dictionary _publishedItemsById = new Dictionary(); + private readonly Dictionary _itemByVersionId = new(); + private readonly Dictionary _publishedItemsById = new(); private bool _hasItems; diff --git a/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentsHandler.cs b/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentsHandler.cs index a63f10d8be0..03115b95878 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentsHandler.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentsHandler.cs @@ -80,7 +80,6 @@ public override Task PublishingAsync(PublishContentContext context) public override Task UnpublishedAsync(PublishContentContext context) { - var utcNow = _clock.UtcNow; context.ContentItem.PublishedUtc = null; return Task.CompletedTask; } diff --git a/src/OrchardCore/OrchardCore.ContentManagement/Records/ContentItemIndex.cs b/src/OrchardCore/OrchardCore.ContentManagement/Records/ContentItemIndex.cs index d40cc3592b7..b219fb29abf 100644 --- a/src/OrchardCore/OrchardCore.ContentManagement/Records/ContentItemIndex.cs +++ b/src/OrchardCore/OrchardCore.ContentManagement/Records/ContentItemIndex.cs @@ -50,22 +50,22 @@ public override void Describe(DescribeContext context) if (contentItemIndex.ContentType?.Length > ContentItemIndex.MaxContentTypeSize) { - contentItemIndex.ContentType = contentItem.ContentType.Substring(0, ContentItemIndex.MaxContentTypeSize); + contentItemIndex.ContentType = contentItem.ContentType[..ContentItemIndex.MaxContentTypeSize]; } if (contentItemIndex.Owner?.Length > ContentItemIndex.MaxOwnerSize) { - contentItemIndex.Owner = contentItem.Owner.Substring(0, ContentItemIndex.MaxOwnerSize); + contentItemIndex.Owner = contentItem.Owner[..ContentItemIndex.MaxOwnerSize]; } if (contentItemIndex.Author?.Length > ContentItemIndex.MaxAuthorSize) { - contentItemIndex.Author = contentItem.Author.Substring(0, ContentItemIndex.MaxAuthorSize); + contentItemIndex.Author = contentItem.Author[..ContentItemIndex.MaxAuthorSize]; } if (contentItemIndex.DisplayText?.Length > ContentItemIndex.MaxDisplayTextSize) { - contentItemIndex.DisplayText = contentItem.DisplayText.Substring(0, ContentItemIndex.MaxDisplayTextSize); + contentItemIndex.DisplayText = contentItem.DisplayText[..ContentItemIndex.MaxDisplayTextSize]; } return contentItemIndex; diff --git a/src/OrchardCore/OrchardCore.Contents.Core/ContentTypePermissionsHelper.cs b/src/OrchardCore/OrchardCore.Contents.Core/ContentTypePermissionsHelper.cs index e3950353648..d8094d7ac46 100644 --- a/src/OrchardCore/OrchardCore.Contents.Core/ContentTypePermissionsHelper.cs +++ b/src/OrchardCore/OrchardCore.Contents.Core/ContentTypePermissionsHelper.cs @@ -12,40 +12,40 @@ namespace OrchardCore.Contents.Security /// public class ContentTypePermissionsHelper { - private static readonly Permission PublishContent = new("Publish_{0}", "Publish or unpublish {0} for others", new[] { CommonPermissions.PublishContent }); - private static readonly Permission PublishOwnContent = new("PublishOwn_{0}", "Publish or unpublish {0}", new[] { PublishContent, CommonPermissions.PublishOwnContent }); - private static readonly Permission EditContent = new("Edit_{0}", "Edit {0} for others", new[] { PublishContent, CommonPermissions.EditContent }); - private static readonly Permission EditOwnContent = new("EditOwn_{0}", "Edit {0}", new[] { EditContent, PublishOwnContent, CommonPermissions.EditOwnContent }); - private static readonly Permission DeleteContent = new("Delete_{0}", "Delete {0} for others", new[] { CommonPermissions.DeleteContent }); - private static readonly Permission DeleteOwnContent = new("DeleteOwn_{0}", "Delete {0}", new[] { DeleteContent, CommonPermissions.DeleteOwnContent }); - private static readonly Permission ViewContent = new("View_{0}", "View {0} by others", new[] { EditContent, CommonPermissions.ViewContent }); - private static readonly Permission ViewOwnContent = new("ViewOwn_{0}", "View own {0}", new[] { ViewContent, CommonPermissions.ViewOwnContent }); - private static readonly Permission PreviewContent = new("Preview_{0}", "Preview {0} by others", new[] { EditContent, CommonPermissions.PreviewContent }); - private static readonly Permission PreviewOwnContent = new("PreviewOwn_{0}", "Preview own {0}", new[] { PreviewContent, CommonPermissions.PreviewOwnContent }); - private static readonly Permission CloneContent = new("Clone_{0}", "Clone {0} by others", new[] { EditContent, CommonPermissions.CloneContent }); - private static readonly Permission CloneOwnContent = new("CloneOwn_{0}", "Clone own {0}", new[] { CloneContent, CommonPermissions.CloneOwnContent }); - 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 }); + private static readonly Permission _publishContent = new("Publish_{0}", "Publish or unpublish {0} for others", new[] { CommonPermissions.PublishContent }); + private static readonly Permission _publishOwnContent = new("PublishOwn_{0}", "Publish or unpublish {0}", new[] { _publishContent, CommonPermissions.PublishOwnContent }); + private static readonly Permission _editContent = new("Edit_{0}", "Edit {0} for others", new[] { _publishContent, CommonPermissions.EditContent }); + private static readonly Permission _editOwnContent = new("EditOwn_{0}", "Edit {0}", new[] { _editContent, _publishOwnContent, CommonPermissions.EditOwnContent }); + private static readonly Permission _deleteContent = new("Delete_{0}", "Delete {0} for others", new[] { CommonPermissions.DeleteContent }); + private static readonly Permission _deleteOwnContent = new("DeleteOwn_{0}", "Delete {0}", new[] { _deleteContent, CommonPermissions.DeleteOwnContent }); + private static readonly Permission _viewContent = new("View_{0}", "View {0} by others", new[] { _editContent, CommonPermissions.ViewContent }); + private static readonly Permission _viewOwnContent = new("ViewOwn_{0}", "View own {0}", new[] { _viewContent, CommonPermissions.ViewOwnContent }); + private static readonly Permission _previewContent = new("Preview_{0}", "Preview {0} by others", new[] { _editContent, CommonPermissions.PreviewContent }); + private static readonly Permission _previewOwnContent = new("PreviewOwn_{0}", "Preview own {0}", new[] { _previewContent, CommonPermissions.PreviewOwnContent }); + private static readonly Permission _cloneContent = new("Clone_{0}", "Clone {0} by others", new[] { _editContent, CommonPermissions.CloneContent }); + private static readonly Permission _cloneOwnContent = new("CloneOwn_{0}", "Clone own {0}", new[] { _cloneContent, CommonPermissions.CloneOwnContent }); + 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 }, + { 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 Dictionary, Permission> PermissionsByType = new(); + private static Dictionary, Permission> _permissionsByType = new(); /// /// Returns a dynamic permission for a content type, based on a global content permission template @@ -92,7 +92,7 @@ public static Permission CreateDynamicPermission(Permission template, string con var key = new ValueTuple(template.Name, contentType); - if (PermissionsByType.TryGetValue(key, out var permission)) + if (_permissionsByType.TryGetValue(key, out var permission)) { return permission; } @@ -103,11 +103,12 @@ public static Permission CreateDynamicPermission(Permission template, string con (template.ImpliedBy ?? Array.Empty()).Select(t => CreateDynamicPermission(t, contentType)) ); - var localPermissions = new Dictionary, Permission>(PermissionsByType) + var localPermissions = new Dictionary, Permission>(_permissionsByType) { - [key] = permission + [key] = permission, }; - PermissionsByType = localPermissions; + + _permissionsByType = localPermissions; return permission; } diff --git a/src/OrchardCore/OrchardCore.Contents.TagHelpers/ContentLinkTagHelper.cs b/src/OrchardCore/OrchardCore.Contents.TagHelpers/ContentLinkTagHelper.cs index 9be51dd6790..7dca66fc163 100644 --- a/src/OrchardCore/OrchardCore.Contents.TagHelpers/ContentLinkTagHelper.cs +++ b/src/OrchardCore/OrchardCore.Contents.TagHelpers/ContentLinkTagHelper.cs @@ -85,7 +85,7 @@ public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHe contentItem = DisplayFor; var previewAspect = await _contentManager.PopulateAspectAsync(contentItem); - if (!string.IsNullOrEmpty(previewAspect.PreviewUrl)) + if (!String.IsNullOrEmpty(previewAspect.PreviewUrl)) { var previewUrl = previewAspect.PreviewUrl; if (!previewUrl.StartsWith("~/", StringComparison.OrdinalIgnoreCase)) @@ -176,7 +176,7 @@ public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHe if (output.TagMode == TagMode.SelfClosing && metadata != null) { output.TagMode = TagMode.StartTagAndEndTag; - if (!string.IsNullOrEmpty(contentItem.DisplayText)) + if (!String.IsNullOrEmpty(contentItem.DisplayText)) { output.Content.Append(contentItem.DisplayText); } @@ -190,13 +190,13 @@ public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHe return; } - private void ApplyRouteValues(TagHelperContext tagHelperContext, RouteValueDictionary route) + private static void ApplyRouteValues(TagHelperContext tagHelperContext, RouteValueDictionary route) { foreach (var attribute in tagHelperContext.AllAttributes) { if (attribute.Name.StartsWith(RoutePrefix, StringComparison.OrdinalIgnoreCase)) { - route.Add(attribute.Name.Substring(RoutePrefix.Length), attribute.Value); + route.Add(attribute.Name[RoutePrefix.Length..], attribute.Value); } } } diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/Documents/DocumentStore.cs b/src/OrchardCore/OrchardCore.Data.YesSql/Documents/DocumentStore.cs index 198636e265a..2432ba6106e 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/Documents/DocumentStore.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/Documents/DocumentStore.cs @@ -12,10 +12,10 @@ public class DocumentStore : IDocumentStore { private readonly ISession _session; - private readonly Dictionary _loaded = new Dictionary(); + private readonly Dictionary _loaded = new(); - private readonly List _afterCommitsSuccess = new List(); - private readonly List _afterCommitsFailure = new List(); + private readonly List _afterCommitsSuccess = new(); + private readonly List _afterCommitsFailure = new(); private DocumentStoreCommitSuccessDelegate _afterCommitSuccess; private DocumentStoreCommitFailureDelegate _afterCommitFailure; diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/Migration/DataMigrationManager.cs b/src/OrchardCore/OrchardCore.Data.YesSql/Migration/DataMigrationManager.cs index 4473bd6dc72..53338ba9f52 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/Migration/DataMigrationManager.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/Migration/DataMigrationManager.cs @@ -107,10 +107,7 @@ public async Task Uninstall(string feature) var dataMigrationRecord = await GetDataMigrationRecordAsync(tempMigration); var uninstallMethod = GetUninstallMethod(migration); - if (uninstallMethod != null) - { - uninstallMethod.Invoke(migration, Array.Empty()); - } + uninstallMethod?.Invoke(migration, Array.Empty()); var uninstallAsyncMethod = GetUninstallAsyncMethod(migration); if (uninstallAsyncMethod != null) @@ -179,7 +176,7 @@ public async Task UpdateAsync(string featureId) if (dataMigrationRecord != null) { // This can be null if a failed create migration has occurred and the data migration record was saved. - current = dataMigrationRecord.Version.HasValue ? dataMigrationRecord.Version.Value : current; + current = dataMigrationRecord.Version ?? current; } else { @@ -293,7 +290,7 @@ private IEnumerable GetDataMigrations(string featureId) { var version = methodInfo.Name.EndsWith(asyncSuffix, StringComparison.Ordinal) ? methodInfo.Name.Substring(updateFromPrefix.Length, methodInfo.Name.Length - updateFromPrefix.Length - asyncSuffix.Length) - : methodInfo.Name.Substring(updateFromPrefix.Length); + : methodInfo.Name[updateFromPrefix.Length..]; if (Int32.TryParse(version, out var versionValue)) { diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/Options/SqliteOptionsConfiguration.cs b/src/OrchardCore/OrchardCore.Data.YesSql/Options/SqliteOptionsConfiguration.cs index 736e5964d3b..a01a6d747e1 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/Options/SqliteOptionsConfiguration.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/Options/SqliteOptionsConfiguration.cs @@ -6,7 +6,7 @@ namespace OrchardCore.Data { public class SqliteOptionsConfiguration : IConfigureOptions { - private static readonly bool DefaultUseConnectionPooling = true; + private static readonly bool _defaultUseConnectionPooling = true; private readonly IShellConfiguration _shellConfiguration; public SqliteOptionsConfiguration(IShellConfiguration shellConfiguration) @@ -18,7 +18,7 @@ public void Configure(SqliteOptions options) { var section = _shellConfiguration.GetSection("OrchardCore_Data_Sqlite"); - options.UseConnectionPooling = section.GetValue(nameof(options.UseConnectionPooling), DefaultUseConnectionPooling); + options.UseConnectionPooling = section.GetValue(nameof(options.UseConnectionPooling), _defaultUseConnectionPooling); } } } diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/PoolingJsonContentSerializer.cs b/src/OrchardCore/OrchardCore.Data.YesSql/PoolingJsonContentSerializer.cs index 25628a701ef..9e9b1961c91 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/PoolingJsonContentSerializer.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/PoolingJsonContentSerializer.cs @@ -11,7 +11,7 @@ namespace OrchardCore.Data /// internal sealed class PoolingJsonContentSerializer : IContentSerializer { - private static readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings + private static readonly JsonSerializerSettings _jsonSettings = new() { TypeNameHandling = TypeNameHandling.Auto, DateTimeZoneHandling = DateTimeZoneHandling.Utc, diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesInfo.cs b/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesInfo.cs index 7be62547fbd..121cdcb8d04 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesInfo.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesInfo.cs @@ -49,6 +49,7 @@ public ShellDbTablesInfo Configure(DbTransaction transaction, ILogger logger, bo Transaction = transaction; Connection = transaction.Connection; ThrowOnError = throwOnError; + _logger = logger; return this; } diff --git a/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesRemovingHandler.cs b/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesRemovingHandler.cs index d409b559d59..29d7fc1bba6 100644 --- a/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesRemovingHandler.cs +++ b/src/OrchardCore/OrchardCore.Data.YesSql/Removing/ShellDbTablesRemovingHandler.cs @@ -20,7 +20,7 @@ namespace OrchardCore.Environment.Shell.Removing; public class ShellDbTablesRemovingHandler : IShellRemovingHandler { private readonly IShellContextFactory _shellContextFactory; - private readonly IStringLocalizer S; + protected readonly IStringLocalizer S; private readonly ILogger _logger; public ShellDbTablesRemovingHandler( diff --git a/src/OrchardCore/OrchardCore.Data/Documents/FileDocumentStore.cs b/src/OrchardCore/OrchardCore.Data/Documents/FileDocumentStore.cs index cf039840bdc..3d8cabc843c 100644 --- a/src/OrchardCore/OrchardCore.Data/Documents/FileDocumentStore.cs +++ b/src/OrchardCore/OrchardCore.Data/Documents/FileDocumentStore.cs @@ -19,7 +19,7 @@ public class FileDocumentStore : IFileDocumentStore { private readonly string _tenantPath; - private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); + private readonly SemaphoreSlim _semaphore = new(1); public FileDocumentStore(IOptions shellOptions, ShellSettings shellSettings) { diff --git a/src/OrchardCore/OrchardCore.Deployment.Abstractions/DeploymentPlanResult.cs b/src/OrchardCore/OrchardCore.Deployment.Abstractions/DeploymentPlanResult.cs index 6dd5fa07994..160ad88e3df 100644 --- a/src/OrchardCore/OrchardCore.Deployment.Abstractions/DeploymentPlanResult.cs +++ b/src/OrchardCore/OrchardCore.Deployment.Abstractions/DeploymentPlanResult.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; @@ -16,16 +17,18 @@ public DeploymentPlanResult(IFileBuilder fileBuilder, RecipeDescriptor recipeDes { FileBuilder = fileBuilder; - Recipe = new JObject(); - Recipe["name"] = recipeDescriptor.Name ?? ""; - Recipe["displayName"] = recipeDescriptor.DisplayName ?? ""; - Recipe["description"] = recipeDescriptor.Description ?? ""; - Recipe["author"] = recipeDescriptor.Author ?? ""; - Recipe["website"] = recipeDescriptor.WebSite ?? ""; - Recipe["version"] = recipeDescriptor.Version ?? ""; - Recipe["issetuprecipe"] = recipeDescriptor.IsSetupRecipe; - Recipe["categories"] = new JArray(recipeDescriptor.Categories ?? new string[] { }); - Recipe["tags"] = new JArray(recipeDescriptor.Tags ?? new string[] { }); + Recipe = new JObject + { + ["name"] = recipeDescriptor.Name ?? "", + ["displayName"] = recipeDescriptor.DisplayName ?? "", + ["description"] = recipeDescriptor.Description ?? "", + ["author"] = recipeDescriptor.Author ?? "", + ["website"] = recipeDescriptor.WebSite ?? "", + ["version"] = recipeDescriptor.Version ?? "", + ["issetuprecipe"] = recipeDescriptor.IsSetupRecipe, + ["categories"] = new JArray(recipeDescriptor.Categories ?? Array.Empty()), + ["tags"] = new JArray(recipeDescriptor.Tags ?? Array.Empty()), + }; } public JObject Recipe { get; } diff --git a/src/OrchardCore/OrchardCore.Deployment.Abstractions/IDeploymentStepFactory.cs b/src/OrchardCore/OrchardCore.Deployment.Abstractions/IDeploymentStepFactory.cs index d2d004afb38..0b8e20236f7 100644 --- a/src/OrchardCore/OrchardCore.Deployment.Abstractions/IDeploymentStepFactory.cs +++ b/src/OrchardCore/OrchardCore.Deployment.Abstractions/IDeploymentStepFactory.cs @@ -8,9 +8,9 @@ public interface IDeploymentStepFactory public class DeploymentStepFactory : IDeploymentStepFactory where TStep : DeploymentStep, new() { - private static readonly string TypeName = typeof(TStep).Name; + private static readonly string _typeName = typeof(TStep).Name; - public string Name => TypeName; + public string Name => _typeName; public DeploymentStep Create() { diff --git a/src/OrchardCore/OrchardCore.Deployment.Abstractions/IFileBuilder.cs b/src/OrchardCore/OrchardCore.Deployment.Abstractions/IFileBuilder.cs index 2bc606cbd60..7460c9d65dd 100644 --- a/src/OrchardCore/OrchardCore.Deployment.Abstractions/IFileBuilder.cs +++ b/src/OrchardCore/OrchardCore.Deployment.Abstractions/IFileBuilder.cs @@ -12,10 +12,8 @@ public static class IFileBuilderExtensions { public static async Task SetFileAsync(this IFileBuilder fileBuilder, string subpath, byte[] content) { - using (var stream = new MemoryStream(content)) - { - await fileBuilder.SetFileAsync(subpath, stream); - } + using var stream = new MemoryStream(content); + await fileBuilder.SetFileAsync(subpath, stream); } } } diff --git a/src/OrchardCore/OrchardCore.Deployment.Core/CommonPermissions.cs b/src/OrchardCore/OrchardCore.Deployment.Core/CommonPermissions.cs index ca1cd7f24a8..3cd9fd1528d 100644 --- a/src/OrchardCore/OrchardCore.Deployment.Core/CommonPermissions.cs +++ b/src/OrchardCore/OrchardCore.Deployment.Core/CommonPermissions.cs @@ -8,8 +8,8 @@ namespace OrchardCore.Deployment /// public class CommonPermissions { - public static readonly Permission ManageDeploymentPlan = new Permission("ManageDeploymentPlan", "Manage deployment plans"); - public static readonly Permission Export = new Permission("Export", "Export Data"); - public static readonly Permission Import = new Permission("Import", "Import Data", isSecurityCritical: true); + public static readonly Permission ManageDeploymentPlan = new("ManageDeploymentPlan", "Manage deployment plans"); + public static readonly Permission Export = new("Export", "Export Data"); + public static readonly Permission Import = new("Import", "Import Data", isSecurityCritical: true); } } diff --git a/src/OrchardCore/OrchardCore.Deployment.Core/Services/TemporaryFileBuilder.cs b/src/OrchardCore/OrchardCore.Deployment.Core/Services/TemporaryFileBuilder.cs index df77574afb0..7fbe9936fa5 100644 --- a/src/OrchardCore/OrchardCore.Deployment.Core/Services/TemporaryFileBuilder.cs +++ b/src/OrchardCore/OrchardCore.Deployment.Core/Services/TemporaryFileBuilder.cs @@ -4,7 +4,7 @@ namespace OrchardCore.Deployment.Core.Services { - public class TemporaryFileBuilder : IFileBuilder, IDisposable + public sealed class TemporaryFileBuilder : IFileBuilder, IDisposable { private readonly bool _deleteOnDispose; @@ -43,10 +43,8 @@ public async Task SetFileAsync(string subpath, Stream stream) directory.Create(); } - using (var fs = File.Create(fullname, 4 * 1024, FileOptions.None)) - { - await stream.CopyToAsync(fs); - } + using var fs = File.Create(fullname, 4 * 1024, FileOptions.None); + await stream.CopyToAsync(fs); } public override string ToString() diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheDependencyTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheDependencyTag.cs index 37bd0f911f3..4f3a0d560e2 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheDependencyTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheDependencyTag.cs @@ -11,7 +11,7 @@ namespace OrchardCore.DynamicCache.Liquid { public class CacheDependencyTag { - public static async ValueTask WriteToAsync(Expression argument, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(Expression argument, TextWriter _1, TextEncoder _2, TemplateContext context) { var services = ((LiquidTemplateContext)context).Services; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresAfterTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresAfterTag.cs index 872b97983ce..4fa7c4e9333 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresAfterTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresAfterTag.cs @@ -13,7 +13,7 @@ namespace OrchardCore.DynamicCache.Liquid { public class CacheExpiresAfterTag { - public static async ValueTask WriteToAsync(Expression argument, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(Expression argument, TextWriter _1, TextEncoder _2, TemplateContext context) { var services = ((LiquidTemplateContext)context).Services; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresOnTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresOnTag.cs index 00ddf65e54c..21d4d9754d6 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresOnTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresOnTag.cs @@ -14,7 +14,7 @@ namespace OrchardCore.DynamicCache.Liquid { public class CacheExpiresOnTag { - public static async ValueTask WriteToAsync(Expression argument, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(Expression argument, TextWriter _1, TextEncoder _2, TemplateContext context) { var services = ((LiquidTemplateContext)context).Services; @@ -25,9 +25,8 @@ public static async ValueTask WriteToAsync(Expression argument, Text return Completion.Normal; } - var value = DateTimeOffset.MinValue; + DateTimeOffset value; var input = await argument.EvaluateAsync(context); - if (input.Type == FluidValues.String) { var stringValue = input.ToStringValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresSlidingTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresSlidingTag.cs index 4cf3e9b594f..abdfaa21c45 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresSlidingTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheExpiresSlidingTag.cs @@ -13,7 +13,7 @@ namespace OrchardCore.DynamicCache.Liquid { public class CacheExpiresSlidingTag { - public static async ValueTask WriteToAsync(Expression argument, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(Expression argument, TextWriter _1, TextEncoder _2, TemplateContext context) { var services = ((LiquidTemplateContext)context).Services; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheTag.cs index d3b72241143..4316ea0de8a 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Cache/CacheTag.cs @@ -16,7 +16,7 @@ namespace OrchardCore.DynamicCache.Liquid { public class CacheTag { - private static readonly char[] SplitChars = new[] { ',', ' ' }; + private static readonly char[] _splitChars = new[] { ',', ' ' }; public static async ValueTask WriteToAsync(List arguments, IReadOnlyList statements, TextWriter writer, TextEncoder encoder, TemplateContext context) { @@ -60,8 +60,8 @@ public static async ValueTask WriteToAsync(List argu var slidingDurationString = filterArguments["expires_sliding"].ToStringValue(); var cacheContext = new CacheContext(cacheKey) - .AddContext(contexts.Split(SplitChars, StringSplitOptions.RemoveEmptyEntries)) - .AddTag(tags.Split(SplitChars, StringSplitOptions.RemoveEmptyEntries)); + .AddContext(contexts.Split(_splitChars, StringSplitOptions.RemoveEmptyEntries)) + .AddTag(tags.Split(_splitChars, StringSplitOptions.RemoveEmptyEntries)); if (TimeSpan.TryParse(durationString, out var duration)) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/LiquidViewFilters.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/LiquidViewFilters.cs index 4844d6396f4..aa516f9084e 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/LiquidViewFilters.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/LiquidViewFilters.cs @@ -28,7 +28,7 @@ public static ValueTask Localize(FluidValue input, FilterArguments a return new ValueTask(new StringValue(localizer.GetString(input.ToStringValue(), parameters))); } - public static ValueTask HtmlClass(FluidValue input, FilterArguments arguments, TemplateContext ctx) + public static ValueTask HtmlClass(FluidValue input, FilterArguments _1, TemplateContext _2) { return new ValueTask(new StringValue(input.ToStringValue().HtmlClassify())); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/ResourceUrlFilter.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/ResourceUrlFilter.cs index c631ac1570d..eb558c77cb7 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/ResourceUrlFilter.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/ResourceUrlFilter.cs @@ -29,7 +29,7 @@ public ValueTask ProcessAsync(FluidValue input, FilterArguments argu if (resourcePath.StartsWith("~/", StringComparison.Ordinal)) { - resourcePath = _httpContextAccessor.HttpContext.Request.PathBase.Add(resourcePath.Substring(1)).Value; + resourcePath = _httpContextAccessor.HttpContext.Request.PathBase.Add(resourcePath[1..]).Value; } // Don't prefix cdn if the path includes a protocol, i.e. is an external url, or is in debug mode. diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewTemplate.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewTemplate.cs index d4872f7ea4b..4cc8cd886b4 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewTemplate.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewTemplate.cs @@ -31,9 +31,9 @@ namespace OrchardCore.DisplayManagement.Liquid { public class LiquidViewTemplate { - public static readonly string ViewsFolder = "Views"; - public static readonly string ViewExtension = ".liquid"; - public static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions()); + public const string ViewsFolder = "Views"; + public const string ViewExtension = ".liquid"; + public static readonly MemoryCache Cache = new(new MemoryCacheOptions()); public IFluidTemplate FluidTemplate { get; } public LiquidViewTemplate(IFluidTemplate fluidTemplate) @@ -156,10 +156,7 @@ public static async Task RenderAsync(this LiquidViewTemplate template, T var viewContextAccessor = context.Services.GetRequiredService(); var viewContext = viewContextAccessor.ViewContext; - if (viewContext == null) - { - viewContext = viewContextAccessor.ViewContext = await GetViewContextAsync(context); - } + viewContext ??= viewContextAccessor.ViewContext = await GetViewContextAsync(context); try { @@ -177,10 +174,7 @@ public static async Task RenderAsync(this LiquidViewTemplate template, TextWrite var viewContextAccessor = context.Services.GetRequiredService(); var viewContext = viewContextAccessor.ViewContext; - if (viewContext == null) - { - viewContext = viewContextAccessor.ViewContext = await GetViewContextAsync(context); - } + viewContext ??= viewContextAccessor.ViewContext = await GetViewContextAsync(context); try { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewsFeatureProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewsFeatureProvider.cs index e1992042ac4..a33f06568bf 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewsFeatureProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewsFeatureProvider.cs @@ -15,11 +15,11 @@ namespace OrchardCore.DisplayManagement.Liquid public class LiquidViewsFeatureProvider : IApplicationFeatureProvider { public const string DefaultLiquidViewName = "DefaultLiquidViewName"; - public static string DefaultRazorViewPath = '/' + DefaultLiquidViewName + RazorViewEngine.ViewExtension; - public static string DefaultLiquidViewPath = '/' + DefaultLiquidViewName + LiquidViewTemplate.ViewExtension; + public static readonly string DefaultRazorViewPath = '/' + DefaultLiquidViewName + RazorViewEngine.ViewExtension; + public static readonly string DefaultLiquidViewPath = '/' + DefaultLiquidViewName + LiquidViewTemplate.ViewExtension; private static List _sharedPaths; - private static object _synLock = new object(); + private static readonly object _synLock = new(); public LiquidViewsFeatureProvider(IOptions templateOptions) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/ModuleProjectLiquidFileProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/ModuleProjectLiquidFileProvider.cs index b8dd4242786..52793d0d976 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/ModuleProjectLiquidFileProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/ModuleProjectLiquidFileProvider.cs @@ -16,7 +16,7 @@ namespace OrchardCore.DisplayManagement.Liquid public class ModuleProjectLiquidFileProvider : IFileProvider { private static Dictionary _paths; - private static readonly object _synLock = new object(); + private static readonly object _synLock = new(); public ModuleProjectLiquidFileProvider(IApplicationContext applicationContext) { @@ -96,9 +96,6 @@ public IChangeToken Watch(string filter) return NullChangeToken.Singleton; } - private string NormalizePath(string path) - { - return path.Replace('\\', '/').Trim('/'); - } + private static string NormalizePath(string path) => path.Replace('\\', '/').Trim('/'); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperActivator.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperActivator.cs index fefec04b09b..be3aa3e4dba 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperActivator.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperActivator.cs @@ -18,11 +18,11 @@ public class LiquidTagHelperActivator { private const string AspPrefix = "asp-"; - public static readonly LiquidTagHelperActivator None = new LiquidTagHelperActivator(); + public static readonly LiquidTagHelperActivator None = new(); private readonly Func _activatorByFactory; private readonly Dictionary, string, FluidValue>> _setters = - new Dictionary, string, FluidValue>>(StringComparer.OrdinalIgnoreCase); + new(StringComparer.OrdinalIgnoreCase); private readonly Func _activatorByService; private readonly Action _viewContextSetter; @@ -58,7 +58,7 @@ public LiquidTagHelperActivator(Type type) if (htmlAttribute.Name.StartsWith(AspPrefix, StringComparison.Ordinal)) { - allNames.Add(htmlAttribute.Name.Substring(AspPrefix.Length).ToPascalCaseDash()); + allNames.Add(htmlAttribute.Name[AspPrefix.Length..].ToPascalCaseDash()); } var dictionaryPrefix = htmlAttribute.DictionaryAttributePrefix; @@ -68,7 +68,7 @@ public LiquidTagHelperActivator(Type type) if (dictionaryPrefix.StartsWith(AspPrefix, StringComparison.Ordinal)) { - allNames.Add(dictionaryPrefix.Substring(AspPrefix.Length).Replace('-', '_')); + allNames.Add(dictionaryPrefix[AspPrefix.Length..].Replace('-', '_')); } } } @@ -162,10 +162,7 @@ public LiquidTagHelperActivator(Type type) var expresionProvider = context.HttpContext.RequestServices.GetRequiredService(); var viewData = context.ViewData as ViewDataDictionary; - if (viewData == null) - { - viewData = new ViewDataDictionary(context.ViewData); - } + viewData ??= new ViewDataDictionary(context.ViewData); foreach (var name in arguments.Names) { @@ -179,8 +176,8 @@ public LiquidTagHelperActivator(Type type) if (index > -1) { - dictionaryName = name.Substring(0, index + 1); - dictionaryKey = name.Substring(index + 1); + dictionaryName = name[..(index + 1)]; + dictionaryKey = name[(index + 1)..]; if (dictionaryName.Length > 0 && dictionaryKey.Length > 0) { @@ -229,13 +226,13 @@ public static ITagHelper CreateTagHelper(ITagHelperFactory tagHelperFactory, Vie { // Create a delegate TDeclaringType -> { TDeclaringType.Property = TValue; } var setterAsAction = prop.SetMethod.CreateDelegate(typeof(Action<,>).MakeGenericType(type, prop.PropertyType)); - var setterClosedGenericMethod = CallPropertySetterOpenGenericMethod.MakeGenericMethod(type, prop.PropertyType); + var setterClosedGenericMethod = _callPropertySetterOpenGenericMethod.MakeGenericMethod(type, prop.PropertyType); var setterDelegate = setterClosedGenericMethod.CreateDelegate(typeof(Action), setterAsAction); return (Action)setterDelegate; } - private static readonly MethodInfo CallPropertySetterOpenGenericMethod = + private static readonly MethodInfo _callPropertySetterOpenGenericMethod = typeof(LiquidTagHelperActivator).GetTypeInfo().GetDeclaredMethod(nameof(CallPropertySetter)); private static void CallPropertySetter(Action setter, object target, object value) @@ -245,13 +242,13 @@ public static ITagHelper CreateTagHelper(ITagHelperFactory tagHelperFactory, Vie { // Create a delegate TDeclaringType -> { TDeclaringType.Property = TValue; } var getterAsFunc = prop.GetMethod.CreateDelegate(typeof(Func<,>).MakeGenericType(type, prop.PropertyType)); - var getterClosedGenericMethod = CallPropertyGetterOpenGenericMethod.MakeGenericMethod(type, prop.PropertyType); + var getterClosedGenericMethod = _callPropertyGetterOpenGenericMethod.MakeGenericMethod(type, prop.PropertyType); var getterDelegate = getterClosedGenericMethod.CreateDelegate(typeof(Func), getterAsFunc); return (Func)getterDelegate; } - private static readonly MethodInfo CallPropertyGetterOpenGenericMethod = + private static readonly MethodInfo _callPropertyGetterOpenGenericMethod = typeof(LiquidTagHelperActivator).GetTypeInfo().GetDeclaredMethod(nameof(CallPropertyGetter)); private static object CallPropertyGetter(Func getter, object target) diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperFactory.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperFactory.cs index d7351dd51d0..3c8115f9e38 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperFactory.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperFactory.cs @@ -18,8 +18,8 @@ namespace OrchardCore.DisplayManagement.Liquid.TagHelpers /// public class LiquidTagHelperFactory { - private static ConcurrentDictionary _allMatchings = new ConcurrentDictionary(); - private static ConcurrentDictionary _allActivators = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary _allMatchings = new(); + private static readonly ConcurrentDictionary _allActivators = new(); private List _matchings; private readonly ApplicationPartManager _partManager; @@ -104,7 +104,7 @@ private static void AddTagMatchingRules(Type type, TagHelperDescriptorBuilder de if (name.EndsWith("TagHelper", StringComparison.OrdinalIgnoreCase)) { - name = name.Substring(0, name.Length - "TagHelper".Length); + name = name[..^"TagHelper".Length]; } descriptorBuilder.TagMatchingRule(ruleBuilder => diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperMatching.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperMatching.cs index 9b2ae857277..280f74ec854 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperMatching.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/LiquidTagHelperMatching.cs @@ -8,8 +8,9 @@ namespace OrchardCore.DisplayManagement.Liquid.TagHelpers public class LiquidTagHelperMatching { private const string AspPrefix = "asp-"; - public readonly static LiquidTagHelperMatching None = new LiquidTagHelperMatching(); + public readonly static LiquidTagHelperMatching None = new(); public readonly TagMatchingRuleDescriptor[] _rules = Array.Empty(); + public LiquidTagHelperMatching() { } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs index da247a1403e..eaf9f86fc52 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/TagHelpers/RequiredAttributeParser.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -18,24 +19,24 @@ private class DefaultRequiredAttributeParser { private const char RequiredAttributeWildcardSuffix = '*'; - private static readonly IReadOnlyDictionary CssValueComparisons = + private static readonly IReadOnlyDictionary _cssValueComparisons = new Dictionary { { '=', RequiredAttributeDescriptor.ValueComparisonMode.FullMatch }, { '^', RequiredAttributeDescriptor.ValueComparisonMode.PrefixMatch }, - { '$', RequiredAttributeDescriptor.ValueComparisonMode.SuffixMatch } + { '$', RequiredAttributeDescriptor.ValueComparisonMode.SuffixMatch }, }; - private static readonly char[] InvalidPlainAttributeNameCharacters = { ' ', '\t', ',', RequiredAttributeWildcardSuffix }; + private static readonly char[] _invalidPlainAttributeNameCharacters = { ' ', '\t', ',', RequiredAttributeWildcardSuffix }; - private static readonly char[] InvalidCssAttributeNameCharacters = (new[] { ' ', '\t', ',', ']' }) - .Concat(CssValueComparisons.Keys) + private static readonly char[] _invalidCssAttributeNameCharacters = (new[] { ' ', '\t', ',', ']' }) + .Concat(_cssValueComparisons.Keys) .ToArray(); - private static readonly char[] InvalidCssQuotelessValueCharacters = { ' ', '\t', ']' }; + private static readonly char[] _invalidCssQuotelessValueCharacters = { ' ', '\t', ']' }; private int _index; - private string _requiredAttributes; + private readonly string _requiredAttributes; public DefaultRequiredAttributeParser(string requiredAttributes) { @@ -48,7 +49,7 @@ public DefaultRequiredAttributeParser(string requiredAttributes) public void AddRequiredAttributes(TagMatchingRuleDescriptorBuilder ruleBuilder) { - if (string.IsNullOrEmpty(_requiredAttributes)) + if (String.IsNullOrEmpty(_requiredAttributes)) { return; } @@ -106,18 +107,18 @@ public void AddRequiredAttributes(TagMatchingRuleDescriptorBuilder ruleBuilder) private void ParsePlainSelector(RequiredAttributeDescriptorBuilder attributeBuilder) { - var nameEndIndex = _requiredAttributes.IndexOfAny(InvalidPlainAttributeNameCharacters, _index); + var nameEndIndex = _requiredAttributes.IndexOfAny(_invalidPlainAttributeNameCharacters, _index); string attributeName; var nameComparison = RequiredAttributeDescriptor.NameComparisonMode.FullMatch; if (nameEndIndex == -1) { - attributeName = _requiredAttributes.Substring(_index); + attributeName = _requiredAttributes[_index..]; _index = _requiredAttributes.Length; } else { - attributeName = _requiredAttributes.Substring(_index, nameEndIndex - _index); + attributeName = _requiredAttributes[_index..nameEndIndex]; _index = nameEndIndex; if (_requiredAttributes[nameEndIndex] == RequiredAttributeWildcardSuffix) @@ -136,11 +137,11 @@ private void ParsePlainSelector(RequiredAttributeDescriptorBuilder attributeBuil private void ParseCssAttributeName(RequiredAttributeDescriptorBuilder builder) { var nameStartIndex = _index; - var nameEndIndex = _requiredAttributes.IndexOfAny(InvalidCssAttributeNameCharacters, _index); + var nameEndIndex = _requiredAttributes.IndexOfAny(_invalidCssAttributeNameCharacters, _index); nameEndIndex = nameEndIndex == -1 ? _requiredAttributes.Length : nameEndIndex; _index = nameEndIndex; - var attributeName = _requiredAttributes.Substring(nameStartIndex, nameEndIndex - nameStartIndex); + var attributeName = _requiredAttributes[nameStartIndex..nameEndIndex]; builder.Name = attributeName; } @@ -149,7 +150,7 @@ private bool TryParseCssValueComparison(RequiredAttributeDescriptorBuilder build { Debug.Assert(!AtEnd); - if (CssValueComparisons.TryGetValue(Current, out valueComparison)) + if (_cssValueComparisons.TryGetValue(Current, out valueComparison)) { var op = Current; _index++; @@ -205,12 +206,12 @@ private bool TryParseCssValue(RequiredAttributeDescriptorBuilder builder) else { valueStart = _index; - var valueEndIndex = _requiredAttributes.IndexOfAny(InvalidCssQuotelessValueCharacters, _index); + var valueEndIndex = _requiredAttributes.IndexOfAny(_invalidCssQuotelessValueCharacters, _index); valueEnd = valueEndIndex == -1 ? _requiredAttributes.Length : valueEndIndex; _index = valueEnd; } - var value = _requiredAttributes.Substring(valueStart, valueEnd - valueStart); + var value = _requiredAttributes[valueStart..valueEnd]; builder.Value = value; @@ -234,7 +235,7 @@ private bool TryParseCssSelector(RequiredAttributeDescriptorBuilder attributeBui return false; } - if (!TryParseCssValueComparison(attributeBuilder, out RequiredAttributeDescriptor.ValueComparisonMode valueComparison)) + if (!TryParseCssValueComparison(attributeBuilder, out var valueComparison)) { return false; } @@ -261,24 +262,24 @@ private bool TryParseCssSelector(RequiredAttributeDescriptorBuilder attributeBui } else if (AtEnd) { - //var diagnostic = RazorDiagnosticFactory.CreateTagHelper_CouldNotFindMatchingEndBrace(_requiredAttributes); - //attributeBuilder.Diagnostics.Add(diagnostic); + // var diagnostic = RazorDiagnosticFactory.CreateTagHelper_CouldNotFindMatchingEndBrace(_requiredAttributes); + // attributeBuilder.Diagnostics.Add(diagnostic); } else { - //var diagnostic = RazorDiagnosticFactory.CreateTagHelper_InvalidRequiredAttributeCharacter(Current, _requiredAttributes); - //attributeBuilder.Diagnostics.Add(diagnostic); + // var diagnostic = RazorDiagnosticFactory.CreateTagHelper_InvalidRequiredAttributeCharacter(Current, _requiredAttributes); + // attributeBuilder.Diagnostics.Add(diagnostic); } return false; } - private bool EnsureNotAtEnd(RequiredAttributeDescriptorBuilder builder) + private bool EnsureNotAtEnd(RequiredAttributeDescriptorBuilder _) { if (AtEnd) { - //var diagnostic = RazorDiagnosticFactory.CreateTagHelper_CouldNotFindMatchingEndBrace(_requiredAttributes); - //builder.Diagnostics.Add(diagnostic); + // var diagnostic = RazorDiagnosticFactory.CreateTagHelper_CouldNotFindMatchingEndBrace(_requiredAttributes); + // builder.Diagnostics.Add(diagnostic); return false; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddAlternatesTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddAlternatesTag.cs index 071ccf0008d..526387a4fc5 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddAlternatesTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddAlternatesTag.cs @@ -10,7 +10,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class AddAlternatesTag { - public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddAttributesTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddAttributesTag.cs index b280fff34c0..0fd6d540a9e 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddAttributesTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddAttributesTag.cs @@ -10,7 +10,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class AddAttributesTag { - public static async ValueTask WriteToAsync(ValueTuple> arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple> arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddClassesTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddClassesTag.cs index 6d962a876d4..d28eb915efa 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddClassesTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddClassesTag.cs @@ -10,7 +10,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class AddClassesTag { - public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddWrappersTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddWrappersTag.cs index 05a21caf069..aba42dd2a58 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddWrappersTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AddWrappersTag.cs @@ -10,7 +10,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class AddWrappersTag { - public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AnchorTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AnchorTag.cs index 47f7c2a91ad..596de4e3fab 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AnchorTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/AnchorTag.cs @@ -125,10 +125,7 @@ public async ValueTask WriteToAsync(List argumentsLi if (area != null) { // Unconditionally replace any value from asp-route-area. - if (localRouteValues == null) - { - localRouteValues = new RouteValueDictionary(); - } + localRouteValues ??= new RouteValueDictionary(); localRouteValues["area"] = area; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearAlternatesTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearAlternatesTag.cs index f50843d3810..7f2c9af26d9 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearAlternatesTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearAlternatesTag.cs @@ -8,7 +8,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ClearAlternatesTag { - public static async ValueTask WriteToAsync(Expression expression, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(Expression expression, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await expression.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearAttributesTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearAttributesTag.cs index 6d86a6b97e1..b4492140eb4 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearAttributesTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearAttributesTag.cs @@ -8,7 +8,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ClearAttributesTag { - public static async ValueTask WriteToAsync(Expression expression, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(Expression expression, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await expression.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearClassesTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearClassesTag.cs index 7a3b4d8f302..2060509dc22 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearClassesTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearClassesTag.cs @@ -8,7 +8,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ClearClassesTag { - public static async ValueTask WriteToAsync(Expression expression, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(Expression expression, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await expression.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearWrappersTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearWrappersTag.cs index 97505cf8097..98f9ec58f95 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearWrappersTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ClearWrappersTag.cs @@ -8,7 +8,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ClearWrappers { - public static async ValueTask WriteToAsync(Expression expression, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(Expression expression, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await expression.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/FluidTagHelper.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/FluidTagHelper.cs index d4f080ee570..a2194e79c22 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/FluidTagHelper.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/FluidTagHelper.cs @@ -15,7 +15,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class FluidTagHelper { - public static Dictionary DefaultArgumentsMapping = new Dictionary(); + public static readonly Dictionary DefaultArgumentsMapping = new(); private static long _uniqueId; public static ValueTask WriteArgumentsTagHelperAsync(List arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) @@ -79,7 +79,7 @@ public static async ValueTask WriteToAsync(string identifier, List(), id.ToString()); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextAddItemTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextAddItemTag.cs index 1bf66bb5927..100ea31ca7c 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextAddItemTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextAddItemTag.cs @@ -12,7 +12,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class HttpContextAddItemTag { - public static async ValueTask WriteToAsync(List expressions, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(List expressions, TextWriter _1, TextEncoder _2, TemplateContext context) { var services = ((LiquidTemplateContext)context).Services; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextRemoveItemTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextRemoveItemTag.cs index 248e767bb63..fa6ee6e0b94 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextRemoveItemTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/HttpContextRemoveItemTag.cs @@ -1,3 +1,4 @@ +using System; using System.IO; using System.Text.Encodings.Web; using System.Threading.Tasks; @@ -11,7 +12,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class HttpContextRemoveItemTag { - public static async ValueTask WriteToAsync(Expression argument, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(Expression argument, TextWriter _1, TextEncoder _2, TemplateContext context) { var services = ((LiquidTemplateContext)context).Services; @@ -21,7 +22,7 @@ public static async ValueTask WriteToAsync(Expression argument, Text { var itemKey = (await argument.EvaluateAsync(context)).ToStringValue(); - if (!string.IsNullOrEmpty(itemKey)) + if (!String.IsNullOrEmpty(itemKey)) { httpContext.Items.Remove(itemKey); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/LayoutTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/LayoutTag.cs index 90b6965958f..71b7cd9a914 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/LayoutTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/LayoutTag.cs @@ -11,7 +11,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class LayoutTag { - public static async ValueTask WriteToAsync(Expression expression, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(Expression expression, TextWriter _1, TextEncoder _2, TemplateContext context) { var services = ((LiquidTemplateContext)context).Services; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeAddPropertyTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeAddPropertyTag.cs index a671dcac12a..cf11e5d4f9a 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeAddPropertyTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeAddPropertyTag.cs @@ -11,7 +11,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ShapeAddPropertyTag { - public static async ValueTask WriteToAsync(ValueTuple> arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple> arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeCacheTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeCacheTag.cs index b48430f3765..657866a645a 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeCacheTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeCacheTag.cs @@ -10,9 +10,9 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ShapeCacheTag { - private static readonly char[] Separators = { ',', ' ' }; + private static readonly char[] _separators = { ',', ' ' }; - public static async ValueTask WriteToAsync(ValueTuple> arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple> arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); @@ -29,13 +29,13 @@ public static async ValueTask WriteToAsync(ValueTuple WriteToAsync(ValueTuple arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePagerTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePagerTag.cs index 6dada8ef8b4..92228352bc7 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePagerTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePagerTag.cs @@ -14,12 +14,12 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ShapePagerTag { - private static readonly HashSet _properties = new HashSet + private static readonly HashSet _properties = new() { "Id", "PreviousText", "NextText", "PreviousClass", "NextClass", "TagName", "ItemTagName" }; - public static async ValueTask WriteToAsync(ValueTuple> arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple> arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue() as dynamic; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePositionTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePositionTag.cs index f04231f9819..1a5c3db03f9 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePositionTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapePositionTag.cs @@ -9,7 +9,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ShapePositionTag { - public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeRemoveItemTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeRemoveItemTag.cs index 408d8dfdfa9..eb7e5a93f61 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeRemoveItemTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeRemoveItemTag.cs @@ -10,7 +10,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ShapeRemoveItemTag { - public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeRemovePropertyTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeRemovePropertyTag.cs index 048160a2893..c2ab2bbd471 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeRemovePropertyTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeRemovePropertyTag.cs @@ -10,7 +10,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ShapeRemovePropertyTag { - public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); @@ -18,7 +18,7 @@ public static async ValueTask WriteToAsync(ValueTuple WriteToAsync(ValueTuple arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeTag.cs index ea80cee29f8..087c7382a47 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeTag.cs @@ -13,7 +13,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ShapeTag { - private static readonly char[] Separators = { ',', ' ' }; + private static readonly char[] _separators = { ',', ' ' }; public static async ValueTask WriteToAsync(List argumentsList, TextWriter writer, TextEncoder encoder, TemplateContext context) { @@ -40,8 +40,12 @@ public static async ValueTask WriteToAsync(List argu switch (argument.Name) { 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; +#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; @@ -93,13 +97,13 @@ public static async ValueTask WriteToAsync(List argu if (!String.IsNullOrWhiteSpace(cacheContext)) { - var contexts = cacheContext.Split(Separators, StringSplitOptions.RemoveEmptyEntries); + var contexts = cacheContext.Split(_separators, StringSplitOptions.RemoveEmptyEntries); metadata.Cache().AddContext(contexts); } if (!String.IsNullOrWhiteSpace(cacheTag)) { - var tags = cacheTag.Split(Separators, StringSplitOptions.RemoveEmptyEntries); + var tags = cacheTag.Split(_separators, StringSplitOptions.RemoveEmptyEntries); metadata.Cache().AddTag(tags); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeTypeTag.cs b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeTypeTag.cs index e1b865c7aa4..22e3d96fddc 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeTypeTag.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Tags/ShapeTypeTag.cs @@ -9,7 +9,7 @@ namespace OrchardCore.DisplayManagement.Liquid.Tags { public class ShapeTypeTag { - public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter writer, TextEncoder encoder, TemplateContext context) + public static async ValueTask WriteToAsync(ValueTuple arguments, TextWriter _1, TextEncoder _2, TemplateContext context) { var objectValue = (await arguments.Item1.EvaluateAsync(context)).ToObjectValue(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs index 919014c83df..4ed785d039f 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Arguments.cs @@ -9,7 +9,7 @@ namespace OrchardCore.DisplayManagement { public static class Arguments { - private static ConcurrentDictionary>> _propertiesAccessors = new ConcurrentDictionary>>(); + private static readonly ConcurrentDictionary>> _propertiesAccessors = new(); public static INamedEnumerable FromT(IEnumerable arguments, IEnumerable names) { @@ -91,7 +91,7 @@ IEnumerator IEnumerable.GetEnumerator() IDictionary INamedEnumerable.Named { - get { return _named ?? (_named = new Named(_arguments, _names)); } + get { return _named ??= new Named(_arguments, _names); } } private class Named : IDictionary @@ -116,7 +116,7 @@ public Named(IList arguments, IList names) private IEnumerable> MakeEnumerable() { - return _enumerable ?? (_enumerable = _arguments.Zip(_names, (arg, name) => new KeyValuePair(name, arg))); + return _enumerable ??= _arguments.Zip(_names, (arg, name) => new KeyValuePair(name, arg)); } IEnumerator> IEnumerable>.GetEnumerator() @@ -195,13 +195,13 @@ IEnumerator IEnumerable.GetEnumerator() { get { - if (((IDictionary)this).TryGetValue(key, out T result)) + if (((IDictionary)this).TryGetValue(key, out var result)) { return result; } else { - return default(T); + return default; } } set { throw new NotImplementedException(); } @@ -222,6 +222,6 @@ IEnumerator IEnumerable.GetEnumerator() } } - public static INamedEnumerable Empty = From(Array.Empty(), Array.Empty()); + public static readonly INamedEnumerable Empty = From(Array.Empty(), Array.Empty()); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/BaseDisplayManager.cs b/src/OrchardCore/OrchardCore.DisplayManagement/BaseDisplayManager.cs index b0f2a30d08b..b9ed6ac1ffd 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/BaseDisplayManager.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/BaseDisplayManager.cs @@ -45,7 +45,7 @@ private static PlacementInfo FindPlacementImpl(IList pla if (delimiterIndex > 0) { - shapeType = shapeType.Substring(0, delimiterIndex); + shapeType = shapeType[..delimiterIndex]; } var placementContext = new ShapePlacementContext( diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/DefaultShapeTableManager.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/DefaultShapeTableManager.cs index 9f9b6552b24..4b0ae1decde 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/DefaultShapeTableManager.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/DefaultShapeTableManager.cs @@ -18,8 +18,8 @@ namespace OrchardCore.DisplayManagement.Descriptors /// public class DefaultShapeTableManager : IShapeTableManager { - private static ConcurrentDictionary _shapeDescriptors = new ConcurrentDictionary(); - private static readonly object _syncLock = new object(); + private static readonly ConcurrentDictionary _shapeDescriptors = new(); + private static readonly object _syncLock = new(); private readonly IHostEnvironment _hostingEnvironment; private readonly IEnumerable _bindingStrategies; @@ -131,7 +131,10 @@ public ShapeTable GetShapeTable(string themeId) return shapeTable; } - private void BuildDescriptors(IShapeTableProvider bindingStrategy, IEnumerable builtAlterations, Dictionary shapeDescriptors) + private static void BuildDescriptors( + IShapeTableProvider bindingStrategy, + IEnumerable builtAlterations, + Dictionary shapeDescriptors) { var alterationSets = builtAlterations.GroupBy(a => a.Feature.Id + a.ShapeType); @@ -168,7 +171,7 @@ private bool IsModuleOrRequestedTheme(IFeatureInfo feature, string themeId) return true; } - if (string.IsNullOrEmpty(themeId)) + if (String.IsNullOrEmpty(themeId)) { return false; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/PlacementInfo.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/PlacementInfo.cs index b29fc31054f..922c06713c0 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/PlacementInfo.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/PlacementInfo.cs @@ -4,7 +4,7 @@ namespace OrchardCore.DisplayManagement.Descriptors { public class PlacementInfo { - private static readonly char[] Delimiters = { ':', '#', '@', '%', '|' }; + private static readonly char[] _delimiters = { ':', '#', '@', '%', '|' }; public string Location { get; set; } public string Source { get; set; } @@ -20,7 +20,7 @@ public bool IsLayoutZone() /// /// Returns the list of zone names. - /// e.g., Content.Metadata:1 will return 'Content', 'Metadata' + /// e.g., Content.Metadata:1 will return 'Content', 'Metadata'. /// /// public string[] GetZones() @@ -28,20 +28,20 @@ public string[] GetZones() string zones; var location = Location; - // Strip the Layout marker + // Strip the Layout marker. if (IsLayoutZone()) { - location = location.Substring(1); + location = location[1..]; } - var firstDelimiter = location.IndexOfAny(Delimiters); + var firstDelimiter = location.IndexOfAny(_delimiters); if (firstDelimiter == -1) { zones = location; } else { - zones = location.Substring(0, firstDelimiter); + zones = location[..firstDelimiter]; } return zones.Split('.'); @@ -55,13 +55,13 @@ public string GetPosition() return DefaultPosition ?? ""; } - var secondDelimiter = Location.IndexOfAny(Delimiters, contentDelimiter + 1); + var secondDelimiter = Location.IndexOfAny(_delimiters, contentDelimiter + 1); if (secondDelimiter == -1) { - return Location.Substring(contentDelimiter + 1); + return Location[(contentDelimiter + 1)..]; } - return Location.Substring(contentDelimiter + 1, secondDelimiter - contentDelimiter - 1); + return Location[(contentDelimiter + 1)..secondDelimiter]; } public string GetTab() @@ -72,13 +72,13 @@ public string GetTab() return ""; } - var nextDelimiter = Location.IndexOfAny(Delimiters, tabDelimiter + 1); + var nextDelimiter = Location.IndexOfAny(_delimiters, tabDelimiter + 1); if (nextDelimiter == -1) { - return Location.Substring(tabDelimiter + 1); + return Location[(tabDelimiter + 1)..]; } - return Location.Substring(tabDelimiter + 1, nextDelimiter - tabDelimiter - 1); + return Location[(tabDelimiter + 1)..nextDelimiter]; } /// @@ -93,13 +93,13 @@ public string GetGroup() return null; } - var nextDelimiter = Location.IndexOfAny(Delimiters, groupDelimiter + 1); + var nextDelimiter = Location.IndexOfAny(_delimiters, groupDelimiter + 1); if (nextDelimiter == -1) { - return Location.Substring(groupDelimiter + 1); + return Location[(groupDelimiter + 1)..]; } - return Location.Substring(groupDelimiter + 1, nextDelimiter - groupDelimiter - 1); + return Location[(groupDelimiter + 1)..nextDelimiter]; } /// @@ -114,13 +114,13 @@ public string GetCard() return null; } - var nextDelimiter = Location.IndexOfAny(Delimiters, cardDelimiter + 1); + var nextDelimiter = Location.IndexOfAny(_delimiters, cardDelimiter + 1); if (nextDelimiter == -1) { - return Location.Substring(cardDelimiter + 1); + return Location[(cardDelimiter + 1)..]; } - return Location.Substring(cardDelimiter + 1, nextDelimiter - cardDelimiter - 1); + return Location[(cardDelimiter + 1)..nextDelimiter]; } /// @@ -135,13 +135,13 @@ public string GetColumn() return null; } - var nextDelimiter = Location.IndexOfAny(Delimiters, colDelimeter + 1); + var nextDelimiter = Location.IndexOfAny(_delimiters, colDelimeter + 1); if (nextDelimiter == -1) { - return Location.Substring(colDelimeter + 1); + return Location[(colDelimeter + 1)..]; } - return Location.Substring(colDelimeter + 1, nextDelimiter - colDelimeter - 1); + return Location[(colDelimeter + 1)..nextDelimiter]; } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/PlacementInfoExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/PlacementInfoExtensions.cs index bd50b5386a6..3195c76158b 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/PlacementInfoExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/PlacementInfoExtensions.cs @@ -1,3 +1,4 @@ +using System; using OrchardCore.DisplayManagement.Shapes; namespace OrchardCore.DisplayManagement.Descriptors @@ -23,19 +24,22 @@ public static PlacementInfo Combine(this PlacementInfo first, PlacementInfo seco { first.Alternates = first.Alternates.Combine(second.Alternates); first.Wrappers = first.Wrappers.Combine(second.Wrappers); - if (!string.IsNullOrEmpty(second.ShapeType)) + if (!String.IsNullOrEmpty(second.ShapeType)) { first.ShapeType = second.ShapeType; } - if (!string.IsNullOrEmpty(second.Location)) + + if (!String.IsNullOrEmpty(second.Location)) { first.Location = second.Location; } - if (!string.IsNullOrEmpty(second.DefaultPosition)) + + if (!String.IsNullOrEmpty(second.DefaultPosition)) { first.DefaultPosition = second.DefaultPosition; } - if (!string.IsNullOrEmpty(second.Source)) + + if (!String.IsNullOrEmpty(second.Source)) { first.Source += "," + second.Source; } @@ -62,6 +66,7 @@ public static AlternatesCollection Combine(this AlternatesCollection first, Alte { first.AddRange(second); } + return first; } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAlterationBuilder.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAlterationBuilder.cs index f951c9c34d8..98f4aa893ef 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAlterationBuilder.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAlterationBuilder.cs @@ -27,7 +27,7 @@ public ShapeAlterationBuilder(IFeatureInfo feature, string shapeType) } else { - _shapeType = shapeType.Substring(0, delimiterIndex); + _shapeType = shapeType[..delimiterIndex]; } } @@ -45,18 +45,17 @@ public ShapeAlterationBuilder Configure(Action action) public ShapeAlterationBuilder BoundAs(string bindingSource, Func> bindingDelegate) { - // schedule the configuration + // Schedule the configuration. return Configure(descriptor => { var binding = new ShapeBinding { BindingName = _bindingName, BindingSource = bindingSource, + BindingAsync = bindingDelegate, }; - binding.BindingAsync = bindingDelegate; - - // ShapeDescriptor.Bindings is a case insensitive dictionary + // ShapeDescriptor.Bindings is a case insensitive dictionary. descriptor.Bindings[_bindingName] = binding; descriptor.BindingSources.Add(bindingSource); }); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAttributeStrategy/ShapeAttributeBindingStrategy.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAttributeStrategy/ShapeAttributeBindingStrategy.cs index 8c3a2454317..a54f40c605d 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAttributeStrategy/ShapeAttributeBindingStrategy.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeAttributeStrategy/ShapeAttributeBindingStrategy.cs @@ -60,7 +60,7 @@ public void Discover(ShapeTableBuilder builder) } [DebuggerStepThrough] - private Func> CreateDelegate(ShapeAttributeOccurrence attributeOccurrence) + private static Func> CreateDelegate(ShapeAttributeOccurrence attributeOccurrence) { var type = attributeOccurrence.ServiceType; var methodInfo = attributeOccurrence.MethodInfo; @@ -126,7 +126,7 @@ public void Discover(ShapeTableBuilder builder) private static Func CreateMethodWrapper(Type type, MethodInfo method) { - CreateParamsExpressions(method, out ParameterExpression argsExp, out Expression[] paramsExps); + CreateParamsExpressions(method, out var argsExp, out var paramsExps); var targetExp = Expression.Parameter(typeof(object), "target"); var castTargetExp = Expression.Convert(targetExp, type); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PathPlacementNodeFilterProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PathPlacementNodeFilterProvider.cs index b1abc068c24..2c2dd3d9941 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PathPlacementNodeFilterProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PathPlacementNodeFilterProvider.cs @@ -38,7 +38,7 @@ public bool IsMatch(ShapePlacementContext context, JToken expression) if (normalizedPath.EndsWith('*')) { - var prefix = normalizedPath.Substring(0, normalizedPath.Length - 1); + var prefix = normalizedPath[..^1]; return requestPath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); } @@ -48,11 +48,11 @@ public bool IsMatch(ShapePlacementContext context, JToken expression) }); } - private string NormalizePath(string path) + private static string NormalizePath(string path) { if (path.StartsWith("~/", StringComparison.Ordinal)) { - return path.Substring(1); + return path[1..]; } else if (!path.StartsWith('/')) { @@ -64,9 +64,6 @@ private string NormalizePath(string path) } } - private string AppendTrailingSlash(string path) - { - return path.EndsWith('/') ? path : path + "/"; - } + private static string AppendTrailingSlash(string path) => path.EndsWith('/') ? path : path + "/"; } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/ShapePlacementParsingStrategy.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/ShapePlacementParsingStrategy.cs index 6ddfbfe33d1..44bd2913652 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/ShapePlacementParsingStrategy.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/ShapePlacementParsingStrategy.cs @@ -3,7 +3,6 @@ using System.IO; using System.Linq; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OrchardCore.DisplayManagement.Shapes; @@ -25,7 +24,6 @@ public class ShapePlacementParsingStrategy : IShapeTableHarvester public ShapePlacementParsingStrategy( IHostEnvironment hostingEnvironment, IShellFeaturesManager shellFeaturesManager, - ILogger logger, IEnumerable placementParseMatchProviders) { _hostingEnvironment = hostingEnvironment; @@ -53,20 +51,15 @@ private void ProcessFeatureDescriptor(ShapeTableBuilder builder, IFeatureInfo fe if (virtualFileInfo.Exists) { - using (var stream = virtualFileInfo.CreateReadStream()) + using var stream = virtualFileInfo.CreateReadStream(); + using var reader = new StreamReader(stream); + using var jtr = new JsonTextReader(reader); + + var serializer = new JsonSerializer(); + var placementFile = serializer.Deserialize(jtr); + if (placementFile != null) { - using (var reader = new StreamReader(stream)) - { - using (var jtr = new JsonTextReader(reader)) - { - JsonSerializer serializer = new JsonSerializer(); - var placementFile = serializer.Deserialize(jtr); - if (placementFile != null) - { - ProcessPlacementFile(builder, featureDescriptor, placementFile); - } - } - } + ProcessPlacementFile(builder, featureDescriptor, placementFile); } } } @@ -88,9 +81,11 @@ private void ProcessPlacementFile(ShapeTableBuilder builder, IFeatureInfo featur predicate = matches.Aggregate(predicate, BuildPredicate); } - var placement = new PlacementInfo(); + var placement = new PlacementInfo + { + Location = filter.Location, + }; - placement.Location = filter.Location; if (filter.Alternates?.Length > 0) { placement.Alternates = new AlternatesCollection(filter.Alternates); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/BasicShapeTemplateHarvester.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/BasicShapeTemplateHarvester.cs index 227e829c50b..8986ad8fe90 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/BasicShapeTemplateHarvester.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/BasicShapeTemplateHarvester.cs @@ -18,16 +18,16 @@ public IEnumerable HarvestShape(HarvestShapeInfo info) { yield return new HarvestShapeHit { - ShapeType = Adjust(info.SubPath, info.FileName, null) + ShapeType = Adjust(info.SubPath, info.FileName, null), }; } else { - var displayType = info.FileName.Substring(lastDot + 1); + var displayType = info.FileName[(lastDot + 1)..]; yield return new HarvestShapeHit { - ShapeType = Adjust(info.SubPath, info.FileName.Substring(0, lastDot), displayType), - DisplayType = displayType + ShapeType = Adjust(info.SubPath, info.FileName[..lastDot], displayType), + DisplayType = displayType, }; } } @@ -37,24 +37,27 @@ private static string Adjust(string subPath, string fileName, string displayType var leader = ""; if (subPath.StartsWith("Views/", StringComparison.Ordinal) && subPath != "Views/Items") { - leader = subPath.Substring("Views/".Length) + "_"; + leader = String.Concat(subPath.AsSpan("Views/".Length), "_"); } // canonical shape type names must not have - or . to be compatible // with display and shape api calls))) var shapeType = leader + fileName.Replace("--", "__").Replace("-", "__").Replace('.', '_'); - if (string.IsNullOrEmpty(displayType)) + if (String.IsNullOrEmpty(displayType)) { return shapeType.ToLowerInvariant(); } + var firstBreakingSeparator = shapeType.IndexOf("__", StringComparison.Ordinal); if (firstBreakingSeparator <= 0) { return (shapeType + "_" + displayType).ToLowerInvariant(); } - return (shapeType.Substring(0, firstBreakingSeparator) + "_" + displayType + shapeType.Substring(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 82a88b208d4..8902665faaf 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/ShapeTemplateBindingStrategy.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapeTemplateStrategy/ShapeTemplateBindingStrategy.cs @@ -20,8 +20,7 @@ public class ShapeTemplateBindingStrategy : IShapeTableHarvester private readonly ILogger _logger; private readonly IShellFeaturesManager _shellFeaturesManager; - private readonly Dictionary _viewEnginesByExtension = - new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _viewEnginesByExtension = new(StringComparer.OrdinalIgnoreCase); public ShapeTemplateBindingStrategy( IEnumerable harvesters, diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/RazorHelperExtensions.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/RazorHelperExtensions.cs index a9d3923e9bb..6a051d85607 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/RazorHelperExtensions.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Extensions/RazorHelperExtensions.cs @@ -2,13 +2,14 @@ using OrchardCore; using OrchardCore.Localization; +#pragma warning disable CA1050 // Declare types in namespaces public static class RazorHelperExtensions { /// /// Returns the text writing directionality or the current request. /// /// "rtl" if the current culture is Left To Right, "ltr" otherwise. - public static string CultureDir(this IOrchardHelper orchardHelper) + public static string CultureDir(this IOrchardHelper _) { return CultureInfo.CurrentUICulture.GetLanguageDirection(); } @@ -16,8 +17,9 @@ public static string CultureDir(this IOrchardHelper orchardHelper) /// /// Returns the current culture name. /// - public static string CultureName(this IOrchardHelper orchardHelper) + public static string CultureName(this IOrchardHelper _) { return CultureInfo.CurrentUICulture.Name; } } +#pragma warning restore CA1050 // Declare types in namespaces diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriverBase.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriverBase.cs index e2c5d433079..053ba72d1cf 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriverBase.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Handlers/DisplayDriverBase.cs @@ -144,14 +144,8 @@ public virtual ShapeResult Factory(string shapeType, Func new(results); - public CombinedResult Combine(IEnumerable results) - { - return new CombinedResult(results); - } + public static CombinedResult Combine(IEnumerable results) => new(results); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/IDisplayManager.cs b/src/OrchardCore/OrchardCore.DisplayManagement/IDisplayManager.cs index eb6040487fa..0358436891d 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/IDisplayManager.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/IDisplayManager.cs @@ -10,11 +10,11 @@ public interface IDisplayManager Task BuildEditorAsync(TModel model, IUpdateModel updater, bool isNew, string groupId, string htmlPrefix); Task UpdateEditorAsync(TModel model, IUpdateModel updater, bool isNew, string groupId, string htmlPrefix); - [Obsolete] + [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, ""); - [Obsolete] + [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, ""); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/IShape.cs b/src/OrchardCore/OrchardCore.DisplayManagement/IShape.cs index 29d230fb2d1..59d06af52bb 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/IShape.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/IShape.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OrchardCore.DisplayManagement.Shapes; using OrchardCore.DisplayManagement.Zones; @@ -12,7 +11,7 @@ namespace OrchardCore.DisplayManagement /// /// Interface present on dynamic shapes. /// May be used to access attributes in a strongly typed fashion. - /// Note: Anything on this interface is a reserved word for the purpose of shape properties + /// Note: Anything on this interface is a reserved word for the purpose of shape properties. /// public interface IShape { @@ -87,7 +86,7 @@ public static TagBuilder GetTagBuilder(this IShape shape, string defaultTagName { var tagName = defaultTagName; - // We keep this for backward compatibility + // We keep this for backward compatibility. if (shape.TryGetProperty("Tag", out string valueString)) { tagName = valueString; @@ -121,13 +120,7 @@ public static TagBuilder GetTagBuilder(this IShape shape, string defaultTagName return tagBuilder; } - private static readonly JsonSerializer ShapeSerializer = new JsonSerializer - { - ReferenceLoopHandling = ReferenceLoopHandling.Ignore - }; - - public static JObject ShapeToJson(this IShape shape) - => new ShapeSerializer(shape).Serialize(); + public static JObject 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 a094d612a1c..682cdcf9b72 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/IShapeFactory.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/IShapeFactory.cs @@ -25,8 +25,8 @@ public interface IShapeFactory public static class ShapeFactoryExtensions { - private static readonly ProxyGenerator ProxyGenerator = new ProxyGenerator(); - private static readonly Func> NewShape = () => new ValueTask(new Shape()); + private static readonly ProxyGenerator _proxyGenerator = new(); + private static readonly Func> _newShape = () => new(new Shape()); /// /// Creates a new shape by copying the properties of the specific model. @@ -52,13 +52,13 @@ private static IShape CreateShape(Type baseType) { var options = new ProxyGenerationOptions(); options.AddMixinInstance(new ShapeViewModel()); - return (IShape)ProxyGenerator.CreateClassProxy(baseType, options); + return (IShape)_proxyGenerator.CreateClassProxy(baseType, options); } } public static ValueTask CreateAsync(this IShapeFactory factory, string shapeType) { - return factory.CreateAsync(shapeType, NewShape); + return factory.CreateAsync(shapeType, _newShape); } public static ValueTask CreateAsync(this IShapeFactory factory, string shapeType, Func> shapeFactory) @@ -122,7 +122,7 @@ public static ValueTask CreateAsync(this IShapeFactory factory, strin return factory.CreateAsync(shapeType); } - return factory.CreateAsync(shapeType, NewShape, null, createdContext => + return factory.CreateAsync(shapeType, _newShape, null, createdContext => { var shape = (Shape)createdContext.Shape; diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultHtmlDisplay.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultHtmlDisplay.cs index 6688d6639ca..c0c798f33b9 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultHtmlDisplay.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultHtmlDisplay.cs @@ -55,16 +55,18 @@ public async Task ExecuteAsync(DisplayContext context) var shapeMetadata = shape.Metadata; - // can't really cope with a shape that has no type information + // Can't really cope with a shape that has no type information. if (shapeMetadata == null || String.IsNullOrEmpty(shapeMetadata.Type)) { return new HtmlContentString(context.Value.ToString()); } - // Copy the current context such that the rendering can customize it if necessary - // For instance to change the HtmlFieldPrefix - var localContext = new DisplayContext(context); - localContext.HtmlFieldPrefix = shapeMetadata.Prefix ?? ""; + // 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 displayContext = new ShapeDisplayContext { @@ -78,7 +80,7 @@ public async Task ExecuteAsync(DisplayContext context) var theme = await _themeManager.GetThemeAsync(); var shapeTable = _shapeTableManager.GetShapeTable(theme?.Id); - // Evaluate global Shape Display Events + // Evaluate global Shape Display Events. await _shapeDisplayEvents.InvokeAsync((e, displayContext) => e.DisplayingAsync(displayContext), displayContext, _logger); // Find base shape association using only the fundamental shape type. @@ -88,7 +90,7 @@ public async Task ExecuteAsync(DisplayContext context) { await shapeDescriptor.DisplayingAsync.InvokeAsync((action, displayContext) => action(displayContext), displayContext, _logger); - // copy all binding sources (all templates for this shape) in order to use them as Localization scopes + // Copy all binding sources (all templates for this shape) in order to use them as Localization scopes. shapeMetadata.BindingSources = shapeDescriptor.BindingSources.Where(x => x != null).ToList(); if (!shapeMetadata.BindingSources.Any()) { @@ -96,10 +98,10 @@ public async Task ExecuteAsync(DisplayContext context) } } - // invoking ShapeMetadata displaying events + // Invoking ShapeMetadata displaying events. shapeMetadata.Displaying.Invoke(action => action(displayContext), _logger); - // use pre-fetched content if available (e.g. coming from specific cache implementation) + // Use pre-fetched content if available (e.g. coming from specific cache implementation). if (displayContext.ChildContent != null) { shape.Metadata.ChildContent = displayContext.ChildContent; @@ -113,7 +115,7 @@ public async Task ExecuteAsync(DisplayContext context) await shapeDescriptor.ProcessingAsync.InvokeAsync((action, displayContext) => action(displayContext), displayContext, _logger); } - // now find the actual binding to render, taking alternates into account + // Now find the actual binding to render, taking alternates into account. var actualBinding = await GetShapeBindingAsync(shapeMetadata.Type, shapeMetadata.Alternates, shapeTable); if (actualBinding != null) { @@ -127,7 +129,7 @@ public async Task ExecuteAsync(DisplayContext context) } } - // Process wrappers + // Process wrappers. if (shape.Metadata.Wrappers.Count > 0) { foreach (var frameType in shape.Metadata.Wrappers) @@ -139,7 +141,7 @@ public async Task ExecuteAsync(DisplayContext context) } } - // Clear wrappers to prevent the child content from rendering them again + // Clear wrappers to prevent the child content from rendering them again. shape.Metadata.Wrappers.Clear(); } @@ -149,7 +151,7 @@ public async Task ExecuteAsync(DisplayContext context) await e.DisplayedAsync(displayContext); - // update the child content if the context variable has been reassigned + // Update the child content if the context variable has been reassigned. if (prior != displayContext.ChildContent) { displayContext.Shape.Metadata.ChildContent = displayContext.ChildContent; @@ -164,7 +166,7 @@ public async Task ExecuteAsync(DisplayContext context) await action(displayContext); - // update the child content if the context variable has been reassigned + // Update the child content if the context variable has been reassigned. if (prior != displayContext.ChildContent) { displayContext.Shape.Metadata.ChildContent = displayContext.ChildContent; @@ -172,7 +174,7 @@ public async Task ExecuteAsync(DisplayContext context) }, displayContext, _logger); } - // invoking ShapeMetadata displayed events + // Invoking ShapeMetadata displayed events. shapeMetadata.Displayed.Invoke((action, displayContext) => action(displayContext), displayContext, _logger); } finally @@ -198,7 +200,7 @@ private static ShapeDescriptor GetShapeDescriptor(string shapeType, ShapeTable s if (index > 0) { // Try again by using the fundamental shape type without any '__' separator. - shapeTable.Descriptors.TryGetValue(shapeType.Substring(0, index), out shapeDescriptor); + shapeTable.Descriptors.TryGetValue(shapeType[..index], out shapeDescriptor); } } @@ -207,10 +209,10 @@ private static ShapeDescriptor GetShapeDescriptor(string shapeType, ShapeTable s private async Task GetShapeBindingAsync(string shapeType, AlternatesCollection shapeAlternates, ShapeTable shapeTable) { - // shape alternates are optional, fully qualified binding names - // the earliest added alternates have the lowest priority + // Shape alternates are optional, fully qualified binding names, + // the earliest added alternates have the lowest priority, // the descriptor returned is based on the binding that is matched, so it may be an entirely - // different descriptor if the alternate has a different base name + // different descriptor if the alternate has a different base name. for (var i = shapeAlternates.Count - 1; i >= 0; i--) { var shapeAlternate = shapeAlternates[i]; @@ -231,9 +233,9 @@ private async Task GetShapeBindingAsync(string shapeType, Alternat } } - // when no alternates match, the shapeType is used to find the longest matching binding - // the shapetype name can break itself into shorter fallbacks at double-underscore marks - // so the shapetype itself may contain a longer alternate forms that falls back to a shorter one + // When no alternates matches, the shapeType is used to find the longest matching binding, + // the shapetype name can break itself into shorter fallbacks at double-underscore marks, + // so the shapetype itself may contain a longer alternate forms that falls back to a shorter one. var shapeTypeScan = shapeType; do @@ -263,9 +265,10 @@ private static bool TryGetParentShapeTypeName(ref string shapeTypeScan) var delimiterIndex = shapeTypeScan.LastIndexOf("__", StringComparison.Ordinal); if (delimiterIndex > 0) { - shapeTypeScan = shapeTypeScan.Substring(0, delimiterIndex); + shapeTypeScan = shapeTypeScan[..delimiterIndex]; return true; } + return false; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultShapeFactory.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultShapeFactory.cs index 7ca09fa4384..277253a4265 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultShapeFactory.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Implementation/DefaultShapeFactory.cs @@ -38,10 +38,12 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o if (binderName.EndsWith("Async", StringComparison.Ordinal)) { - binderName = binder.Name.Substring(binder.Name.Length - "Async".Length); + binderName = binder.Name[^"Async".Length..]; } - result = ShapeFactoryExtensions.CreateAsync(this, binderName, Arguments.From(args, binder.CallInfo.ArgumentNames)); + result = ShapeFactoryExtensions + .CreateAsync(this, binderName, Arguments.From(args, binder.CallInfo.ArgumentNames)) + .AsTask(); return true; } @@ -74,7 +76,7 @@ public async ValueTask CreateAsync(string shapeType, Func CreateAsync(string shapeType, Func CreateAsync(string shapeType, Func 0) { shapeMetadata.Wrappers.AddRange(shapeDescriptor.Wrappers); } - // "created" events provides default values and new object initialization + // 'Created' events provides default values and new object initialization. foreach (var ev in _events) { ev.Created(createdContext); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Layout/LayoutAccessor.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Layout/LayoutAccessor.cs index 1a5bace34d7..bb1d236d051 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Layout/LayoutAccessor.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Layout/LayoutAccessor.cs @@ -16,15 +16,14 @@ public LayoutAccessor(IShapeFactory shapeFactory) public async Task GetLayoutAsync() { - if (_layout == null) - { - // 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; - } + // 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; if (_layout == null) { - // At this point a Layout shape should always exist + // At this point a Layout shape should always exist. throw new ApplicationException("Fatal error, a Layout couldn't be created."); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/LocalModelBinderAccessor.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/LocalModelBinderAccessor.cs index 541882bd744..7751814ce0f 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/LocalModelBinderAccessor.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ModelBinding/LocalModelBinderAccessor.cs @@ -4,7 +4,7 @@ namespace OrchardCore.DisplayManagement.ModelBinding { public class LocalModelBinderAccessor : IUpdateModelAccessor { - private readonly static object Key = typeof(LocalModelBinderAccessor); + private static readonly object _key = typeof(LocalModelBinderAccessor); private readonly IHttpContextAccessor _httpContextAccessor; public LocalModelBinderAccessor(IHttpContextAccessor httpContextAccessor) @@ -16,11 +16,11 @@ public IUpdateModel ModelUpdater { get { - var updateModel = _httpContextAccessor.HttpContext.Items[Key] as IUpdateModel; + var updateModel = _httpContextAccessor.HttpContext.Items[_key] as IUpdateModel; return updateModel ?? new NullModelUpdater(); } - set { _httpContextAccessor.HttpContext.Items[Key] = value; } + set { _httpContextAccessor.HttpContext.Items[_key] = value; } } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyEntryConverter.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyEntryConverter.cs index a2c0965bf0e..b63ac09ff1b 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyEntryConverter.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyEntryConverter.cs @@ -28,8 +28,10 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist NotifyType type; - var notifyEntry = new NotifyEntry(); - notifyEntry.Message = new HtmlString(jo.Value("Message")); + var notifyEntry = new NotifyEntry + { + Message = new HtmlString(jo.Value("Message")), + }; if (Enum.TryParse(jo.Value("Type"), out type)) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyFilter.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyFilter.cs index e9064de325c..768fcfac0b7 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyFilter.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Notify/NotifyFilter.cs @@ -56,7 +56,7 @@ private void OnHandlerExecuting(FilterContext filterContext) if (messageEntries == null) { - // An error occurred during deserialization + // An error occurred during deserialization. _shouldDeleteCookie = true; return; } @@ -161,7 +161,7 @@ public async Task OnResultExecutionAsync(ResultExecutingContext filterContext, R await next(); } - private void DeleteCookies(ResultExecutingContext filterContext) + private static void DeleteCookies(ResultExecutingContext filterContext) { filterContext.HttpContext.Response.Cookies.Delete(CookiePrefix, GetCookieOptions(filterContext.HttpContext)); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ObjectPool.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ObjectPool.cs index 96993fbdacd..82cb23f1899 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ObjectPool.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ObjectPool.cs @@ -121,7 +121,7 @@ internal T Allocate() // Note that the initial read is optimistically not synchronized. That is intentional. // We will interlock only when we have a candidate. in a worst case we may miss some // recently returned objects. Not a big deal. - T inst = _firstItem; + var inst = _firstItem; if (inst == null || inst != Interlocked.CompareExchange(ref _firstItem, null, inst)) { inst = AllocateSlow(); @@ -143,12 +143,12 @@ private T AllocateSlow() { var items = _items; - for (int i = 0; i < items.Length; i++) + for (var i = 0; i < items.Length; i++) { // Note that the initial read is optimistically not synchronized. That is intentional. // We will interlock only when we have a candidate. in a worst case we may miss some // recently returned objects. Not a big deal. - T inst = items[i].Value; + var inst = items[i].Value; if (inst != null) { if (inst == Interlocked.CompareExchange(ref items[i].Value, null, inst)) @@ -187,7 +187,7 @@ internal void Free(T obj) private void FreeSlow(T obj) { var items = _items; - for (int i = 0; i < items.Length; i++) + for (var i = 0; i < items.Length; i++) { if (items[i].Value == null) { @@ -213,10 +213,10 @@ public sealed class StringBuilderPool : IDisposable { private const int DefaultCapacity = 1 * 1024; - // global pool - private static readonly ObjectPool s_poolInstance = CreatePool(); + // Global pool. + private static readonly ObjectPool _poolInstance = CreatePool(); - public readonly StringBuilder Builder = new StringBuilder(DefaultCapacity); + public readonly StringBuilder Builder = new(DefaultCapacity); private readonly ObjectPool _pool; private StringBuilderPool(ObjectPool pool) @@ -236,7 +236,7 @@ internal static ObjectPool CreatePool(int size = 1000) public static StringBuilderPool GetInstance() { - var builder = s_poolInstance.Allocate(); + var builder = _poolInstance.Allocate(); Debug.Assert(builder.Builder.Length == 0); return builder; } @@ -251,7 +251,6 @@ public void Dispose() var builder = Builder; // Do not store builders that are too large. - if (builder.Capacity == DefaultCapacity) { builder.Clear(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/PositionWrapper.cs b/src/OrchardCore/OrchardCore.DisplayManagement/PositionWrapper.cs index 900cb85ea9d..a955adcdeec 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/PositionWrapper.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/PositionWrapper.cs @@ -10,7 +10,7 @@ namespace OrchardCore.DisplayManagement { public class PositionWrapper : IHtmlContent, IPositioned, IShape { - private IHtmlContent _value; + private readonly IHtmlContent _value; public string Position { get; set; } public ShapeMetadata Metadata { get; set; } = new ShapeMetadata(); @@ -24,6 +24,7 @@ public class PositionWrapper : IHtmlContent, IPositioned, IShape public IDictionary Attributes { get; } private Dictionary _properties; + public IDictionary Properties => _properties ??= new Dictionary(); public IReadOnlyList Items => throw new System.NotImplementedException(); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorPage.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorPage.cs index 605f0ae533c..0fbd1aa8b1e 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorPage.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorPage.cs @@ -35,21 +35,9 @@ public override ViewContext ViewContext } } - private void EnsureDisplayHelper() - { - if (_displayHelper == null) - { - _displayHelper = Context.RequestServices.GetService(); - } - } + private void EnsureDisplayHelper() => _displayHelper ??= Context.RequestServices.GetService(); - private void EnsureShapeFactory() - { - if (_shapeFactory == null) - { - _shapeFactory = Context.RequestServices.GetService(); - } - } + private void EnsureShapeFactory() => _shapeFactory ??= Context.RequestServices.GetService(); /// /// Gets a dynamic shape factory to create new shapes. @@ -129,20 +117,8 @@ public IOrchardDisplayHelper Orchard public IZoneHolding ThemeLayout { - get - { - if (_themeLayout == null) - { - _themeLayout = Context.Features.Get()?.ThemeLayout; - } - - return _themeLayout; - } - - set - { - _themeLayout = value; - } + get => _themeLayout ??= Context.Features.Get()?.ThemeLayout; + set => _themeLayout = value; } public string ViewLayout @@ -183,18 +159,7 @@ public string ViewLayout private IPageTitleBuilder _pageTitleBuilder; - public IPageTitleBuilder Title - { - get - { - if (_pageTitleBuilder == null) - { - _pageTitleBuilder = Context.RequestServices.GetRequiredService(); - } - - return _pageTitleBuilder; - } - } + public IPageTitleBuilder Title => _pageTitleBuilder ??= Context.RequestServices.GetRequiredService(); private IViewLocalizer _t; @@ -248,21 +213,14 @@ public IHtmlContent RenderTitleSegments(string segment, string position = "0", I /// /// Renders the content zone of the layout. /// - public IHtmlContent RenderLayoutBody() - { - var result = base.RenderBody(); - return result; - } + public IHtmlContent RenderLayoutBody() => base.RenderBody(); /// /// Creates a to render a shape. /// /// The shape. /// A new . - public TagBuilder Tag(IShape shape) - { - return shape.GetTagBuilder(); - } + public static TagBuilder Tag(IShape shape) => shape.GetTagBuilder(); /// /// Creates a to render a shape. @@ -270,19 +228,13 @@ public TagBuilder Tag(IShape shape) /// The shape. /// The tag name to use. /// A new . - public TagBuilder Tag(IShape shape, string tag) - { - return shape.GetTagBuilder(tag); - } + public static TagBuilder Tag(IShape shape, string tag) => shape.GetTagBuilder(tag); /// /// In a Razor layout page, renders the portion of a content page that is not within a named zone. /// /// The HTML content to render. - public Task RenderBodyAsync() - { - return DisplayAsync(ThemeLayout.Zones["Content"]); - } + public Task RenderBodyAsync() => DisplayAsync(ThemeLayout.Zones["Content"]); /// /// Check if a zone is defined in the layout or it has items. @@ -374,7 +326,7 @@ public new Task RenderSectionAsync(string name, bool required) return DisplayAsync(zone); } - public object OrDefault(object text, object other) + public static object OrDefault(object text, object other) { if (text == null || Convert.ToString(text) == "") { @@ -392,18 +344,7 @@ public object OrDefault(object text, object other) /// /// Gets the instance. /// - public ISite Site - { - get - { - if (_site == null) - { - _site = Context.Features.Get()?.Site; - } - - return _site; - } - } + public ISite Site => _site ??= Context.Features.Get()?.Site; } public abstract class RazorPage : RazorPage diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorShapeTemplateViewEngine.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorShapeTemplateViewEngine.cs index ac8547035e2..500b4e614a0 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorShapeTemplateViewEngine.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Razor/RazorShapeTemplateViewEngine.cs @@ -28,7 +28,7 @@ public class RazorShapeTemplateViewEngine : IShapeTemplateViewEngine private readonly IHttpContextAccessor _httpContextAccessor; private readonly ViewContextAccessor _viewContextAccessor; private readonly ITempDataProvider _tempDataProvider; - private readonly List _templateFileExtensions = new List(new[] { RazorViewEngine.ViewExtension }); + private readonly List _templateFileExtensions = new(new[] { RazorViewEngine.ViewExtension }); public RazorShapeTemplateViewEngine( IOptions options, @@ -79,7 +79,7 @@ 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.", + 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)); @@ -118,7 +118,7 @@ public async Task RenderViewToStringAsync(string viewName, object model, return output.ToString(); } - private IView FindView(ActionContext actionContext, string viewName, IViewEngine viewEngine) + private static IView FindView(ActionContext actionContext, string viewName, IViewEngine viewEngine) { var getViewResult = viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true); if (getViewResult.Success) @@ -133,7 +133,7 @@ private IView FindView(ActionContext actionContext, string viewName, IViewEngine } var searchedLocations = getViewResult.SearchedLocations.Concat(findViewResult.SearchedLocations); - var errorMessage = string.Join( + var errorMessage = String.Join( System.Environment.NewLine, new[] { $"Unable to find view '{viewName}'. The following locations were searched:" }.Concat(searchedLocations)); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/RazorPages/Page.cs b/src/OrchardCore/OrchardCore.DisplayManagement/RazorPages/Page.cs index b7f28e8aa8a..d2db8870dbd 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/RazorPages/Page.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/RazorPages/Page.cs @@ -31,21 +31,9 @@ public override ViewContext ViewContext } } - private void EnsureDisplayHelper() - { - if (_displayHelper == null) - { - _displayHelper = HttpContext.RequestServices.GetService(); - } - } + private void EnsureDisplayHelper() => _displayHelper ??= HttpContext.RequestServices.GetService(); - private void EnsureShapeFactory() - { - if (_shapeFactory == null) - { - _shapeFactory = HttpContext.RequestServices.GetService(); - } - } + private void EnsureShapeFactory() => _shapeFactory ??= HttpContext.RequestServices.GetService(); /// /// Gets a dynamic shape factory to create new shapes. @@ -125,20 +113,8 @@ public IOrchardDisplayHelper Orchard public IZoneHolding ThemeLayout { - get - { - if (_themeLayout == null) - { - _themeLayout = HttpContext.Features.Get()?.ThemeLayout; - } - - return _themeLayout; - } - - set - { - _themeLayout = value; - } + get => _themeLayout ??= HttpContext.Features.Get()?.ThemeLayout; + set => _themeLayout = value; } public string ViewLayout @@ -179,18 +155,7 @@ public string ViewLayout private IPageTitleBuilder _pageTitleBuilder; - public IPageTitleBuilder Title - { - get - { - if (_pageTitleBuilder == null) - { - _pageTitleBuilder = HttpContext.RequestServices.GetRequiredService(); - } - - return _pageTitleBuilder; - } - } + public IPageTitleBuilder Title => _pageTitleBuilder ??= HttpContext.RequestServices.GetRequiredService(); private IViewLocalizer _t; @@ -242,10 +207,7 @@ public IHtmlContent RenderTitleSegments(string segment, string position = "0", I /// /// The shape. /// A new . - public TagBuilder Tag(IShape shape) - { - return shape.GetTagBuilder(); - } + public static TagBuilder Tag(IShape shape) => shape.GetTagBuilder(); /// /// Creates a to render a shape. @@ -253,10 +215,7 @@ public TagBuilder Tag(IShape shape) /// The shape. /// The tag name to use. /// A new . - public TagBuilder Tag(IShape shape, string tag) - { - return shape.GetTagBuilder(tag); - } + public static TagBuilder Tag(IShape shape, string tag) => shape.GetTagBuilder(tag); /// /// Check if a zone is defined in the layout or it has items. @@ -311,7 +270,7 @@ public Task RenderSectionAsync(string name, bool required) return DisplayAsync(zone); } - public object OrDefault(object text, object other) + public static object OrDefault(object text, object other) { if (text == null || Convert.ToString(text) == "") { @@ -329,17 +288,6 @@ public object OrDefault(object text, object other) /// /// Gets the instance. /// - public ISite Site - { - get - { - if (_site == null) - { - _site = HttpContext.Features.Get()?.Site; - } - - return _site; - } - } + public ISite Site => _site ??= HttpContext.Features.Get()?.Site; } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/ShapeAttribute.cs b/src/OrchardCore/OrchardCore.DisplayManagement/ShapeAttribute.cs index aa9ea1070e3..6a98bf8e312 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/ShapeAttribute.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/ShapeAttribute.cs @@ -2,6 +2,7 @@ namespace OrchardCore.DisplayManagement { + [AttributeUsage(AttributeTargets.Method)] public class ShapeAttribute : Attribute { public ShapeAttribute() diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/AlternatesCollection.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/AlternatesCollection.cs index e2e87cdb4ad..3a4072fae35 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/AlternatesCollection.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/AlternatesCollection.cs @@ -11,7 +11,7 @@ namespace OrchardCore.DisplayManagement.Shapes /// public class AlternatesCollection : IEnumerable { - public static AlternatesCollection Empty = new AlternatesCollection(); + public static readonly AlternatesCollection Empty = new(); private KeyedAlternateCollection _collection; @@ -111,10 +111,7 @@ public void AddRange(IEnumerable alternates) private void EnsureCollection() { - if (_collection == null) - { - _collection = new KeyedAlternateCollection(); - } + _collection ??= new KeyedAlternateCollection(); } public IEnumerator GetEnumerator() diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Composite.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Composite.cs index 14884626c08..25f1676dbc5 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Composite.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Composite.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; @@ -7,7 +8,7 @@ namespace OrchardCore.DisplayManagement.Shapes { public class Composite : DynamicObject { - protected readonly Dictionary _properties = new Dictionary(); + protected readonly Dictionary _properties = new(); public override bool TryGetMember(GetMemberBinder binder, out object result) { @@ -43,7 +44,7 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o return TryGetMemberImpl(binder.Name, out result); } - // method call with one argument will assign the property + // Method call with one argument will assign the property. if (args.Length == 1) { result = this; @@ -54,7 +55,7 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o { if (binder.Name == "ToString") { - result = string.Empty; + result = String.Empty; return true; } @@ -116,7 +117,7 @@ public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object get { return _properties; } } - public static bool operator ==(Composite a, Nil b) + public static bool operator ==(Composite a, Nil _) { return null == a; } @@ -133,18 +134,21 @@ protected bool Equals(Composite other) public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) { return false; } + if (ReferenceEquals(this, obj)) { return true; } - if (obj.GetType() != this.GetType()) + + if (obj.GetType() != GetType()) { return false; } + return Equals((Composite)obj); } @@ -156,8 +160,8 @@ public override int GetHashCode() public class Nil : DynamicObject { - private static readonly Nil Singleton = new Nil(); - public static Nil Instance { get { return Singleton; } } + private static readonly Nil _singleton = new(); + public static Nil Instance { get { return _singleton; } } private Nil() { @@ -186,29 +190,29 @@ public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg switch (binder.Operation) { case ExpressionType.Equal: - result = ReferenceEquals(arg, Nil.Instance) || (object)arg == null; + result = ReferenceEquals(arg, Nil.Instance) || arg == null; return true; case ExpressionType.NotEqual: - result = !ReferenceEquals(arg, Nil.Instance) && (object)arg != null; + result = !ReferenceEquals(arg, Nil.Instance) && arg != null; return true; } return base.TryBinaryOperation(binder, arg, out result); } - public static bool operator ==(Nil a, Nil b) + public static bool operator ==(Nil _1, Nil _2) { return true; } - public static bool operator !=(Nil a, Nil b) + public static bool operator !=(Nil _1, Nil _2) { return false; } public static bool operator ==(Nil a, object b) { - return ReferenceEquals(a, b) || (object)b == null; + return ReferenceEquals(a, b) || b == null; } public static bool operator !=(Nil a, object b) @@ -239,7 +243,7 @@ public override bool TryConvert(ConvertBinder binder, out object result) public override string ToString() { - return string.Empty; + return String.Empty; } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/CoreShapes.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/CoreShapes.cs index d13d971f68d..864dd032676 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/CoreShapes.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/CoreShapes.cs @@ -21,7 +21,9 @@ 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, +#pragma warning restore CA1822 // Mark members as static string ItemTagName, IEnumerable ItemClasses, IDictionary ItemAttributes, @@ -40,11 +42,11 @@ public void PlaceChildContent(dynamic Source, TextWriter Output) } } - // prevent multiple enumerations + // Prevent multiple enumerations. var items = Items.ToList(); // var itemDisplayOutputs = Items.Select(item => Display(item)).Where(output => !string.IsNullOrWhiteSpace(output.ToHtmlString())).ToList(); - var count = items.Count(); + var count = items.Count; if (count < 1) { return HtmlString.Empty; @@ -102,10 +104,12 @@ public void PlaceChildContent(dynamic Source, TextWriter Output) } [Shape] +#pragma warning disable CA1822 // Mark members as static public IHtmlContent Message(IShape Shape) +#pragma warning restore CA1822 // Mark members as static { var tagBuilder = Shape.GetTagBuilder("div"); - string type = Shape.Properties["Type"].ToString().ToLowerInvariant(); + var type = Shape.Properties["Type"].ToString().ToLowerInvariant(); var message = Shape.Properties["Message"] as IHtmlContent; tagBuilder.AddCssClass("message"); tagBuilder.AddCssClass("message-" + type); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/DateTimeShapes.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/DateTimeShapes.cs index 3d2b968bc5e..a54ef37848c 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/DateTimeShapes.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/DateTimeShapes.cs @@ -16,8 +16,8 @@ public class DateTimeShapes : IShapeAttributeProvider private const string LongDateTimeFormat = "dddd, MMMM d, yyyy h:mm:ss tt"; private readonly IClock _clock; private readonly ILocalClock _localClock; - private readonly IStringLocalizer S; - private readonly IHtmlLocalizer H; + protected readonly IStringLocalizer S; + protected readonly IHtmlLocalizer H; public DateTimeShapes( IClock clock, @@ -33,47 +33,82 @@ ILocalClock localClock } [Shape] - public IHtmlContent TimeSpan(IHtmlHelper Html, DateTime? Utc, DateTime? Origin) + public IHtmlContent TimeSpan(DateTime? Utc, DateTime? Origin) { - Utc = Utc ?? _clock.UtcNow; - Origin = Origin ?? _clock.UtcNow; + Utc ??= _clock.UtcNow; + Origin ??= _clock.UtcNow; - var time = _clock.UtcNow - Utc.Value; + var time = Origin.Value - Utc.Value; if (time.TotalYears() > 1) + { return H.Plural(time.TotalYears(), "1 year ago", "{0} years ago"); + } + if (time.TotalYears() < -1) + { return H.Plural(-time.TotalYears(), "in 1 year", "in {0} years"); + } if (time.TotalMonths() > 1) + { return H.Plural(time.TotalMonths(), "1 month ago", "{0} months ago"); + } + if (time.TotalMonths() < -1) + { return H.Plural(-time.TotalMonths(), "in 1 month", "in {0} months"); + } if (time.TotalWeeks() > 1) + { return H.Plural(time.TotalWeeks(), "1 week ago", "{0} weeks ago"); + } + if (time.TotalWeeks() < -1) + { return H.Plural(-time.TotalWeeks(), "in 1 week", "in {0} weeks"); + } if (time.TotalHours > 24) + { return H.Plural(time.Days, "1 day ago", "{0} days ago"); + } + if (time.TotalHours < -24) + { return H.Plural(-time.Days, "in 1 day", "in {0} days"); + } if (time.TotalMinutes > 60) + { return H.Plural(time.Hours, "1 hour ago", "{0} hours ago"); + } + if (time.TotalMinutes < -60) + { return H.Plural(-time.Hours, "in 1 hour", "in {0} hours"); + } if (time.TotalSeconds > 60) + { return H.Plural(time.Minutes, "1 minute ago", "{0} minutes ago"); + } + if (time.TotalSeconds < -60) + { return H.Plural(-time.Minutes, "in 1 minute", "in {0} minutes"); + } if (time.TotalSeconds > 10) - return H.Plural(time.Seconds, "1 second ago", "{0} seconds ago"); //aware that the singular won't be used + { + return H.Plural(time.Seconds, "1 second ago", "{0} seconds ago"); // Aware that the singular won't be used. + } + if (time.TotalSeconds < -10) + { return H.Plural(-time.Seconds, "in 1 second", "in {0} seconds"); + } return time.TotalMilliseconds > 0 ? H["a moment ago"] @@ -83,13 +118,9 @@ public IHtmlContent TimeSpan(IHtmlHelper Html, DateTime? Utc, DateTime? Origin) [Shape] public async Task DateTime(IHtmlHelper Html, DateTime? Utc, string Format) { - Utc = Utc ?? _clock.UtcNow; + Utc ??= _clock.UtcNow; var zonedTime = await _localClock.ConvertToLocalAsync(Utc.Value); - - if (Format == null) - { - Format = S[LongDateTimeFormat].Value; - } + Format ??= S[LongDateTimeFormat].Value; return Html.Raw(Html.Encode(zonedTime.ToString(Format, CultureInfo.CurrentUICulture))); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/GroupShapes.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/GroupShapes.cs index 99d319dd11e..688529b7320 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/GroupShapes.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/GroupShapes.cs @@ -14,6 +14,7 @@ namespace OrchardCore.DisplayManagement.Shapes public class GroupShapes : IShapeAttributeProvider { [Shape] +#pragma warning disable CA1822 // Mark members as static public IHtmlContent AdminTabs(IShape shape) { var tabsGrouping = shape.GetProperty>>("Tabs"); @@ -215,5 +216,6 @@ public Task LocalNavigation(IDisplayHelper displayAsync, IShape sh return displayAsync.ShapeExecuteAsync(shape); } +#pragma warning restore CA1822 // Mark members as static } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/PageTitleShapes.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/PageTitleShapes.cs index 0b617199db3..bfe485f95de 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/PageTitleShapes.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/PageTitleShapes.cs @@ -17,18 +17,7 @@ public class PageTitleShapes : IShapeAttributeProvider { private IPageTitleBuilder _pageTitleBuilder; - public IPageTitleBuilder Title - { - get - { - if (_pageTitleBuilder == null) - { - _pageTitleBuilder = ShellScope.Services.GetRequiredService(); - } - - return _pageTitleBuilder; - } - } + public IPageTitleBuilder Title => _pageTitleBuilder ??= ShellScope.Services.GetRequiredService(); [Shape] public async Task PageTitle() diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Shape.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Shape.cs index 177b709141a..b0a7d8a4c36 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Shape.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/Shape.cs @@ -59,10 +59,7 @@ public virtual ValueTask AddAsync(object item, string position) return new ValueTask(this); } - if (position == null) - { - position = ""; - } + position ??= ""; _sorted = false; @@ -192,10 +189,13 @@ public override bool TryConvert(ConvertBinder binder, out object result) public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { - // In case AddAsync() is called on a dynamic object, to prevent Copmosite from seing it as a property assignment + // 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() : ""); + result = + AddAsync(args.Length > 0 ? args[0] : null, args.Length > 1 ? args[1].ToString() : "") + .AsTask(); + return true; } @@ -211,13 +211,10 @@ protected override bool TryGetMemberImpl(string name, out object result) { if (!base.TryGetMemberImpl(name, out result) || (null == result)) { - // Try to get a Named shape + // Try to get a Named shape. result = Named(name); - if (result == null) - { - result = NormalizedNamed(name.Replace("__", "-")); - } + result ??= NormalizedNamed(name.Replace("__", "-")); } return true; @@ -225,7 +222,7 @@ protected override bool TryGetMemberImpl(string name, out object result) protected override bool TrySetMemberImpl(string name, object value) { - // We set the Shape real properties for Razor + // We set the Shape real properties for Razor. if (name == "Id") { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeDebugView.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeDebugView.cs index 540a75e0cf5..a8e43cbae2b 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeDebugView.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeDebugView.cs @@ -47,13 +47,15 @@ public KeyValuePairs(string key, object value) } [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string _key; +#pragma warning disable IDE0052 // Remove unread private members + private readonly string _key; +#pragma warning restore IDE0052 // Remove unread private members [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private object _shapeType; + private readonly object _shapeType; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - private object _value; + private readonly object _value; } } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeSerializer.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeSerializer.cs index 5ba5c4b9fe5..dc871a1f425 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeSerializer.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeSerializer.cs @@ -15,12 +15,12 @@ namespace OrchardCore.DisplayManagement.Shapes public class ShapeSerializer { // This code is used for debugging so does not need to be performance optimized. - private static readonly JsonSerializer ShapeJsonSerializer = new JsonSerializer + private static readonly JsonSerializer _shapeJsonSerializer = new() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; - private readonly HashSet _shapes = new HashSet(); + private readonly HashSet _shapes = new(); private readonly IShape _shape; public ShapeSerializer(IShape shape) @@ -51,23 +51,23 @@ public JObject Serialize() jObject.Add("Shape", displayText); - var metadata = JObject.FromObject(_shape.Metadata, ShapeJsonSerializer); + var metadata = JObject.FromObject(_shape.Metadata, _shapeJsonSerializer); jObject.Add(nameof(ShapeMetadata), metadata); if (_shape.Classes != null && _shape.Classes.Any()) { - jObject.Add(nameof(_shape.Classes), JArray.FromObject(_shape.Classes, ShapeJsonSerializer)); + jObject.Add(nameof(_shape.Classes), JArray.FromObject(_shape.Classes, _shapeJsonSerializer)); } if (_shape.Attributes != null && _shape.Attributes.Any()) { - jObject.Add(nameof(_shape.Attributes), JObject.FromObject(_shape.Attributes, ShapeJsonSerializer)); + jObject.Add(nameof(_shape.Attributes), JObject.FromObject(_shape.Attributes, _shapeJsonSerializer)); } if (_shape.Properties != null && _shape.Properties.Any()) { - jObject.Add(nameof(_shape.Properties), JObject.FromObject(_shape.Properties, ShapeJsonSerializer)); + jObject.Add(nameof(_shape.Properties), JObject.FromObject(_shape.Properties, _shapeJsonSerializer)); FindShapesInProperties(_shape); } @@ -98,7 +98,7 @@ private void FindShapesInProperties(IShape shape) if (property is Shape shapeProperty && _shapes.Add(shapeProperty) && shapeProperty.HasItems) { var shapeItems = shapeProperty.Items.ToArray(); - foreach (IShape item in shapeItems) + foreach (var item in shapeItems.Cast()) { if (item is IShape shapeItem && _shapes.Add(shapeItem)) { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/BaseShapeTagHelper.cs b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/BaseShapeTagHelper.cs index 56cfd21955b..e420aa26246 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/BaseShapeTagHelper.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/TagHelpers/BaseShapeTagHelper.cs @@ -8,14 +8,15 @@ namespace OrchardCore.DisplayManagement.TagHelpers { public abstract class BaseShapeTagHelper : TagHelper { - private static readonly HashSet InternalProperties = new HashSet + protected const string PropertyDictionaryName = "prop-all"; + protected const string PropertyPrefix = "prop-"; + + private static readonly HashSet _internalProperties = new() { "id", "alternate", "wrapper", "cache-id", "cache-context", "cache-tag", "cache-fixed-duration", "cache-sliding-duration" }; - protected const string PropertyDictionaryName = "prop-all"; - protected const string PropertyPrefix = "prop-"; - private static readonly char[] Separators = { ',', ' ' }; + private static readonly char[] _separators = { ',', ' ' }; protected IShapeFactory _shapeFactory; protected IDisplayHelper _displayHelper; @@ -59,7 +60,7 @@ public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHe foreach (var pair in output.Attributes) { // Check it's not a reserved property name - if (!InternalProperties.Contains(pair.Name)) + if (!_internalProperties.Contains(pair.Name)) { var normalizedName = pair.Name.ToPascalCaseDash(); @@ -70,22 +71,22 @@ public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHe } } - if (string.IsNullOrWhiteSpace(Type)) + if (String.IsNullOrWhiteSpace(Type)) { Type = output.TagName; } - if (string.IsNullOrWhiteSpace(Cache) && output.Attributes.ContainsName("cache-id")) + if (String.IsNullOrWhiteSpace(Cache) && output.Attributes.ContainsName("cache-id")) { Cache = Convert.ToString(output.Attributes["cache-id"].Value); } - if (string.IsNullOrWhiteSpace(Context) && output.Attributes.ContainsName("cache-context")) + if (String.IsNullOrWhiteSpace(Context) && output.Attributes.ContainsName("cache-context")) { Context = Convert.ToString(output.Attributes["cache-context"].Value); } - if (string.IsNullOrWhiteSpace(Tag) && output.Attributes.ContainsName("cache-tag")) + if (String.IsNullOrWhiteSpace(Tag) && output.Attributes.ContainsName("cache-tag")) { Tag = Convert.ToString(output.Attributes["cache-tag"].Value); } @@ -127,7 +128,7 @@ public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHe tagHelperContext.Items.Add(typeof(IShape), shape); - if (!string.IsNullOrWhiteSpace(Cache)) + if (!String.IsNullOrWhiteSpace(Cache)) { var metadata = shape.Metadata; @@ -143,15 +144,15 @@ public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHe metadata.Cache().WithExpirySliding(SlidingDuration.Value); } - if (!string.IsNullOrWhiteSpace(Context)) + if (!String.IsNullOrWhiteSpace(Context)) { - var contexts = Context.Split(Separators, StringSplitOptions.RemoveEmptyEntries); + var contexts = Context.Split(_separators, StringSplitOptions.RemoveEmptyEntries); metadata.Cache().AddContext(contexts); } - if (!string.IsNullOrWhiteSpace(Tag)) + if (!String.IsNullOrWhiteSpace(Tag)) { - var tags = Tag.Split(Separators, StringSplitOptions.RemoveEmptyEntries); + var tags = Tag.Split(_separators, StringSplitOptions.RemoveEmptyEntries); metadata.Cache().AddTag(tags); } } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemingViewsFeatureProvider.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemingViewsFeatureProvider.cs index 7c4c646025c..cdb26100ccb 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemingViewsFeatureProvider.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Theming/ThemingViewsFeatureProvider.cs @@ -13,7 +13,7 @@ namespace OrchardCore.DisplayManagement.Theming /// public class ThemingViewsFeatureProvider : IApplicationFeatureProvider { - public static string ThemeLayoutFileName = "DefaultOrchardCoreThemingLayout" + RazorViewEngine.ViewExtension; + public static readonly string ThemeLayoutFileName = "DefaultOrchardCoreThemingLayout" + RazorViewEngine.ViewExtension; public ThemingViewsFeatureProvider() { diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Title/PageTitleBuilder.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Title/PageTitleBuilder.cs index 936a2d15559..f1654b978cd 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 HtmlString(" - "); + private readonly static HtmlString _defaultTitleSeparator = new(" - "); private readonly List _titleParts; private IHtmlContent _title; @@ -53,10 +53,7 @@ public IHtmlContent GenerateTitle(IHtmlContent separator) return _title; } - if (separator == null) - { - separator = DefaultTitleSeparator; - } + separator ??= _defaultTitleSeparator; _titleParts.Sort(FlatPositionComparer.Instance); diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeResult.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeResult.cs index 9fdb576bbef..9b2e8b89d46 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeResult.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeResult.cs @@ -53,16 +53,16 @@ public Task ApplyAsync(BuildEditorContext context) private async Task ApplyImplementationAsync(BuildShapeContext context, string displayType) { - // If no location is set from the driver, use the one from the context + // If no location is set from the driver, use the one from the context. if (String.IsNullOrEmpty(_defaultLocation)) { _defaultLocation = context.DefaultZone; } - // Look into specific implementations of placements (like placement.json files and IShapePlacementProviders) + // Look into specific implementations of placements (like placement.json files and IShapePlacementProviders). var placement = context.FindPlacement(_shapeType, _differentiator, displayType, context); - // Look for mapped display type locations + // Look for mapped display type locations. if (_otherLocations != null) { string displayTypePlacement; @@ -72,25 +72,16 @@ private async Task ApplyImplementationAsync(BuildShapeContext context, string di } } - // If no placement is found, use the default location - if (placement == null) - { - placement = new PlacementInfo() { Location = _defaultLocation }; - } + // If no placement is found, use the default location. + placement ??= new PlacementInfo() { Location = _defaultLocation }; - if (placement.Location == null) - { - // If a placement was found without actual location, use the default. - // It can happen when just setting alternates or wrappers for instance. - placement.Location = _defaultLocation; - } + // If a placement was found without actual location, use the default. + // It can happen when just setting alternates or wrappers for instance. + placement.Location ??= _defaultLocation; - if (placement.DefaultPosition == null) - { - placement.DefaultPosition = context.DefaultPosition; - } + placement.DefaultPosition ??= context.DefaultPosition; - // If there are no placement or it's explicitly noop then stop rendering execution + // If there are no placement or it's explicitly noop then stop rendering execution. if (String.IsNullOrEmpty(placement.Location) || placement.Location == "-") { return; @@ -99,7 +90,7 @@ private async Task ApplyImplementationAsync(BuildShapeContext context, string di // Parse group placement. _groupId = placement.GetGroup() ?? _groupId; - // If the shape's group doesn't match the currently rendered one, return + // If the shape's group doesn't match the currently rendered one, return. if (!String.Equals(context.GroupId ?? "", _groupId ?? "", StringComparison.OrdinalIgnoreCase)) { return; @@ -136,7 +127,7 @@ private async Task ApplyImplementationAsync(BuildShapeContext context, string di } // The _processing callback is used to delay execution of costly initialization - // that can be prevented by caching + // that can be prevented by caching. if (_processing != null) { newShapeMetadata.OnProcessing(_processing); @@ -188,12 +179,12 @@ private async Task ApplyImplementationAsync(BuildShapeContext context, string di if (parentShape is IZoneHolding layout) { - // parentShape is a ZoneHolding + // parentShape is a ZoneHolding. parentShape = layout.Zones[zone]; } else { - // try to access it as a member + // try to access it as a member. parentShape = parentShape.GetProperty(zone); } } @@ -232,11 +223,7 @@ public ShapeResult Location(string location) /// public ShapeResult Location(string displayType, string location) { - if (_otherLocations == null) - { - _otherLocations = new Dictionary(2); - } - + _otherLocations ??= new Dictionary(2); _otherLocations[displayType] = location; return this; } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModel.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModel.cs index c3843d1bd3b..77f1f10a371 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModel.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Views/ShapeViewModel.cs @@ -25,7 +25,7 @@ public ShapeViewModel(string shapeType) } private ShapeMetadata _metadata; - public ShapeMetadata Metadata => _metadata = _metadata ?? new ShapeMetadata(); + public ShapeMetadata Metadata => _metadata ??= new ShapeMetadata(); public string Position { @@ -78,11 +78,7 @@ public ValueTask AddAsync(object item, string position) return new ValueTask(this); } - if (position == null) - { - position = ""; - } - + position ??= ""; _sorted = false; if (item is IHtmlContent) diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneHoldingBehavior.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneHoldingBehavior.cs index 8d572171a27..99fc4df86de 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneHoldingBehavior.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneHoldingBehavior.cs @@ -108,10 +108,10 @@ protected override bool TrySetMemberImpl(string name, object value) } /// - /// InterfaceProxyBehavior() - /// NilBehavior() => return Nil on GetMember and GetIndex in all cases - /// ZoneOnDemandBehavior(_zoneFactory, _parent, name) => when a zone (Shape) is - /// created, replace itself with the zone so that Layout.ZoneName is no more equal to Nil + /// InterfaceProxyBehavior(). + /// NilBehavior() => return Nil on GetMember and GetIndex in all cases. + /// ZoneOnDemandBehavior(_zoneFactory, _parent, name) => when a zone (Shape) is + /// created, replace itself with the zone so that Layout.ZoneName is no more equal to Nil. /// public class ZoneOnDemand : Shape { @@ -129,14 +129,14 @@ public ZoneOnDemand(Func> zoneFactory, ZoneHolding parent, str public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result) { - // NilBehavior + // NilBehavior. result = Nil.Instance; return true; } public override bool TryGetIndex(System.Dynamic.GetIndexBinder binder, object[] indexes, out object result) { - // NilBehavior + // NilBehavior. result = Nil.Instance; return true; } @@ -145,7 +145,7 @@ public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, o { var name = binder.Name; - // NilBehavior + // NilBehavior. if (!args.Any() && name != "ToString") { result = Nil.Instance; @@ -178,15 +178,15 @@ public override bool TryConvert(System.Dynamic.ConvertBinder binder, out object return true; } - public static bool operator ==(ZoneOnDemand a, object b) + public static bool operator ==(ZoneOnDemand _, object b) { - // if ZoneOnDemand is compared to null it must return true + // If ZoneOnDemand is compared to null it must return true. return b == null || ReferenceEquals(b, Nil.Instance); } public static bool operator !=(ZoneOnDemand a, object b) { - // if ZoneOnDemand is compared to null it must return true + // If ZoneOnDemand is compared to null it must return true. return !(a == b); } diff --git a/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapes.cs b/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapes.cs index 4bbdc77184c..478b86effab 100644 --- a/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapes.cs +++ b/src/OrchardCore/OrchardCore.DisplayManagement/Zones/ZoneShapes.cs @@ -18,7 +18,9 @@ public class ZoneShapes : IShapeAttributeProvider private const string ContentKey = "Content"; [Shape] +#pragma warning disable CA1822 // Mark members as static public async Task Zone(IDisplayHelper DisplayAsync, IEnumerable Shape) +#pragma warning restore CA1822 // Mark members as static { var htmlContentBuilder = new HtmlContentBuilder(); foreach (var item in Shape) @@ -30,7 +32,9 @@ public async Task Zone(IDisplayHelper DisplayAsync, IEnumerable ContentZone(IDisplayHelper DisplayAsync, dynamic Shape, IShapeFactory ShapeFactory) +#pragma warning restore CA1822 // Mark members as static { var htmlContentBuilder = new HtmlContentBuilder(); @@ -70,7 +74,7 @@ public async Task ContentZone(IDisplayHelper DisplayAsync, dynamic var modifierIndex = key.IndexOf(';'); if (modifierIndex != -1) { - key = key.Substring(0, modifierIndex); + key = key[..modifierIndex]; } return key; @@ -99,7 +103,7 @@ public async Task ContentZone(IDisplayHelper DisplayAsync, dynamic var key = shape.Metadata.Tab; var modifierIndex = key.IndexOf(';'); - return new PositionalGrouping(key.Substring(modifierIndex)); + return new PositionalGrouping(key[modifierIndex..]); } return new PositionalGrouping(null); @@ -147,7 +151,9 @@ public async Task ContentZone(IDisplayHelper DisplayAsync, dynamic } [Shape] +#pragma warning disable CA1822 // Mark members as static public async Task CardGrouping(IDisplayHelper DisplayAsync, GroupingViewModel Shape, IShapeFactory ShapeFactory) +#pragma warning restore CA1822 // Mark members as static { var htmlContentBuilder = new HtmlContentBuilder(); @@ -165,7 +171,7 @@ public async Task CardGrouping(IDisplayHelper DisplayAsync, Groupi var modifierIndex = key.IndexOf(';'); if (modifierIndex != -1) { - key = key.Substring(0, modifierIndex); + key = key[..modifierIndex]; } return key; @@ -193,7 +199,7 @@ public async Task CardGrouping(IDisplayHelper DisplayAsync, Groupi { var key = shape.Metadata.Card; var modifierIndex = key.IndexOf(';'); - return new PositionalGrouping(key.Substring(modifierIndex)); + return new PositionalGrouping(key[modifierIndex..]); } return new PositionalGrouping(); @@ -240,7 +246,9 @@ public async Task CardGrouping(IDisplayHelper DisplayAsync, Groupi } [Shape] +#pragma warning disable CA1822 // Mark members as static public async Task ColumnGrouping(IDisplayHelper DisplayAsync, GroupingViewModel Shape, IShapeFactory ShapeFactory) +#pragma warning restore CA1822 // Mark members as static { var htmlContentBuilder = new HtmlContentBuilder(); @@ -258,14 +266,14 @@ public async Task ColumnGrouping(IDisplayHelper DisplayAsync, Grou var modifierIndex = key.IndexOf('_'); if (modifierIndex != -1) { - key = key.Substring(0, modifierIndex); + key = key[..modifierIndex]; } // Remove positional modifier. modifierIndex = key.IndexOf(';'); if (modifierIndex != -1) { - key = key.Substring(0, modifierIndex); + key = key[..modifierIndex]; } return key; @@ -361,18 +369,18 @@ public async Task ColumnGrouping(IDisplayHelper DisplayAsync, Grou // Column-9;56 if (positionModifierIndex > columnModifierIndex) { - positionModifiers.Add(key.Substring(0, columnModifierIndex), key.Substring(positionModifierIndex + 1)); + positionModifiers.Add(key[..columnModifierIndex], key[(positionModifierIndex + 1)..]); } else // Column;56-9 { var length = columnModifierIndex - positionModifierIndex; - positionModifiers.Add(key.Substring(0, positionModifierIndex), key.Substring(positionModifierIndex + 1, length - 1)); + positionModifiers.Add(key[..positionModifierIndex], key.Substring(positionModifierIndex + 1, length - 1)); } } else { var positionModifierIndex = key.IndexOf(';'); - positionModifiers.Add(key.Substring(0, positionModifierIndex), key.Substring(positionModifierIndex + 1)); + positionModifiers.Add(key[..positionModifierIndex], key[(positionModifierIndex + 1)..]); } } } @@ -396,18 +404,18 @@ public async Task ColumnGrouping(IDisplayHelper DisplayAsync, Grou // Column;5.1_9 if (colModifierIndex > posModifierIndex) { - columnModifiers.Add(key.Substring(0, posModifierIndex), key.Substring(colModifierIndex + 1)); + columnModifiers.Add(key[..posModifierIndex], key[(colModifierIndex + 1)..]); } else // Column_9;5.1 { var length = posModifierIndex - colModifierIndex; - columnModifiers.Add(key.Substring(0, colModifierIndex), key.Substring(colModifierIndex + 1, length - 1)); + columnModifiers.Add(key[..colModifierIndex], key.Substring(colModifierIndex + 1, length - 1)); } } else { var columnModifierIndex = key.IndexOf('_'); - columnModifiers.Add(key.Substring(0, columnModifierIndex), key.Substring(columnModifierIndex + 1)); + columnModifiers.Add(key[..columnModifierIndex], key[(columnModifierIndex + 1)..]); } } } @@ -444,7 +452,7 @@ public PositionalGrouping(string key) var modifierIndex = key.IndexOf(';'); if (modifierIndex != -1) { - Position = key.Substring(modifierIndex + 1); + Position = key[(modifierIndex + 1)..]; } } } diff --git a/src/OrchardCore/OrchardCore.Email.Abstractions/SmtpResult.cs b/src/OrchardCore/OrchardCore.Email.Abstractions/SmtpResult.cs index 6d0c3733f06..729449d8cf8 100644 --- a/src/OrchardCore/OrchardCore.Email.Abstractions/SmtpResult.cs +++ b/src/OrchardCore/OrchardCore.Email.Abstractions/SmtpResult.cs @@ -32,6 +32,6 @@ public class SmtpResult /// Creates an indicating a failed Smtp operation, with a list of errors if applicable. /// /// An optional array of which caused the operation to fail. - public static SmtpResult Failed(params LocalizedString[] errors) => new SmtpResult { Succeeded = false, Errors = errors }; + public static SmtpResult Failed(params LocalizedString[] errors) => new() { Succeeded = false, Errors = errors }; } } diff --git a/src/OrchardCore/OrchardCore.Email.Core/Services/SmtpService.cs b/src/OrchardCore/OrchardCore.Email.Core/Services/SmtpService.cs index 2105205aef5..14252c5008a 100644 --- a/src/OrchardCore/OrchardCore.Email.Core/Services/SmtpService.cs +++ b/src/OrchardCore/OrchardCore.Email.Core/Services/SmtpService.cs @@ -22,11 +22,11 @@ public class SmtpService : ISmtpService { private const string EmailExtension = ".eml"; - private static readonly char[] EmailsSeparator = new char[] { ',', ';' }; + private static readonly char[] _emailsSeparator = new char[] { ',', ';' }; private readonly SmtpSettings _options; private readonly ILogger _logger; - private readonly IStringLocalizer S; + protected readonly IStringLocalizer S; /// /// Initializes a new instance of a . @@ -37,8 +37,7 @@ public class SmtpService : ISmtpService public SmtpService( IOptions options, ILogger logger, - IStringLocalizer stringLocalizer - ) + IStringLocalizer stringLocalizer) { _options = options.Value; _logger = logger; @@ -92,7 +91,7 @@ public async Task SendAsync(MailMessage message) response = await SendOnlineMessageAsync(mimeMessage); break; case SmtpDeliveryMethod.SpecifiedPickupDirectory: - await SendOfflineMessage(mimeMessage, _options.PickupDirectoryLocation); + await SendOfflineMessageAsync(mimeMessage, _options.PickupDirectoryLocation); break; default: throw new NotSupportedException($"The '{_options.DeliveryMethod}' delivery method is not supported."); @@ -133,7 +132,7 @@ private MimeMessage FromMailMessage(MailMessage message, IList if (!String.IsNullOrWhiteSpace(message.From)) { - foreach (var address in message.From.Split(EmailsSeparator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + foreach (var address in message.From.Split(_emailsSeparator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { if (MailboxAddress.TryParse(address, out var mailBox)) { @@ -148,7 +147,7 @@ private MimeMessage FromMailMessage(MailMessage message, IList if (!String.IsNullOrWhiteSpace(message.To)) { - foreach (var address in message.To.Split(EmailsSeparator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + foreach (var address in message.To.Split(_emailsSeparator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { if (MailboxAddress.TryParse(address, out var mailBox)) { @@ -163,7 +162,7 @@ private MimeMessage FromMailMessage(MailMessage message, IList if (!String.IsNullOrWhiteSpace(message.Cc)) { - foreach (var address in message.Cc.Split(EmailsSeparator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + foreach (var address in message.Cc.Split(_emailsSeparator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { if (MailboxAddress.TryParse(address, out var mailBox)) { @@ -178,7 +177,7 @@ private MimeMessage FromMailMessage(MailMessage message, IList if (!String.IsNullOrWhiteSpace(message.Bcc)) { - foreach (var address in message.Bcc.Split(EmailsSeparator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + foreach (var address in message.Bcc.Split(_emailsSeparator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { if (MailboxAddress.TryParse(address, out var mailBox)) { @@ -200,7 +199,7 @@ private MimeMessage FromMailMessage(MailMessage message, IList } else { - foreach (var address in message.ReplyTo.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries)) + foreach (var address in message.ReplyTo.Split(_emailsSeparator, StringSplitOptions.RemoveEmptyEntries)) { if (MailboxAddress.TryParse(address, out var mailBox)) { @@ -242,14 +241,21 @@ private MimeMessage FromMailMessage(MailMessage message, IList 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"; + if (sslPolicyErrors == SslPolicyErrors.None) + { return true; + } - _logger.LogError(string.Concat("SMTP Server's certificate {CertificateSubject} issued by {CertificateIssuer} ", - "with thumbprint {CertificateThumbprint} and expiration date {CertificateExpirationDate} ", - "is considered invalid with {SslPolicyErrors} policy errors"), - 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) { @@ -262,10 +268,7 @@ private bool CertificateValidationCallback(object sender, X509Certificate certif return false; } - protected virtual async Task OnMessageSendingAsync(SmtpClient client, MimeMessage message) - { - await Task.CompletedTask; - } + protected virtual Task OnMessageSendingAsync(SmtpClient client, MimeMessage message) => Task.CompletedTask; private async Task SendOnlineMessageAsync(MimeMessage message) { @@ -315,10 +318,10 @@ private async Task SendOnlineMessageAsync(MimeMessage message) return response; } - private static async Task SendOfflineMessage(MimeMessage message, string pickupDirectory) + private static Task SendOfflineMessageAsync(MimeMessage message, string pickupDirectory) { var mailPath = Path.Combine(pickupDirectory, Guid.NewGuid().ToString() + EmailExtension); - await message.WriteToAsync(mailPath, CancellationToken.None); + return message.WriteToAsync(mailPath, CancellationToken.None); } } } diff --git a/src/OrchardCore/OrchardCore.FileStorage.Abstractions/IFileStore.cs b/src/OrchardCore/OrchardCore.FileStorage.Abstractions/IFileStore.cs index bb98cc6a1ec..29d04aa72f6 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.Abstractions/IFileStore.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.Abstractions/IFileStore.cs @@ -150,10 +150,12 @@ public static string Combine(this IFileStore fileStore, params string[] paths) /// Backslash is converted to forward slash and any leading or trailing slashes /// are removed. /// - public static string NormalizePath(this IFileStore fileStore, string path) + public static string NormalizePath(this IFileStore _, string path) { if (path == null) + { return null; + } return path.Replace('\\', '/').Trim('/', ' '); } diff --git a/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs b/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs index d5854d16470..4bcc4edb893 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.AmazonS3/AwsFileStorage.cs @@ -103,7 +103,7 @@ public async Task GetDirectoryInfoAsync(string path) var folderPath = awsFolderPath; if (!IsNullOrEmpty(_basePrefix)) { - folderPath = folderPath.Substring(_basePrefix.Length - 1); + folderPath = folderPath[(_basePrefix.Length - 1)..]; } folderPath = folderPath.TrimEnd('/'); @@ -287,7 +287,7 @@ public async Task CreateFileFromStreamAsync(string path, Stream inputStr return path; } - private string NormalizePrefix(string prefix) + private static string NormalizePrefix(string prefix) { prefix = prefix.Trim('/') + '/'; if (prefix.Length == 1) diff --git a/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobDirectory.cs b/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobDirectory.cs index 853e24b9880..73fa4ef697d 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobDirectory.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobDirectory.cs @@ -13,9 +13,10 @@ public BlobDirectory(string path, DateTime lastModifiedUtc) { _path = path; _lastModifiedUtc = lastModifiedUtc; - // Use GetFileName rather than GetDirectoryName as GetDirectoryName requires a delimiter + + // Use GetFileName rather than GetDirectoryName as GetDirectoryName requires a delimiter. _name = System.IO.Path.GetFileName(path); - _directoryPath = _path.Length > _name.Length ? _path.Substring(0, _path.Length - _name.Length - 1) : ""; + _directoryPath = _path.Length > _name.Length ? _path[..^(_name.Length + 1)] : ""; } public string Path => _path; diff --git a/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFile.cs b/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFile.cs index 7ff950d96dc..346b971b346 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFile.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFile.cs @@ -15,13 +15,14 @@ public BlobFile(string path, long? length, DateTimeOffset? lastModified) _path = path; _name = System.IO.Path.GetFileName(_path); - if (_name == _path) // file is in root Directory + // File is in root Directory. + if (_name == _path) { _directoryPath = ""; } else { - _directoryPath = _path.Substring(0, _path.Length - _name.Length - 1); + _directoryPath = _path[..^(_name.Length + 1)]; } _length = length; diff --git a/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFileStore.cs b/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFileStore.cs index cb33259c287..e2e4e60ea05 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFileStore.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.AzureBlob/BlobFileStore.cs @@ -137,7 +137,7 @@ await foreach (var blob in page) var folderPath = blob.Prefix; if (!String.IsNullOrEmpty(_basePrefix)) { - folderPath = folderPath.Substring(_basePrefix.Length - 1); + folderPath = folderPath[(_basePrefix.Length - 1)..]; } folderPath = folderPath.Trim('/'); @@ -146,6 +146,7 @@ await foreach (var blob in page) else { var itemName = Path.GetFileName(WebUtility.UrlDecode(blob.Blob.Name)).Trim('/'); + // Ignore directory marker files. if (itemName != _directoryMarkerFileName) { @@ -173,13 +174,18 @@ await foreach (var blob in page) // We can infer a hierarchy by examining the paths returned for the file contents // and evaluate whether a directory exists and should be added to the results listing. var directory = Path.GetDirectoryName(name); + // Strip base folder from directory name. if (!String.IsNullOrEmpty(_basePrefix)) { - directory = directory.Substring(_basePrefix.Length - 1); + directory = directory[(_basePrefix.Length - 1)..]; } + // Do not include root folder, or current path, or multiple folders in folder listing. - if (!String.IsNullOrEmpty(directory) && !directories.Contains(directory) && (String.IsNullOrEmpty(path) ? true : !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); @@ -190,7 +196,7 @@ await foreach (var blob in page) { if (!String.IsNullOrEmpty(_basePrefix)) { - name = name.Substring(_basePrefix.Length - 1); + name = name[(_basePrefix.Length - 1)..]; } yield return new BlobFile(name.Trim('/'), blob.Properties.ContentLength, blob.Properties.LastModified); } @@ -254,7 +260,7 @@ public async Task TryDeleteDirectoryAsync(string path) var blobsWereDeleted = false; var prefix = this.Combine(_basePrefix, path); - prefix = this.NormalizePrefix(prefix); + prefix = NormalizePrefix(prefix); var page = _blobContainer.GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, prefix); await foreach (var blob in page) @@ -319,6 +325,7 @@ public async Task CopyFileAsync(string srcPath, string dstPath) while (properties.Value.CopyStatus == CopyStatus.Pending) { await Task.Delay(250); + // Need to fetch properties or CopyStatus will never update. properties = await newBlob.GetPropertiesAsync(); } @@ -432,16 +439,14 @@ private async Task CreateDirectoryAsync(string path) var placeholderBlob = GetBlobReference(this.Combine(path, _directoryMarkerFileName)); // Create a directory marker file to make this directory appear when listing directories. - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("This is a directory marker file created by Orchard Core. It is safe to delete it."))) - { - await placeholderBlob.UploadAsync(stream); - } + using var stream = new MemoryStream(Encoding.UTF8.GetBytes("This is a directory marker file created by Orchard Core. It is safe to delete it.")); + await placeholderBlob.UploadAsync(stream); } /// /// Blob prefix requires a trailing slash except when loading the root of the container. /// - private string NormalizePrefix(string prefix) + private static string NormalizePrefix(string prefix) { prefix = prefix.Trim('/') + '/'; if (prefix.Length == 1) diff --git a/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStore.cs b/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStore.cs index 39eca68698c..d4427ed341e 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStore.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStore.cs @@ -77,7 +77,7 @@ public IAsyncEnumerable GetDirectoryContentAsync(string path = .Select(f => { var fileSystemInfo = new PhysicalDirectoryInfo(new DirectoryInfo(f)); - var fileRelativePath = f.Substring(_fileSystemPath.Length); + var fileRelativePath = f[_fileSystemPath.Length..]; var filePath = this.NormalizePath(fileRelativePath); return new FileSystemStoreEntry(filePath, fileSystemInfo); })); @@ -89,7 +89,7 @@ public IAsyncEnumerable GetDirectoryContentAsync(string path = .Select(f => { var fileSystemInfo = new PhysicalFileInfo(new FileInfo(f)); - var fileRelativePath = f.Substring(_fileSystemPath.Length); + var fileRelativePath = f[_fileSystemPath.Length..]; var filePath = this.NormalizePath(fileRelativePath); return new FileSystemStoreEntry(filePath, fileSystemInfo); })); diff --git a/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStoreEntry.cs b/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStoreEntry.cs index c77713645d2..f908e01a54f 100644 --- a/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStoreEntry.cs +++ b/src/OrchardCore/OrchardCore.FileStorage.FileSystem/FileSystemStoreEntry.cs @@ -16,7 +16,7 @@ internal FileSystemStoreEntry(string path, IFileInfo fileInfo) public string Path => _path; public string Name => _fileInfo.Name; - public string DirectoryPath => _path.Substring(0, _path.Length - Name.Length).TrimEnd('/'); + public string DirectoryPath => _path[..^Name.Length].TrimEnd('/'); public DateTime LastModifiedUtc => _fileInfo.LastModified.UtcDateTime; public long Length => _fileInfo.Length; public bool IsDirectory => _fileInfo.IsDirectory; diff --git a/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentFieldIndexHandler.cs b/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentFieldIndexHandler.cs index 37b7d638d06..f38576ecc26 100644 --- a/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentFieldIndexHandler.cs +++ b/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentFieldIndexHandler.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Threading.Tasks; using OrchardCore.ContentManagement; @@ -13,8 +14,8 @@ public abstract class ContentFieldIndexHandler : IContentFieldIndexHandl { 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; } diff --git a/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentPartIndexHandler.cs b/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentPartIndexHandler.cs index 6a80599d409..975f5426414 100644 --- a/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentPartIndexHandler.cs +++ b/src/OrchardCore/OrchardCore.Indexing.Abstractions/ContentPartIndexHandler.cs @@ -20,8 +20,11 @@ Task IContentPartIndexHandler.BuildIndexAsync(ContentPart contentPart, ContentTy return Task.CompletedTask; } - var keys = new List(); - keys.Add(typePartDefinition.Name); + var keys = new List + { + typePartDefinition.Name, + }; + foreach (var key in context.Keys) { keys.Add($"{key}.{typePartDefinition.Name}"); diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Cache/CacheContext.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Cache/CacheContext.cs index 814f09c9686..c39cc04fbb0 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Cache/CacheContext.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Cache/CacheContext.cs @@ -50,10 +50,7 @@ public CacheContext WithExpirySliding(TimeSpan window) /// public CacheContext AddContext(params string[] contexts) { - if (_contexts == null) - { - _contexts = new HashSet(); - } + _contexts ??= new HashSet(); foreach (var context in contexts) { @@ -68,20 +65,14 @@ public CacheContext AddContext(params string[] contexts) /// public CacheContext RemoveContext(string context) { - if (_contexts != null) - { - _contexts.Remove(context); - } + _contexts?.Remove(context); return this; } public CacheContext AddTag(params string[] tags) { - if (_tags == null) - { - _tags = new HashSet(); - } + _tags ??= new HashSet(); foreach (var tag in tags) { @@ -93,10 +84,7 @@ public CacheContext AddTag(params string[] tags) public CacheContext RemoveTag(string tag) { - if (_tags != null) - { - _tags.Remove(tag); - } + _tags?.Remove(tag); return this; } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/DefaultCommandHandler.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/DefaultCommandHandler.cs index b4bb6fdcabe..96bf4e1b302 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/DefaultCommandHandler.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/DefaultCommandHandler.cs @@ -38,30 +38,30 @@ private void SetSwitchValues(CommandContext context) private void SetSwitchValue(KeyValuePair commandSwitch) { - // Find the property - PropertyInfo propertyInfo = GetType().GetProperty(commandSwitch.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase); - if (propertyInfo == null) - { - throw new InvalidOperationException(S["Switch \"{0}\" was not found", commandSwitch.Key]); - } + // Find the property. + 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).Any()) { throw new InvalidOperationException(S["A property \"{0}\" exists but is not decorated with \"{1}\"", commandSwitch.Key, typeof(OrchardSwitchAttribute).Name]); } - // Set the value + // Set the value. try { - object value = ConvertToType(propertyInfo.PropertyType, commandSwitch.Value); + var value = ConvertToType(propertyInfo.PropertyType, commandSwitch.Value); propertyInfo.SetValue(this, value, null /*index*/); } catch (Exception ex) when (!ex.IsFatal()) { - //TODO: (ngm) fix this message - string message = S["Error converting value \"{0}\" to \"{1}\" for switch \"{2}\"", + // TODO: (ngm) fix this message. + 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,13 +71,10 @@ private async Task InvokeAsync(CommandContext context) CheckMethodForSwitches(context.CommandDescriptor.MethodInfo, context.Switches); var arguments = (context.Arguments ?? Enumerable.Empty()).ToArray(); - object[] invokeParameters = GetInvokeParametersForMethod(context.CommandDescriptor.MethodInfo, arguments); - if (invokeParameters == null) - { - throw new InvalidOperationException(S["Command arguments \"{0}\" don't match command definition", string.Join(" ", arguments)]); - } + var invokeParameters = GetInvokeParametersForMethod(context.CommandDescriptor.MethodInfo, arguments) + ?? throw new InvalidOperationException(S["Command arguments \"{0}\" don't match command definition", String.Join(" ", arguments)]); - this.Context = context; + Context = context; if (context.CommandDescriptor.MethodInfo.ReturnType == typeof(Task)) { @@ -103,7 +100,7 @@ private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, ILis var invokeParameters = new List(); var args = new List(arguments); var methodParameters = methodInfo.GetParameters(); - bool methodHasParams = false; + var methodHasParams = false; if (methodParameters.Length == 0) { @@ -111,10 +108,11 @@ private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, ILis { return invokeParameters.ToArray(); } + return null; } - if (methodParameters[methodParameters.Length - 1].ParameterType.IsAssignableFrom(typeof(string[]))) + if (methodParameters[^1].ParameterType.IsAssignableFrom(typeof(string[]))) { methodHasParams = true; } @@ -124,7 +122,7 @@ private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, ILis if (!methodHasParams && args.Count < requiredMethodParameters.Length) return null; if (methodHasParams && (methodParameters.Length - args.Count >= 2)) return null; - for (int i = 0; i < methodParameters.Length; i++) + for (var i = 0; i < methodParameters.Length; i++) { if (methodParameters[i].ParameterType.IsAssignableFrom(typeof(string[]))) { @@ -152,7 +150,7 @@ private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, ILis if (methodHasParams && (methodParameters.Length - args.Count == 1) && !lastParameterIsParams) { - invokeParameters.Add(new string[] { }); + invokeParameters.Add(Array.Empty()); } return invokeParameters.ToArray(); @@ -164,7 +162,7 @@ private void CheckMethodForSwitches(MethodInfo methodInfo, IDictionary(StringComparer.OrdinalIgnoreCase); - foreach (OrchardSwitchesAttribute switchesAttribute in methodInfo.GetCustomAttributes(typeof(OrchardSwitchesAttribute), false)) + foreach (var switchesAttribute in methodInfo.GetCustomAttributes(typeof(OrchardSwitchesAttribute), false).Cast()) { supportedSwitches.UnionWith(switchesAttribute.Switches); } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/Parameters/ICommandParser.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/Parameters/ICommandParser.cs index 46f91cf79a6..ba2262654e7 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/Parameters/ICommandParser.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Commands/Parameters/ICommandParser.cs @@ -70,7 +70,7 @@ public void MoveNext() /// copy the next character. Otherwise, copy the backslash and the next character. /// The semantics of whitespace is: end the current argument and move on to the next one. /// - private IEnumerable SplitArgs(string commandLine) + private static IEnumerable SplitArgs(string commandLine) { var state = new State(commandLine); while (!state.EOF) @@ -103,7 +103,7 @@ private IEnumerable SplitArgs(string commandLine) return state.Arguments; } - private void ProcessQuote(State state) + private static void ProcessQuote(State state) { state.MoveNext(); while (!state.EOF) @@ -120,7 +120,7 @@ private void ProcessQuote(State state) state.AddArgument(); } - private void ProcessBackslash(State state) + private static void ProcessBackslash(State state) { state.MoveNext(); if (state.EOF) diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Files/PathExtensions.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Files/PathExtensions.cs index 1d3b41b285d..a609bd0f078 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Files/PathExtensions.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Files/PathExtensions.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Text; using Microsoft.Extensions.Primitives; +using System; namespace System.IO { @@ -37,7 +38,7 @@ public static string Combine(string path, string other = null) } else { - result = path.Substring(0, index + 1) + other; + result = String.Concat(path.AsSpan(0, index + 1), other); } return result; diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/SecurityHeaderNames.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/SecurityHeaderNames.cs index 9cb1aef4098..59c267708b8 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/SecurityHeaderNames.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/SecurityHeaderNames.cs @@ -2,12 +2,12 @@ namespace OrchardCore.Security { public static class SecurityHeaderNames { - public static readonly string ContentSecurityPolicy = "Content-Security-Policy"; + public const string ContentSecurityPolicy = "Content-Security-Policy"; - public static readonly string PermissionsPolicy = "Permissions-Policy"; + public const string PermissionsPolicy = "Permissions-Policy"; - public static readonly string ReferrerPolicy = "Referrer-Policy"; + public const string ReferrerPolicy = "Referrer-Policy"; - public static readonly string XContentTypeOptions = "X-Content-Type-Options"; + public const string XContentTypeOptions = "X-Content-Type-Options"; } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/StandardPermissions.cs b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/StandardPermissions.cs index 0dd12d92671..f8043358697 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/StandardPermissions.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure.Abstractions/Security/StandardPermissions.cs @@ -4,6 +4,6 @@ namespace OrchardCore.Security { public class StandardPermissions { - public static readonly Permission SiteOwner = new Permission("SiteOwner", "Site Owners Permission", isSecurityCritical: true); + public static readonly Permission SiteOwner = new("SiteOwner", "Site Owners Permission", isSecurityCritical: true); } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/FeaturesCacheContextProvider.cs b/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/FeaturesCacheContextProvider.cs index 0a90e768418..1ee116788dc 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/FeaturesCacheContextProvider.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/FeaturesCacheContextProvider.cs @@ -20,9 +20,9 @@ public FeaturesCacheContextProvider(IFeatureHash featureHash) public async Task PopulateContextEntriesAsync(IEnumerable contexts, List entries) { - if (contexts.Any(ctx => string.Equals(ctx, "features", StringComparison.OrdinalIgnoreCase))) + if (contexts.Any(ctx => String.Equals(ctx, "features", StringComparison.OrdinalIgnoreCase))) { - // Add a hash of the enabled features + // Add a hash of the enabled features. var hash = await _featureHash.GetFeatureHashAsync(); entries.Add(new CacheContextEntry("features", hash.ToString(CultureInfo.InvariantCulture))); } @@ -30,7 +30,7 @@ public async Task PopulateContextEntriesAsync(IEnumerable contexts, List { foreach (var context in contexts.Where(ctx => ctx.StartsWith(FeaturesPrefix, StringComparison.OrdinalIgnoreCase))) { - var featureName = context.Substring(FeaturesPrefix.Length); + var featureName = context[FeaturesPrefix.Length..]; var hash = await _featureHash.GetFeatureHashAsync(featureName); entries.Add(new CacheContextEntry("features", hash.ToString(CultureInfo.InvariantCulture))); diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/QueryCacheContextProvider.cs b/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/QueryCacheContextProvider.cs index 273d28da018..05cc96c0b23 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/QueryCacheContextProvider.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheContextProviders/QueryCacheContextProvider.cs @@ -29,13 +29,13 @@ public Task PopulateContextEntriesAsync(IEnumerable contexts, List ctx.StartsWith(QueryPrefix, StringComparison.OrdinalIgnoreCase))) { - var key = context.Substring(QueryPrefix.Length); + var key = context[QueryPrefix.Length..]; var httpContext = _httpContextAccessor.HttpContext; var query = httpContext.Request.Query; diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheScopeManager.cs b/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheScopeManager.cs index 503fb7ed438..202c97ee520 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheScopeManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Cache/CacheScopeManager.cs @@ -4,7 +4,7 @@ namespace OrchardCore.Environment.Cache { - // todo: does this belong in dynamic cache? + // Todo: does this belong in dynamic cache? public class CacheScopeManager : ICacheScopeManager { private readonly Stack _scopes; @@ -93,7 +93,7 @@ public void WithExpirySliding(TimeSpan expirySliding) } } - private void MergeCacheContexts(CacheContext into, CacheContext from) + private static void MergeCacheContexts(CacheContext into, CacheContext from) { into.AddContext(from.Contexts.ToArray()); into.AddTag(from.Tags.ToArray()); @@ -117,7 +117,7 @@ private void MergeCacheContexts(CacheContext into, CacheContext from) } } - private DateTimeOffset? GetMostRestrictiveDateTimeOffset(DateTimeOffset? a, DateTimeOffset? b) + private static DateTimeOffset? GetMostRestrictiveDateTimeOffset(DateTimeOffset? a, DateTimeOffset? b) { if (a.HasValue && b.HasValue) { @@ -127,7 +127,7 @@ private void MergeCacheContexts(CacheContext into, CacheContext from) return a ?? b; } - private TimeSpan? GetMostRestrictiveTimespan(TimeSpan? a, TimeSpan? b) + private static TimeSpan? GetMostRestrictiveTimespan(TimeSpan? a, TimeSpan? b) { if (a.HasValue && b.HasValue) { diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Commands/Builtin/HelpCommand.cs b/src/OrchardCore/OrchardCore.Infrastructure/Commands/Builtin/HelpCommand.cs index 6556ab600ce..8f104759679 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Commands/Builtin/HelpCommand.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Commands/Builtin/HelpCommand.cs @@ -10,7 +10,7 @@ namespace OrchardCore.Environment.Commands.Builtin public class HelpCommand : DefaultCommandHandler { private readonly IServiceProvider _serviceProvider; - private readonly CommandHandlerDescriptorBuilder _builder = new CommandHandlerDescriptorBuilder(); + private readonly CommandHandlerDescriptorBuilder _builder = new(); public HelpCommand(IServiceProvider serviceProvider, IStringLocalizer localizer) : base(localizer) @@ -39,7 +39,7 @@ public async Task AllCommandsAsync() [CommandHelp("help ", "\tDisplay help text for ")] public async Task SingleCommandAsync(string[] commandNameStrings) { - string command = string.Join(" ", commandNameStrings); + var command = String.Join(" ", commandNameStrings); var descriptors = GetCommandDescriptors() .Where(t => t.Names.Any(x => x.StartsWith(command, StringComparison.OrdinalIgnoreCase))) .OrderBy(d => d.Names); @@ -65,7 +65,7 @@ private IEnumerable GetCommandDescriptors() private LocalizedString GetHelpText(CommandDescriptor descriptor) { - if (string.IsNullOrEmpty(descriptor.HelpText)) + if (String.IsNullOrEmpty(descriptor.HelpText)) { return S["{0}.{1}: no help text", descriptor.MethodInfo.DeclaringType?.FullName, descriptor.MethodInfo.Name]; } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Commands/CommandHandlerDescriptorBuilder.cs b/src/OrchardCore/OrchardCore.Infrastructure/Commands/CommandHandlerDescriptorBuilder.cs index 1df7aa1d7cc..ac81ac4fb49 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Commands/CommandHandlerDescriptorBuilder.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Commands/CommandHandlerDescriptorBuilder.cs @@ -7,12 +7,14 @@ namespace OrchardCore.Environment.Commands { public class CommandHandlerDescriptorBuilder { +#pragma warning disable CA1822 // Mark members as static public CommandHandlerDescriptor Build(Type type) +#pragma warning restore CA1822 // Mark members as static { return new CommandHandlerDescriptor { Commands = CollectMethods(type) }; } - private IEnumerable CollectMethods(Type type) + private static IEnumerable CollectMethods(Type type) { var methods = type .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) @@ -24,7 +26,7 @@ private IEnumerable CollectMethods(Type type) } } - private CommandDescriptor BuildMethod(MethodInfo methodInfo) + private static CommandDescriptor BuildMethod(MethodInfo methodInfo) { return new CommandDescriptor { @@ -34,17 +36,17 @@ private CommandDescriptor BuildMethod(MethodInfo methodInfo) }; } - private string GetCommandHelpText(MethodInfo methodInfo) + private static string GetCommandHelpText(MethodInfo methodInfo) { var attributes = methodInfo.GetCustomAttributes(typeof(CommandHelpAttribute), false/*inherit*/); if (attributes != null && attributes.Any()) { return attributes.Cast().Single().HelpText; } - return string.Empty; + return String.Empty; } - private string[] GetCommandNames(MethodInfo methodInfo) + private static string[] GetCommandNames(MethodInfo methodInfo) { var attributes = methodInfo.GetCustomAttributes(typeof(CommandNameAttribute), false/*inherit*/); if (attributes != null && attributes.Any()) diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs b/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs index d69828a7ec1..9a56769d5f0 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Commands/DefaultCommandManager.cs @@ -9,8 +9,8 @@ namespace OrchardCore.Environment.Commands public class DefaultCommandManager : ICommandManager { private readonly IEnumerable _commandHandlers; - private readonly CommandHandlerDescriptorBuilder _builder = new CommandHandlerDescriptorBuilder(); - private readonly IStringLocalizer S; + private readonly CommandHandlerDescriptorBuilder _builder = new(); + protected readonly IStringLocalizer S; public DefaultCommandManager(IEnumerable commandHandlers, IStringLocalizer localizer) @@ -31,8 +31,8 @@ public async Task ExecuteAsync(CommandParameters parameters) } else { - var commandMatch = string.Join(" ", parameters.Arguments.ToArray()); - var commandList = string.Join(",", GetCommandDescriptors().SelectMany(d => d.Names).ToArray()); + var commandMatch = String.Join(" ", parameters.Arguments.ToArray()); + var commandList = String.Join(",", GetCommandDescriptors().SelectMany(d => d.Names).ToArray()); if (matches.Any()) { throw new Exception(S["Multiple commands found matching arguments \"{0}\". Commands available: {1}.", @@ -63,11 +63,12 @@ private static IEnumerable MatchCommands(CommandParameters parameters, in foreach (var name in commandDescriptor.Names) { var names = name.Split(' '); - var namesCount = names.Count(); + var namesCount = names.Length; + // We check here number of arguments a command can recieve against // arguments provided for the command to identify the correct command // and avoid matching multiple commands. - if (name == string.Join(" ", parameters.Arguments.Take(namesCount)) && commandDescriptor.MethodInfo.GetParameters().Length == argCount - namesCount) + if (name == String.Join(" ", parameters.Arguments.Take(namesCount)) && commandDescriptor.MethodInfo.GetParameters().Length == argCount - namesCount) { names = parameters.Arguments.ToArray(); } @@ -78,14 +79,14 @@ private static IEnumerable MatchCommands(CommandParameters parameters, in { Context = new CommandContext { - Arguments = parameters.Arguments.Skip(name.Split(' ').Count()), - Command = string.Join(" ", names), + Arguments = parameters.Arguments.Skip(name.Split(' ').Length), + Command = String.Join(" ", names), CommandDescriptor = commandDescriptor, Input = parameters.Input, Output = parameters.Output, Switches = parameters.Switches, }, - CommandHandler = handler + CommandHandler = handler, }; } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Commands/Parameters/CommandParametersParser.cs b/src/OrchardCore/OrchardCore.Infrastructure/Commands/Parameters/CommandParametersParser.cs index 1d86afcc0df..d7a87200099 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Commands/Parameters/CommandParametersParser.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Commands/Parameters/CommandParametersParser.cs @@ -17,13 +17,13 @@ public CommandParameters Parse(IEnumerable args) // Switch? if (arg[0] == '/') { - int index = arg.IndexOf(':'); - var switchName = (index < 0 ? arg.Substring(1) : arg.Substring(1, index - 1)); - var switchValue = (index < 0 || index >= arg.Length ? string.Empty : arg.Substring(index + 1)); + var index = arg.IndexOf(':'); + var switchName = index < 0 ? arg[1..] : arg[1..index]; + var switchValue = index < 0 || index >= arg.Length ? String.Empty : arg[(index + 1)..]; - if (string.IsNullOrEmpty(switchName)) + if (String.IsNullOrEmpty(switchName)) { - throw new ArgumentException(string.Format("Invalid switch syntax: \"{0}\". Valid syntax is /[:].", arg)); + throw new ArgumentException(String.Format("Invalid switch syntax: \"{0}\". Valid syntax is /[:].", arg)); } switches.Add(switchName, switchValue); diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DefaultDocumentSerializer.cs b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DefaultDocumentSerializer.cs index cbf4e19a210..c402db3dc56 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Documents/DefaultDocumentSerializer.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Documents/DefaultDocumentSerializer.cs @@ -13,9 +13,9 @@ namespace OrchardCore.Documents /// public class DefaultDocumentSerializer : IDocumentSerialiser { - public static DefaultDocumentSerializer Instance = new DefaultDocumentSerializer(); + public static readonly DefaultDocumentSerializer Instance = new(); - private static readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings + private static readonly JsonSerializerSettings _jsonSettings = new() { TypeNameHandling = TypeNameHandling.Auto, DateTimeZoneHandling = DateTimeZoneHandling.Utc @@ -49,18 +49,18 @@ public Task DeserializeAsync(byte[] data) where TDocument return Task.FromResult(document); } - private static readonly byte[] GZipHeaderBytes = { 0x1f, 0x8b }; + private static readonly byte[] _gZipHeaderBytes = { 0x1f, 0x8b }; internal static bool IsCompressed(byte[] data) { - if (data.Length < GZipHeaderBytes.Length) + if (data.Length < _gZipHeaderBytes.Length) { return false; } - for (var i = 0; i < GZipHeaderBytes.Length; i++) + for (var i = 0; i < _gZipHeaderBytes.Length; i++) { - if (data[i] != GZipHeaderBytes[i]) + if (data[i] != _gZipHeaderBytes[i]) { return false; } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Documents/Options/DocumentOptionsSetup.cs b/src/OrchardCore/OrchardCore.Infrastructure/Documents/Options/DocumentOptionsSetup.cs index 41679082ea1..457840b8341 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Documents/Options/DocumentOptionsSetup.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Documents/Options/DocumentOptionsSetup.cs @@ -8,7 +8,7 @@ namespace OrchardCore.Documents.Options { public class DocumentOptionsSetup : IConfigureNamedOptions { - public static TimeSpan DefaultFailoverRetryLatency = TimeSpan.FromSeconds(30); + public static readonly TimeSpan DefaultFailoverRetryLatency = TimeSpan.FromSeconds(30); private readonly IShellConfiguration _shellConfiguration; diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Entities/DefaultIdGenerator.cs b/src/OrchardCore/OrchardCore.Infrastructure/Entities/DefaultIdGenerator.cs index d6775f8e96f..4cc77909d6f 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Entities/DefaultIdGenerator.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Entities/DefaultIdGenerator.cs @@ -5,7 +5,7 @@ namespace OrchardCore.Entities public class DefaultIdGenerator : IIdGenerator { // Some confusing chars are ignored: http://www.crockford.com/wrmg/base32.html - private static readonly string _encode32Chars = "0123456789abcdefghjkmnpqrstvwxyz"; + private const string _encode32Chars = "0123456789abcdefghjkmnpqrstvwxyz"; public string GenerateUniqueId() { diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Entities/Scripting/IdGeneratorMethod.cs b/src/OrchardCore/OrchardCore.Infrastructure/Entities/Scripting/IdGeneratorMethod.cs index d8b064fb547..1c0c694d994 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Entities/Scripting/IdGeneratorMethod.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Entities/Scripting/IdGeneratorMethod.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using OrchardCore.Scripting; @@ -7,19 +6,19 @@ namespace OrchardCore.Entities.Scripting { public class IdGeneratorMethod : IGlobalMethodProvider { - private static GlobalMethod Uuid = new GlobalMethod + private static readonly GlobalMethod _uuid = new() { Name = "uuid", - Method = serviceProvider => (Func)(() => + Method = serviceProvider => () => { var idGenerator = serviceProvider.GetRequiredService(); return idGenerator.GenerateUniqueId(); - }) + }, }; public IEnumerable GetMethods() { - yield return Uuid; + yield return _uuid; } } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Html/HtmlSanitizerRazorExtensions.cs b/src/OrchardCore/OrchardCore.Infrastructure/Html/HtmlSanitizerRazorExtensions.cs index 18b1fb90d35..93cacbb55ba 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Html/HtmlSanitizerRazorExtensions.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Html/HtmlSanitizerRazorExtensions.cs @@ -3,7 +3,9 @@ using OrchardCore; using OrchardCore.Infrastructure.Html; +#pragma warning disable CA1050 // Declare types in namespaces public static class HtmlSanitizerRazorExtensions +#pragma warning restore CA1050 // Declare types in namespaces { /// /// Sanitizes a string of html. diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Html/HtmlSanitizerService.cs b/src/OrchardCore/OrchardCore.Infrastructure/Html/HtmlSanitizerService.cs index 217ad92a11f..bb73aadbac2 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Html/HtmlSanitizerService.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Html/HtmlSanitizerService.cs @@ -5,7 +5,7 @@ namespace OrchardCore.Infrastructure.Html { public class HtmlSanitizerService : IHtmlSanitizerService { - private readonly HtmlSanitizer _sanitizer = new HtmlSanitizer(); + private readonly HtmlSanitizer _sanitizer = new(); public HtmlSanitizerService(IOptions options) { @@ -15,9 +15,6 @@ public HtmlSanitizerService(IOptions options) } } - public string Sanitize(string html) - { - return _sanitizer.Sanitize(html); - } + public string Sanitize(string html) => _sanitizer.Sanitize(html); } } diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Scripting/CommonGeneratorMethods.cs b/src/OrchardCore/OrchardCore.Infrastructure/Scripting/CommonGeneratorMethods.cs index 0ad1953491e..88e19fec7b3 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Scripting/CommonGeneratorMethods.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Scripting/CommonGeneratorMethods.cs @@ -9,52 +9,49 @@ namespace OrchardCore.Scripting { public class CommonGeneratorMethods : IGlobalMethodProvider { - private static GlobalMethod Base64 = new GlobalMethod + private static readonly GlobalMethod _base64 = new() { Name = "base64", Method = serviceProvider => (Func)(encoded => { return Encoding.UTF8.GetString(Convert.FromBase64String(encoded)); - }) + }), }; - private static GlobalMethod Html = new GlobalMethod + private static readonly GlobalMethod _html = new() { 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 GlobalMethod GZip = new GlobalMethod + private static readonly GlobalMethod _gZip = new() { 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; - while ((nRead = gzip.Read(buffer, 0, buffer.Length)) > 0) - { - decompressed.Write(buffer, 0, nRead); - } + using var gzip = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress); + + var decompressed = new MemoryStream(); + var buffer = new byte[1024]; + int nRead; - return Convert.ToBase64String(decompressed.ToArray()); + while ((nRead = gzip.Read(buffer, 0, buffer.Length)) > 0) + { + decompressed.Write(buffer, 0, nRead); } - }) + + return Convert.ToBase64String(decompressed.ToArray()); + }), }; - public IEnumerable GetMethods() - { - return new[] { Base64, Html, GZip }; - } + 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 25e90e37f68..52f72476ff3 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Scripting/DefaultScriptingManager.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Scripting/DefaultScriptingManager.cs @@ -25,14 +25,13 @@ public class DefaultScriptingManager : IScriptingManager IEnumerable scopedMethodProviders) { var directiveIndex = directive.IndexOf(':'); - if (directiveIndex == -1 || directiveIndex >= directive.Length - 2) { return directive; } - var prefix = directive.Substring(0, directiveIndex); - var script = directive.Substring(directiveIndex + 1); + var prefix = directive[..directiveIndex]; + var script = directive[(directiveIndex + 1)..]; var engine = GetScriptingEngine(prefix); if (engine == null) diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Scripting/Files/FilesScriptEngine.cs b/src/OrchardCore/OrchardCore.Infrastructure/Scripting/Files/FilesScriptEngine.cs index 7df7cb50958..67965fda014 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Scripting/Files/FilesScriptEngine.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Scripting/Files/FilesScriptEngine.cs @@ -31,38 +31,30 @@ public object Evaluate(IScriptingScope scope, string script) if (script.StartsWith("text('", StringComparison.Ordinal) && script.EndsWith("')", StringComparison.Ordinal)) { - var filePath = script.Substring(6, script.Length - 8); + var filePath = script[6..^2]; var fileInfo = fileScope.FileProvider.GetRelativeFileInfo(fileScope.BasePath, filePath); if (!fileInfo.Exists) { throw new FileNotFoundException(filePath); } - using (var fileStream = fileInfo.CreateReadStream()) - { - using (var streamReader = new StreamReader(fileStream)) - { - return streamReader.ReadToEnd(); - } - } + using var fileStream = fileInfo.CreateReadStream(); + using var streamReader = new StreamReader(fileStream); + return streamReader.ReadToEnd(); } else if (script.StartsWith("base64('", StringComparison.Ordinal) && script.EndsWith("')", StringComparison.Ordinal)) { - var filePath = script.Substring(8, script.Length - 10); + var filePath = script[8..^2]; var fileInfo = fileScope.FileProvider.GetRelativeFileInfo(fileScope.BasePath, filePath); if (!fileInfo.Exists) { throw new FileNotFoundException(filePath); } - using (var fileStream = fileInfo.CreateReadStream()) - { - using (var ms = new MemoryStream()) - { - fileStream.CopyTo(ms); - return Convert.ToBase64String(ms.ToArray()); - } - } + using var fileStream = fileInfo.CreateReadStream(); + using var ms = new MemoryStream(); + fileStream.CopyTo(ms); + return Convert.ToBase64String(ms.ToArray()); } else { diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellConfigurationSources.cs b/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellConfigurationSources.cs index 506e43922cb..ef8670252c5 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellConfigurationSources.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellConfigurationSources.cs @@ -148,14 +148,12 @@ private async Task TryMigrateFromFileAsync(string tenant, JObject configur return false; } - using (var file = File.OpenText(appsettings)) - { - var configuration = await file.ReadToEndAsync(); + using var file = File.OpenText(appsettings); + var configuration = await file.ReadToEndAsync(); - if (configuration != null) - { - configurations[tenant] = JObject.Parse(configuration); - } + if (configuration != null) + { + configurations[tenant] = JObject.Parse(configuration); } return true; diff --git a/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellsSettingsSources.cs b/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellsSettingsSources.cs index c6d05afa435..ab8870609b4 100644 --- a/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellsSettingsSources.cs +++ b/src/OrchardCore/OrchardCore.Infrastructure/Shells.Database/Configuration/DatabaseShellsSettingsSources.cs @@ -154,11 +154,10 @@ private async Task TryMigrateFromFileAsync(DatabaseShellsSettings document return false; } - using (var file = File.OpenText(_tenants)) - { - var settings = await file.ReadToEndAsync(); - document.ShellsSettings = JObject.Parse(settings); - } + using var file = File.OpenText(_tenants); + var settings = await file.ReadToEndAsync(); + + document.ShellsSettings = JObject.Parse(settings); return true; } diff --git a/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidFilterDelegateResolver.cs b/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidFilterDelegateResolver.cs index 615f56cbf52..5e9123e2c47 100644 --- a/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidFilterDelegateResolver.cs +++ b/src/OrchardCore/OrchardCore.Liquid.Abstractions/LiquidFilterDelegateResolver.cs @@ -10,11 +10,8 @@ public class LiquidFilterDelegateResolver where TLiquidFilter : c { public ValueTask ResolveAsync(FluidValue input, FilterArguments arguments, TemplateContext context) { - var ctx = context as LiquidTemplateContext; - if (ctx == null) - { - 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.Localization.Abstractions/CultureDictionaryRecordKey.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecordKey.cs index 299ce34c97d..b8d2bdb9d30 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecordKey.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/CultureDictionaryRecordKey.cs @@ -5,7 +5,7 @@ namespace OrchardCore.Localization /// /// Represents a key for . /// - public struct CultureDictionaryRecordKey : IEquatable + public readonly struct CultureDictionaryRecordKey : IEquatable { private readonly string _messageId; private readonly string _context; @@ -55,5 +55,9 @@ public override string ToString() => String.IsNullOrEmpty(_context) ? _messageId : _context.ToLowerInvariant() + "|" + _messageId; + + public static bool operator ==(CultureDictionaryRecordKey left, CultureDictionaryRecordKey right) => left.Equals(right); + + public static bool operator !=(CultureDictionaryRecordKey left, CultureDictionaryRecordKey right) => !(left == right); } } diff --git a/src/OrchardCore/OrchardCore.Localization.Abstractions/LanguageDirection.cs b/src/OrchardCore/OrchardCore.Localization.Abstractions/LanguageDirection.cs index 29c84cb2fc2..4b97ef2da3a 100644 --- a/src/OrchardCore/OrchardCore.Localization.Abstractions/LanguageDirection.cs +++ b/src/OrchardCore/OrchardCore.Localization.Abstractions/LanguageDirection.cs @@ -8,10 +8,10 @@ public static class LanguageDirection /// /// Defines left to right direction. /// - public static readonly string LTR = "ltr"; + public const string LTR = "ltr"; /// /// Defines right to left direction. /// - public static readonly string RTL = "rtl"; + public const string RTL = "rtl"; } diff --git a/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/DataAnnotationsDefaultErrorMessages.cs b/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/DataAnnotationsDefaultErrorMessages.cs index 17523f92f55..3d955613fc9 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/DataAnnotationsDefaultErrorMessages.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/DataAnnotations/DataAnnotationsDefaultErrorMessages.cs @@ -7,12 +7,9 @@ namespace OrchardCore.Localization.DataAnnotations /// internal sealed class DataAnnotationsDefaultErrorMessages { +#pragma warning disable IDE1006 // Naming Styles private readonly IStringLocalizer S = null; - - private DataAnnotationsDefaultErrorMessages() - { - - } +#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."]; diff --git a/src/OrchardCore/OrchardCore.Localization.Core/LocalizationManager.cs b/src/OrchardCore/OrchardCore.Localization.Core/LocalizationManager.cs index d3b02a78176..828b9d5848c 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/LocalizationManager.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/LocalizationManager.cs @@ -14,7 +14,7 @@ public class LocalizationManager : ILocalizationManager { private const string CacheKeyPrefix = "CultureDictionary-"; - private static readonly PluralizationRuleDelegate DefaultPluralRule = n => (n != 1 ? 1 : 0); + private static readonly PluralizationRuleDelegate _defaultPluralRule = n => (n != 1 ? 1 : 0); private readonly IList _pluralRuleProviders; private readonly IEnumerable _translationProviders; @@ -41,7 +41,7 @@ public CultureDictionary GetDictionary(CultureInfo culture) { var cachedDictionary = _cache.GetOrCreate(CacheKeyPrefix + culture.Name, k => new Lazy(() => { - var rule = DefaultPluralRule; + var rule = _defaultPluralRule; foreach (var provider in _pluralRuleProviders) { @@ -51,7 +51,7 @@ public CultureDictionary GetDictionary(CultureInfo culture) } } - var dictionary = new CultureDictionary(culture.Name, rule ?? DefaultPluralRule); + var dictionary = new CultureDictionary(culture.Name, rule ?? _defaultPluralRule); foreach (var translationProvider in _translationProviders) { translationProvider.LoadTranslations(culture.Name, dictionary); diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoFilesTranslationsProvider.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoFilesTranslationsProvider.cs index a3d9e3905e3..4c49f5f8116 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoFilesTranslationsProvider.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoFilesTranslationsProvider.cs @@ -34,13 +34,9 @@ private void LoadFileToDictionary(IFileInfo fileInfo, CultureDictionary dictiona { if (fileInfo.Exists && !fileInfo.IsDirectory) { - using (var stream = fileInfo.CreateReadStream()) - { - using (var reader = new StreamReader(stream)) - { - dictionary.MergeTranslations(_parser.Parse(reader)); - } - } + using var stream = fileInfo.CreateReadStream(); + using var reader = new StreamReader(stream); + dictionary.MergeTranslations(_parser.Parse(reader)); } } } diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoParser.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoParser.cs index e4429a70b3f..3ee695ec81f 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoParser.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PoParser.cs @@ -11,10 +11,11 @@ namespace OrchardCore.Localization.PortableObject /// public class PoParser { - private static readonly Dictionary _escapeTranslations = new Dictionary { + private static readonly Dictionary _escapeTranslations = new() + { { 'n', '\n' }, { 'r', '\r' }, - { 't', '\t' } + { 't', '\t' }, }; /// @@ -22,7 +23,9 @@ public class PoParser /// /// The . /// A list of culture records. +#pragma warning disable CA1822 // Mark members as static public IEnumerable Parse(TextReader reader) +#pragma warning restore CA1822 // Mark members as static { var entryBuilder = new DictionaryRecordBuilder(); string line; @@ -50,7 +53,7 @@ public IEnumerable Parse(TextReader reader) } } - private string Unescape(string str) + private static string Unescape(string str) { StringBuilder sb = null; var escaped = false; @@ -64,9 +67,10 @@ private string Unescape(string str) sb = new StringBuilder(str.Length); if (i > 1) { - sb.Append(str.Substring(0, i - 1)); + sb.Append(str[..(i - 1)]); } } + char unescaped; if (_escapeTranslations.TryGetValue(c, out unescaped)) { @@ -85,16 +89,17 @@ private string Unescape(string str) { escaped = true; } - else if (sb != null) + else { - sb.Append(c); + sb?.Append(c); } } } - return sb == null ? str : sb.ToString(); + + return sb?.ToString() ?? str; } - private string TrimQuote(string str) + private static string TrimQuote(string str) { if (str.StartsWith('\"') && str.EndsWith('\"')) { @@ -103,13 +108,13 @@ private string TrimQuote(string str) return ""; } - return str.Substring(1, str.Length - 2); + return str[1..^1]; } return str; } - private (PoContext context, string content) ParseLine(string line) + private static (PoContext context, string content) ParseLine(string line) { if (line.StartsWith('\"')) { @@ -119,24 +124,24 @@ private string TrimQuote(string str) var keyAndValue = line.Split(null, 2); if (keyAndValue.Length != 2) { - return (PoContext.Other, string.Empty); + return (PoContext.Other, String.Empty); } var content = Unescape(TrimQuote(keyAndValue[1].Trim())); - switch (keyAndValue[0]) + return keyAndValue[0] switch { - case "msgctxt": return (PoContext.MessageContext, content); - case "msgid": return (PoContext.MessageId, content); - case "msgid_plural": return (PoContext.MessageIdPlural, content); - case var key when key.StartsWith("msgstr", StringComparison.Ordinal): return (PoContext.Translation, content); - default: return (PoContext.Other, content); - } + "msgctxt" => (PoContext.MessageContext, content), + "msgid" => (PoContext.MessageId, content), + "msgid_plural" => (PoContext.MessageIdPlural, content), + var key when key.StartsWith("msgstr", StringComparison.Ordinal) => (PoContext.Translation, content), + _ => (PoContext.Other, content), + }; } private class DictionaryRecordBuilder { - private List _values; - private IEnumerable _validValues => _values.Where(value => !string.IsNullOrEmpty(value)); + private readonly List _values; + private IEnumerable _validValues => _values.Where(value => !String.IsNullOrEmpty(value)); private PoContext _context; public string MessageId { get; private set; } @@ -144,7 +149,7 @@ private class DictionaryRecordBuilder public IEnumerable Values => _values; - public bool IsValid => !string.IsNullOrEmpty(MessageId) && _validValues.Any(); + public bool IsValid => !String.IsNullOrEmpty(MessageId) && _validValues.Any(); public bool ShouldFlushRecord => IsValid && _context == PoContext.Translation; public DictionaryRecordBuilder() @@ -160,7 +165,7 @@ public void Set(PoContext context, string text) { // 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 (String.IsNullOrEmpty(MessageId)) { _values.Clear(); } @@ -170,7 +175,7 @@ public void Set(PoContext context, string text) } 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 + case PoContext.Text: AppendText(text); return; // We don't want to set context to Text. } _context = context; @@ -185,7 +190,7 @@ private void AppendText(string text) case PoContext.Translation: if (_values.Count > 0) { - _values[_values.Count - 1] += text; + _values[^1] += text; } break; } diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizer.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizer.cs index a42a107ca0b..03285d9017f 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizer.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizer.cs @@ -38,7 +38,7 @@ public PortableObjectHtmlLocalizer(IStringLocalizer localizer) : base(localizer) // Otherwise an already formatted string containing curly braces will be wrongly reformatted. - if (_localizer is IPluralStringLocalizer pluralLocalizer && arguments.Length == 1 && arguments[0] is PluralizationArgument pluralArgument) + if (_localizer is IPluralStringLocalizer pluralLocalizer && arguments.Length == 1 && arguments[0] is PluralizationArgument) { // Get an unformatted string and all non plural arguments (1st one is the plural count). var (translation, argumentsWithCount) = pluralLocalizer.GetTranslation(name, arguments); diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizerFactory.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizerFactory.cs index b03a79d79fb..18dfea17442 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizerFactory.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectHtmlLocalizerFactory.cs @@ -15,37 +15,15 @@ public class PortableObjectHtmlLocalizerFactory : IHtmlLocalizerFactory /// Creates a new instance of . /// /// The . - public PortableObjectHtmlLocalizerFactory(IStringLocalizerFactory stringLocalizerFactory) - { + public PortableObjectHtmlLocalizerFactory(IStringLocalizerFactory stringLocalizerFactory) => _stringLocalizerFactory = stringLocalizerFactory; - } /// - public IHtmlLocalizer Create(Type resourceSource) - { - return new PortableObjectHtmlLocalizer(_stringLocalizerFactory.Create(resourceSource)); - } + public IHtmlLocalizer Create(Type resourceSource) => + new PortableObjectHtmlLocalizer(_stringLocalizerFactory.Create(resourceSource)); /// - public IHtmlLocalizer Create(string baseName, string location) - { - var index = 0; - if (baseName.StartsWith(location, StringComparison.OrdinalIgnoreCase)) - { - index = location.Length; - } - - if (baseName.Length > index && baseName[index] == '.') - { - index += 1; - } - - if (baseName.Length > index && baseName.IndexOf("Areas.", index, StringComparison.Ordinal) == index) - { - index += "Areas.".Length; - } - - return 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 778a280a344..d51f9cb6d85 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizer.cs @@ -13,13 +13,13 @@ namespace OrchardCore.Localization.PortableObject /// public class PortableObjectStringLocalizer : IPluralStringLocalizer { - private static readonly string DataAnnotationsDefaultErrorMessagesContext = typeof(DataAnnotationsDefaultErrorMessages).FullName; - private static readonly string LocalizedDataAnnotationsMvcOptionsContext = typeof(LocalizedDataAnnotationsMvcOptions).FullName; + private static readonly string _dataAnnotationsDefaultErrorMessagesContext = typeof(DataAnnotationsDefaultErrorMessages).FullName; + private static readonly string _localizedDataAnnotationsMvcOptionsContext = typeof(LocalizedDataAnnotationsMvcOptions).FullName; private readonly ILocalizationManager _localizationManager; private readonly bool _fallBackToParentCulture; private readonly ILogger _logger; - private string _context; + private readonly string _context; /// /// Creates a new instance of . @@ -62,7 +62,7 @@ public class PortableObjectStringLocalizer : IPluralStringLocalizer get { var (translation, argumentsWithCount) = GetTranslation(name, arguments); - var formatted = string.Format(translation.Value, argumentsWithCount); + var formatted = String.Format(translation.Value, argumentsWithCount); return new LocalizedString(name, formatted, translation.ResourceNotFound); } @@ -86,7 +86,7 @@ public virtual (LocalizedString, object[]) GetTranslation(string name, params ob throw new ArgumentNullException(nameof(name)); } - // Check if a plural form is called, which is when the only argument is of type PluralizationArgument + // Check if a plural form is called, which is when the only argument is of type PluralizationArgument. if (arguments.Length == 1 && arguments[0] is PluralizationArgument pluralArgument) { var translation = GetTranslation(name, _context, CultureInfo.CurrentUICulture, pluralArgument.Count); @@ -104,7 +104,7 @@ public virtual (LocalizedString, object[]) GetTranslation(string name, params ob argumentsWithCount = new object[] { pluralArgument.Count }; } - translation = translation ?? GetTranslation(pluralArgument.Forms, CultureInfo.CurrentUICulture, pluralArgument.Count); + translation ??= GetTranslation(pluralArgument.Forms, CultureInfo.CurrentUICulture, pluralArgument.Count); return (new LocalizedString(name, translation, translation == null), argumentsWithCount); } @@ -164,8 +164,8 @@ protected string GetTranslation(string[] pluralForms, CultureInfo culture, int? _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 - return pluralForms[pluralForms.Length - 1]; + // Use the latest available form. + return pluralForms[^1]; } return pluralForms[pluralForm]; @@ -202,11 +202,11 @@ string ExtractTranslation() { var key = CultureDictionaryRecord.GetKey(name, context); - // Extract translation from data annotations attributes - if (context == LocalizedDataAnnotationsMvcOptionsContext) + // Extract translation from data annotations attributes. + if (context == _localizedDataAnnotationsMvcOptionsContext) { - // Extract translation with context - key = CultureDictionaryRecord.GetKey(name, DataAnnotationsDefaultErrorMessagesContext); + // Extract translation with context. + key = CultureDictionaryRecord.GetKey(name, _dataAnnotationsDefaultErrorMessagesContext); translation = dictionary[key]; if (translation != null) @@ -214,7 +214,7 @@ string ExtractTranslation() return translation; } - // Extract translation without context + // Extract translation without context. key = CultureDictionaryRecord.GetKey(name, null); translation = dictionary[key]; @@ -224,12 +224,12 @@ string ExtractTranslation() } } - // Extract translation with context + // Extract translation with context. translation = dictionary[key, count]; if (context != null && translation == null) { - // Extract translation without context + // Extract translation without context. key = CultureDictionaryRecord.GetKey(name, null); translation = dictionary[key, count]; } @@ -240,7 +240,7 @@ string ExtractTranslation() } catch (PluralFormNotFoundException ex) { - _logger.LogWarning(ex.Message); + _logger.LogWarning(ex, "Plural form not found."); } return translation; diff --git a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizerFactory.cs b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizerFactory.cs index 79354cbfd1f..75cfa796f4d 100644 --- a/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizerFactory.cs +++ b/src/OrchardCore/OrchardCore.Localization.Core/PortableObject/PortableObjectStringLocalizerFactory.cs @@ -61,13 +61,13 @@ public IStringLocalizer Create(string baseName, string location) index += "Areas.".Length; } - var relativeName = baseName.Substring(index); + var relativeName = baseName[index..]; return new PortableObjectStringLocalizer(relativeName, _localizationManager, _fallBackToParentCulture, _logger); } - // The context within inner class - private string TryFixInnerClassPath(string context) + // The context within inner class. + private static string TryFixInnerClassPath(string context) { const char innerClassSeparator = '+'; var path = context; diff --git a/src/OrchardCore/OrchardCore.Logging.NLog/TenantLayoutRenderer.cs b/src/OrchardCore/OrchardCore.Logging.NLog/TenantLayoutRenderer.cs index 3ea358efa4b..fbbdebbebf5 100644 --- a/src/OrchardCore/OrchardCore.Logging.NLog/TenantLayoutRenderer.cs +++ b/src/OrchardCore/OrchardCore.Logging.NLog/TenantLayoutRenderer.cs @@ -8,7 +8,7 @@ namespace OrchardCore.Logging { /// - /// Print the tenant name + /// Print the tenant name. /// [LayoutRenderer(LayoutRendererName)] public class TenantLayoutRenderer : AspNetLayoutRendererBase @@ -19,11 +19,8 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent) { var tenantName = ShellScope.Context?.Settings.Name; - if (tenantName == null) - { - // If there is no ShellContext in the Features then the log is rendered from the Host. - tenantName = HttpContextAccessor.HttpContext.Features.Get()?.ShellContext.Settings.Name ?? "None"; - } + // If there is no ShellContext in the Features then the log is rendered from the Host. + tenantName ??= HttpContextAccessor.HttpContext.Features.Get()?.ShellContext.Settings.Name ?? "None"; builder.Append(tenantName); } diff --git a/src/OrchardCore/OrchardCore.Logging.Serilog/ApplicationBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Logging.Serilog/ApplicationBuilderExtensions.cs index c4c35557af6..9e932dc2972 100644 --- a/src/OrchardCore/OrchardCore.Logging.Serilog/ApplicationBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Logging.Serilog/ApplicationBuilderExtensions.cs @@ -5,7 +5,7 @@ namespace OrchardCore.Logging { public static class ApplicationBuilderExtensions { - [Obsolete] + [Obsolete("This method will be removed in a future version.", false)] public static IApplicationBuilder UseSerilogTenantNameLoggingMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware(); diff --git a/src/OrchardCore/OrchardCore.Logging.Serilog/WebHostBuilderExtensions.cs b/src/OrchardCore/OrchardCore.Logging.Serilog/WebHostBuilderExtensions.cs index e707a09af97..47cf4812a79 100644 --- a/src/OrchardCore/OrchardCore.Logging.Serilog/WebHostBuilderExtensions.cs +++ b/src/OrchardCore/OrchardCore.Logging.Serilog/WebHostBuilderExtensions.cs @@ -6,7 +6,7 @@ namespace OrchardCore.Logging { public static class WebHostBuilderExtensions { - [Obsolete] + [Obsolete("This method will be removed in a future version.", false)] public static IWebHostBuilder UseSerilogWeb(this IWebHostBuilder builder) { return builder.UseSerilog((hostingContext, configBuilder) => diff --git a/src/OrchardCore/OrchardCore.Media.Abstractions/Indexing/MediaFileIndexingOptions.cs b/src/OrchardCore/OrchardCore.Media.Abstractions/Indexing/MediaFileIndexingOptions.cs index e1b88092572..9019138c8e3 100644 --- a/src/OrchardCore/OrchardCore.Media.Abstractions/Indexing/MediaFileIndexingOptions.cs +++ b/src/OrchardCore/OrchardCore.Media.Abstractions/Indexing/MediaFileIndexingOptions.cs @@ -5,8 +5,7 @@ namespace OrchardCore.Media.Indexing { public class MediaFileIndexingOptions { - private readonly Dictionary _mediaFileTextProviderRegistrations = - new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _mediaFileTextProviderRegistrations = new(StringComparer.OrdinalIgnoreCase); public MediaFileIndexingOptions RegisterMediaFileTextProvider(string fileExtension) where TMediaFileTextProvider : class, IMediaFileTextProvider diff --git a/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStore.cs b/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStore.cs index f1277f05d8b..b66ac1fe44b 100644 --- a/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStore.cs +++ b/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStore.cs @@ -151,15 +151,15 @@ public virtual async Task CreateFileFromStreamAsync(string path, Stream foreach (var mediaCreatingEventHandler in _mediaCreatingEventHandlers) { // Creating stream disposed by using. - using (var creatingStream = outputStream) - { - // Stop disposal of inputStream, as creating stream is the object to dispose. - inputStream = null; - // Outputstream must be created by event handler. - outputStream = null; - - outputStream = await mediaCreatingEventHandler.MediaCreatingAsync(context, creatingStream); - } + using var creatingStream = outputStream; + + // Stop disposal of inputStream, as creating stream is the object to dispose. + inputStream = null; + + // Outputstream must be created by event handler. + outputStream = null; + + outputStream = await mediaCreatingEventHandler.MediaCreatingAsync(context, creatingStream); } return await _fileStore.CreateFileFromStreamAsync(context.Path, outputStream, overwrite); diff --git a/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStoreCacheFileProvider.cs b/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStoreCacheFileProvider.cs index 8bafb85018c..e78e5c40122 100644 --- a/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStoreCacheFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Media.Core/DefaultMediaFileStoreCacheFileProvider.cs @@ -16,7 +16,7 @@ public class DefaultMediaFileStoreCacheFileProvider : PhysicalFileProvider, IMed /// The path in the wwwroot folder containing the asset cache. /// The tenants name will be prepended to this path. /// - public static readonly string AssetsCachePath = "ms-cache"; + public const string AssetsCachePath = "ms-cache"; // Use default stream copy buffer size to stay in gen0 garbage collection. private const int StreamCopyBufferSize = 81920; @@ -48,7 +48,7 @@ public Task IsCachedAsync(string path) public async Task SetCacheAsync(Stream stream, IFileStoreEntry fileStoreEntry, CancellationToken cancellationToken) { // File store semantics include a leading slash. - var cachePath = Path.Combine(Root, fileStoreEntry.Path.Substring(1)); + var cachePath = Path.Combine(Root, fileStoreEntry.Path[1..]); var directory = Path.GetDirectoryName(cachePath); if (!Directory.Exists(directory)) @@ -64,15 +64,14 @@ public async Task SetCacheAsync(Stream stream, IFileStoreEntry fileStoreEntry, C { File.Delete(cachePath); } - using (var fileStream = File.Create(cachePath)) - { - await stream.CopyToAsync(fileStream, StreamCopyBufferSize); - await stream.FlushAsync(); - if (fileStream.Length == 0) - { - throw new Exception($"Error retrieving file (length equals 0 byte) : {cachePath}"); - } + using var fileStream = File.Create(cachePath); + await stream.CopyToAsync(fileStream, StreamCopyBufferSize, CancellationToken.None); + await stream.FlushAsync(CancellationToken.None); + + if (fileStream.Length == 0) + { + throw new Exception($"Error retrieving file (length equals 0 byte) : {cachePath}"); } } catch (Exception ex) diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ApplicationViewFileProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ApplicationViewFileProvider.cs index 3fb0bfcfde0..b8d488e2315 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ApplicationViewFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ApplicationViewFileProvider.cs @@ -56,7 +56,7 @@ public IDirectoryContents GetDirectoryContents(string subpath) if (tokenizer.Any(s => s == "Pages" || s == "Views")) { // Resolve the subpath relative to the application's module root. - var folderSubPath = folder.Substring(Application.ModuleRoot.Length); + var folderSubPath = folder[Application.ModuleRoot.Length..]; // And serve the contents from the physical application root folder. return new PhysicalDirectoryContents(Application.Root + folderSubPath); @@ -79,7 +79,7 @@ public IFileInfo GetFileInfo(string subpath) if (path.StartsWith(Application.ModuleRoot, StringComparison.Ordinal)) { // Resolve the subpath relative to the application's module. - var fileSubPath = path.Substring(Application.ModuleRoot.Length); + var fileSubPath = path[Application.ModuleRoot.Length..]; // And serve the file from the physical application root folder. return new PhysicalFileInfo(new FileInfo(Application.Root + fileSubPath)); @@ -101,7 +101,7 @@ public IChangeToken Watch(string filter) if (path.StartsWith(Application.ModuleRoot, StringComparison.Ordinal)) { // Resolve the subpath relative to the application's module. - var fileSubPath = path.Substring(Application.ModuleRoot.Length); + var fileSubPath = path[Application.ModuleRoot.Length..]; // And watch the application file from the physical application root folder. return new PollingFileChangeToken(new FileInfo(Application.Root + fileSubPath)); @@ -110,9 +110,6 @@ public IChangeToken Watch(string filter) return NullChangeToken.Singleton; } - private string NormalizePath(string path) - { - return path.Replace('\\', '/').Trim('/'); - } + private static string NormalizePath(string path) => path.Replace('\\', '/').Trim('/'); } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/ComponentViewLocationExpanderProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/ComponentViewLocationExpanderProvider.cs index 607cf2c3543..9fba083e492 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/ComponentViewLocationExpanderProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/ComponentViewLocationExpanderProvider.cs @@ -11,13 +11,13 @@ namespace OrchardCore.Mvc.LocationExpander { public class ComponentViewLocationExpanderProvider : IViewLocationExpanderProvider { - private static readonly string SharedViewsPath = "/Views/Shared/{0}" + RazorViewEngine.ViewExtension; - private static readonly string SharedPagesPath = "/Pages/Shared/{0}" + RazorViewEngine.ViewExtension; - private static readonly string[] RazorExtensions = new[] { RazorViewEngine.ViewExtension }; + private static readonly string _sharedViewsPath = "/Views/Shared/{0}" + RazorViewEngine.ViewExtension; + private static readonly string _sharedPagesPath = "/Pages/Shared/{0}" + RazorViewEngine.ViewExtension; + private static readonly string[] _razorExtensions = new[] { RazorViewEngine.ViewExtension }; private const string CacheKey = "ModuleComponentViewLocations"; private static List _modulesWithComponentViews; private static List _modulesWithPagesComponentViews; - private static object _synLock = new object(); + private static readonly object _synLock = new(); private static bool _initialized; private readonly IExtensionManager _extensionManager; @@ -53,7 +53,7 @@ public class ComponentViewLocationExpanderProvider : IViewLocationExpanderProvid foreach (var module in orderedModules) { var moduleComponentsViewFilePaths = fileProviderAccessor.FileProvider.GetViewFilePaths( - module.SubPath + "/Views/Shared/Components", RazorExtensions, + module.SubPath + "/Views/Shared/Components", _razorExtensions, viewsFolder: null, inViewsFolder: true, inDepth: true); if (moduleComponentsViewFilePaths.Any()) @@ -62,7 +62,7 @@ public class ComponentViewLocationExpanderProvider : IViewLocationExpanderProvid } var modulePagesComponentsViewFilePaths = fileProviderAccessor.FileProvider.GetViewFilePaths( - module.SubPath + "/Pages/Shared/Components", RazorExtensions, + module.SubPath + "/Pages/Shared/Components", _razorExtensions, viewsFolder: null, inViewsFolder: true, inDepth: true); if (modulePagesComponentsViewFilePaths.Any()) @@ -112,10 +112,10 @@ public void PopulateValues(ViewLocationExpanderContext context) moduleComponentViewLocations = _modulesWithComponentViews .Where(m => enabledExtensionIds.Contains(m.Id)) - .Select(m => '/' + m.SubPath + SharedViewsPath) + .Select(m => '/' + m.SubPath + _sharedViewsPath) .Concat(_modulesWithPagesComponentViews .Where(m => enabledExtensionIds.Contains(m.Id)) - .Select(m => '/' + m.SubPath + SharedPagesPath)) + .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 3dab1bb9208..8518c6fc4cd 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/CompositeViewLocationExpanderProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/CompositeViewLocationExpanderProvider.cs @@ -35,7 +35,7 @@ public void PopulateValues(ViewLocationExpanderContext context) } } - private IEnumerable DiscoverProviders(ViewLocationExpanderContext context) + private static IEnumerable DiscoverProviders(ViewLocationExpanderContext context) { return context .ActionContext diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/SharedViewLocationExpanderProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/SharedViewLocationExpanderProvider.cs index 55982dec1ac..eed18ba745e 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/SharedViewLocationExpanderProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/LocationExpander/SharedViewLocationExpanderProvider.cs @@ -11,15 +11,15 @@ namespace OrchardCore.Mvc.LocationExpander { public class SharedViewLocationExpanderProvider : IViewLocationExpanderProvider { - private static readonly string PageSharedViewsPath = "/Pages/Shared/{0}" + RazorViewEngine.ViewExtension; - private static readonly string SharedViewsPath = "/Views/Shared/{0}" + RazorViewEngine.ViewExtension; + private static readonly string _pageSharedViewsPath = "/Pages/Shared/{0}" + RazorViewEngine.ViewExtension; + private static readonly string _sharedViewsPath = "/Views/Shared/{0}" + RazorViewEngine.ViewExtension; - private static readonly string[] RazorExtensions = new[] { RazorViewEngine.ViewExtension }; + private static readonly string[] _razorExtensions = new[] { RazorViewEngine.ViewExtension }; private const string CacheKey = "ModuleSharedViewLocations"; private const string PageCacheKey = "ModulePageSharedViewLocations"; private static List _modulesWithPageSharedViews; private static List _modulesWithSharedViews; - private static object _synLock = new object(); + private static readonly object _synLock = new(); private readonly IExtensionManager _extensionManager; private readonly ShellDescriptor _shellDescriptor; @@ -54,7 +54,7 @@ public class SharedViewLocationExpanderProvider : IViewLocationExpanderProvider foreach (var module in orderedModules) { var modulePageSharedViewFilePaths = fileProviderAccessor.FileProvider.GetViewFilePaths( - module.SubPath + "/Pages/Shared", RazorExtensions, + module.SubPath + "/Pages/Shared", _razorExtensions, viewsFolder: null, inViewsFolder: true, inDepth: true); if (modulePageSharedViewFilePaths.Any()) @@ -63,7 +63,7 @@ public class SharedViewLocationExpanderProvider : IViewLocationExpanderProvider } var moduleSharedViewFilePaths = fileProviderAccessor.FileProvider.GetViewFilePaths( - module.SubPath + "/Views/Shared", RazorExtensions, + module.SubPath + "/Views/Shared", _razorExtensions, viewsFolder: null, inViewsFolder: true, inDepth: true); if (moduleSharedViewFilePaths.Any()) @@ -104,7 +104,7 @@ public void PopulateValues(ViewLocationExpanderContext context) { modulePageSharedViewLocations = _modulesWithPageSharedViews .Where(m => GetEnabledExtensionIds().Contains(m.Id)) - .Select(m => '/' + m.SubPath + PageSharedViewsPath); + .Select(m => '/' + m.SubPath + _pageSharedViewsPath); _memoryCache.Set(PageCacheKey, modulePageSharedViewLocations); } @@ -116,7 +116,7 @@ public void PopulateValues(ViewLocationExpanderContext context) { moduleSharedViewLocations = _modulesWithSharedViews .Where(m => GetEnabledExtensionIds().Contains(m.Id)) - .Select(m => '/' + m.SubPath + SharedViewsPath); + .Select(m => '/' + m.SubPath + _sharedViewsPath); _memoryCache.Set(CacheKey, moduleSharedViewLocations); } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs index ab68bd056f4..a17d2e130df 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ModuleProjectRazorFileProvider.cs @@ -18,7 +18,7 @@ public class ModuleProjectRazorFileProvider : IFileProvider { private static IList _pageFileProviders; private static Dictionary _roots; - private static object _synLock = new object(); + private static readonly object _synLock = new(); public ModuleProjectRazorFileProvider(IApplicationContext applicationContext) { @@ -57,8 +57,8 @@ public ModuleProjectRazorFileProvider(IApplicationContext applicationContext) var index = asset.ModuleAssetPath.IndexOf(module.Root, StringComparison.Ordinal); // Resolve the physical "{ModuleProjectDirectory}" from the project asset. - var filePath = asset.ModuleAssetPath.Substring(index + module.Root.Length); - var root = asset.ProjectAssetPath.Substring(0, asset.ProjectAssetPath.Length - filePath.Length); + var filePath = asset.ModuleAssetPath[(index + module.Root.Length)..]; + var root = asset.ProjectAssetPath[..^filePath.Length]; // Get the first module project asset which is under a "Pages" folder. var page = assets.FirstOrDefault(a => a.ProjectAssetPath.Contains("/Pages/")); @@ -103,22 +103,22 @@ public IDirectoryContents GetDirectoryContents(string subpath) if (folder.StartsWith(Application.ModulesRoot, StringComparison.Ordinal)) { // Remove "Areas/" from the folder path. - folder = folder.Substring(Application.ModulesRoot.Length); + folder = folder[Application.ModulesRoot.Length..]; var index = folder.IndexOf('/'); // "{ModuleId}/**". if (index != -1) { // Resolve the module id. - var module = folder.Substring(0, index); + var module = folder[..index]; - // Try to get the module project root and + // Try to get the module project root. if (_roots.TryGetValue(module, out var root) && - // check for a final or an intermadiate "Pages" segment. + // Check for a final or an intermadiate "Pages" segment. (folder.EndsWith("/Pages", StringComparison.Ordinal) || folder.Contains("/Pages/"))) { // Resolve the subpath relative to "{ModuleProjectDirectory}". - folder = root + folder.Substring(module.Length + 1); + folder = String.Concat(root, folder.AsSpan(module.Length + 1)); if (Directory.Exists(folder)) { @@ -145,20 +145,20 @@ public IFileInfo GetFileInfo(string subpath) if (path.StartsWith(Application.ModulesRoot, StringComparison.Ordinal)) { // Skip the "Areas/" root folder. - path = path.Substring(Application.ModulesRoot.Length); + path = path[Application.ModulesRoot.Length..]; var index = path.IndexOf('/'); // "{ModuleId}/**/*.*". if (index != -1) { // Resolve the module id. - var module = path.Substring(0, index); + var module = path[..index]; // Get the module root folder. if (_roots.TryGetValue(module, out var root)) { - // Resolve "{ModuleProjectDirectory}**/*.*" - var filePath = root + path.Substring(module.Length + 1); + // Resolve "{ModuleProjectDirectory}**/*.*". + var filePath = String.Concat(root, path.AsSpan(module.Length + 1)); if (File.Exists(filePath)) { @@ -185,20 +185,20 @@ public IChangeToken Watch(string filter) if (path.StartsWith(Application.ModulesRoot, StringComparison.Ordinal) && !path.Contains('*')) { // Skip the "Areas/" root folder. - path = path.Substring(Application.ModulesRoot.Length); + path = path[Application.ModulesRoot.Length..]; var index = path.IndexOf('/'); // "{ModuleId}/**/*.*". if (index != -1) { // Resolve the module id. - var module = path.Substring(0, index); + var module = path[..index]; // Get the module root folder. if (_roots.TryGetValue(module, out var root)) { - // Resolve "{ModuleProjectDirectory}**/*.*" - var filePath = root + path.Substring(module.Length + 1); + // Resolve "{ModuleProjectDirectory}**/*.*". + var filePath = String.Concat(root, path.AsSpan(module.Length + 1)); var directory = Path.GetDirectoryName(filePath); var fileName = Path.GetFileNameWithoutExtension(filePath); @@ -247,9 +247,6 @@ public IChangeToken Watch(string filter) return NullChangeToken.Singleton; } - private string NormalizePath(string path) - { - return path.Replace('\\', '/').Trim('/'); - } + private static string NormalizePath(string path) => path.Replace('\\', '/').Trim('/'); } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/RazorCompilationFileProviderAccessor.cs b/src/OrchardCore/OrchardCore.Mvc.Core/RazorCompilationFileProviderAccessor.cs index fff3d7e2164..a0bda3b5e25 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/RazorCompilationFileProviderAccessor.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/RazorCompilationFileProviderAccessor.cs @@ -24,10 +24,7 @@ public IFileProvider FileProvider { get { - if (_compositeFileProvider == null) - { - _compositeFileProvider = GetCompositeFileProvider(_options); - } + _compositeFileProvider ??= GetCompositeFileProvider(_options); return _compositeFileProvider; } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/PageConventionCollectionExtensions.cs b/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/PageConventionCollectionExtensions.cs index 627055c8ce4..7efda4f3c05 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/PageConventionCollectionExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/PageConventionCollectionExtensions.cs @@ -59,7 +59,7 @@ public static class PageConventionCollectionExtensions } else { - var cleanSubTemplate = route.Template.Substring(areaFolder.Length).TrimStart('/'); + var cleanSubTemplate = route.Template[areaFolder.Length..].TrimStart('/'); template = AttributeRouteModel.CombineTemplates(folderRoute, cleanSubTemplate); } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/SharedViewCompilerProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/SharedViewCompilerProvider.cs index 9de3434bbde..259112c2975 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/SharedViewCompilerProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/SharedViewCompilerProvider.cs @@ -10,7 +10,7 @@ namespace OrchardCore.Mvc /// public class SharedViewCompilerProvider : IViewCompilerProvider { - private object _synLock = new object(); + private readonly object _synLock = new(); private static IViewCompiler _compiler; private readonly IServiceProvider _services; diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ShellFeatureApplicationPart.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ShellFeatureApplicationPart.cs index e3c6899be03..1954505d039 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ShellFeatureApplicationPart.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ShellFeatureApplicationPart.cs @@ -19,7 +19,7 @@ public class ShellFeatureApplicationPart : ICompilationReferencesProvider { private static IEnumerable _referencePaths; - private static object _synLock = new object(); + private static readonly object _synLock = new(); private ShellBlueprint _shellBlueprint; private IEnumerable _tagHelpers; diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ShellFileVersionProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ShellFileVersionProvider.cs index 685c83cc722..cb5eb1b04b5 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ShellFileVersionProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ShellFileVersionProvider.cs @@ -19,8 +19,8 @@ namespace OrchardCore.Mvc public class ShellFileVersionProvider : IFileVersionProvider { private const string VersionKey = "v"; - private static readonly char[] QueryStringAndFragmentTokens = new[] { '?', '#' }; - private static readonly MemoryCache _sharedCache = new MemoryCache(new MemoryCacheOptions()); + private static readonly char[] _queryStringAndFragmentTokens = new[] { '?', '#' }; + private static readonly MemoryCache _sharedCache = new(new MemoryCacheOptions()); private readonly IFileProvider[] _fileProviders; private readonly IMemoryCache _cache; @@ -46,10 +46,10 @@ public string AddFileVersionToPath(PathString requestPathBase, string path) var resolvedPath = path; - var queryStringOrFragmentStartIndex = path.IndexOfAny(QueryStringAndFragmentTokens); + var queryStringOrFragmentStartIndex = path.IndexOfAny(_queryStringAndFragmentTokens); if (queryStringOrFragmentStartIndex != -1) { - resolvedPath = path.Substring(0, queryStringOrFragmentStartIndex); + resolvedPath = path[..queryStringOrFragmentStartIndex]; } if (Uri.TryCreate(resolvedPath, UriKind.Absolute, out var uri) && !uri.IsFile) @@ -72,7 +72,7 @@ public string AddFileVersionToPath(PathString requestPathBase, string path) // Try to get the hash from the cache shared across tenants. if (resolvedPath.StartsWith(requestPathBase.Value, StringComparison.OrdinalIgnoreCase)) { - if (_sharedCache.TryGetValue(resolvedPath.Substring(requestPathBase.Value.Length), out value)) + if (_sharedCache.TryGetValue(resolvedPath[requestPathBase.Value.Length..], out value)) { return QueryHelpers.AddQueryString(path, VersionKey, value); } @@ -91,7 +91,7 @@ public string AddFileVersionToPath(PathString requestPathBase, string path) requestPathBase.HasValue && resolvedPath.StartsWith(requestPathBase.Value, StringComparison.OrdinalIgnoreCase)) { - resolvedPath = resolvedPath.Substring(requestPathBase.Value.Length); + resolvedPath = resolvedPath[requestPathBase.Value.Length..]; cacheEntryOptions.AddExpirationToken(fileProvider.Watch(resolvedPath)); fileInfo = fileProvider.GetFileInfo(resolvedPath); } @@ -102,7 +102,7 @@ public string AddFileVersionToPath(PathString requestPathBase, string path) virtualPathBaseProvider.VirtualPathBase.HasValue && resolvedPath.StartsWith(virtualPathBaseProvider.VirtualPathBase.Value, StringComparison.OrdinalIgnoreCase)) { - resolvedPath = resolvedPath.Substring(virtualPathBaseProvider.VirtualPathBase.Value.Length); + resolvedPath = resolvedPath[virtualPathBaseProvider.VirtualPathBase.Value.Length..]; cacheEntryOptions.AddExpirationToken(fileProvider.Watch(resolvedPath)); fileInfo = fileProvider.GetFileInfo(resolvedPath); } @@ -134,14 +134,10 @@ public string AddFileVersionToPath(PathString requestPathBase, string path) private static string GetHashForFile(IFileInfo fileInfo) { - using (var sha256 = SHA256.Create()) - { - using (var readStream = fileInfo.CreateReadStream()) - { - var hash = sha256.ComputeHash(readStream); - return WebEncoders.Base64UrlEncode(hash); - } - } + using var sha256 = SHA256.Create(); + using var readStream = fileInfo.CreateReadStream(); + var hash = sha256.ComputeHash(readStream); + return WebEncoders.Base64UrlEncode(hash); } } } diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/ShellViewFeatureProvider.cs b/src/OrchardCore/OrchardCore.Mvc.Core/ShellViewFeatureProvider.cs index 2f4a621da91..6cddde3286d 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/ShellViewFeatureProvider.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/ShellViewFeatureProvider.cs @@ -31,7 +31,7 @@ public void PopulateFeature(IEnumerable parts, ViewsFeature fea { EnsureScopedServices(); - PopulateFeatureInternal(parts, feature); + PopulateFeatureInternal(feature); // Apply views feature providers registered at the tenant level. foreach (var provider in _featureProviders) @@ -51,7 +51,7 @@ public void PopulateFeature(IEnumerable parts, DevelopmentViews if (_hostingEnvironment.IsDevelopment() && refsFolderExists) { var viewsFeature = new ViewsFeature(); - PopulateFeatureInternal(parts, viewsFeature); + PopulateFeatureInternal(viewsFeature); // Apply views feature providers registered at the tenant level. foreach (var provider in _featureProviders) @@ -66,7 +66,7 @@ public void PopulateFeature(IEnumerable parts, DevelopmentViews } } - private void PopulateFeatureInternal(IEnumerable parts, ViewsFeature feature) + private void PopulateFeatureInternal(ViewsFeature feature) { // Retrieve mvc views feature providers but not this one. var mvcFeatureProviders = _applicationPartManager.FeatureProviders @@ -115,8 +115,7 @@ private void PopulateFeatureInternal(IEnumerable parts, ViewsFe } } - // Look for compiled views in the same assembly as the module - + // Look for compiled views in the same assembly as the module. if (module.Assembly.GetCustomAttributes().Any()) { assembliesWithViews.Add(module.Assembly); diff --git a/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/ControllerTypeExtensions.cs b/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/ControllerTypeExtensions.cs index 042b6004724..77b0a34245d 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/ControllerTypeExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/ControllerTypeExtensions.cs @@ -13,7 +13,7 @@ public static string ControllerName(this Type controllerType) } return controllerType.Name.EndsWith(nameof(Controller), StringComparison.OrdinalIgnoreCase) - ? controllerType.Name.Substring(0, controllerType.Name.Length - nameof(Controller).Length) + ? 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 93186832217..18f8608496f 100644 --- a/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/StringExtensions.cs +++ b/src/OrchardCore/OrchardCore.Mvc.Core/Utilities/StringExtensions.cs @@ -15,8 +15,8 @@ public static class StringExtensions { public static string CamelFriendly(this string camel) { - // optimize common cases - if (string.IsNullOrWhiteSpace(camel)) + // Optimize common cases. + if (String.IsNullOrWhiteSpace(camel)) { return ""; } @@ -25,7 +25,7 @@ public static string CamelFriendly(this string camel) for (var i = 0; i < camel.Length; ++i) { var c = camel[i]; - if (i != 0 && char.IsUpper(c)) + if (i != 0 && Char.IsUpper(c)) { sb.Append(' '); } @@ -42,7 +42,7 @@ public static string Ellipsize(this string text, int characterCount) public static string Ellipsize(this string text, int characterCount, string ellipsis, bool wordBoundary = false) { - if (string.IsNullOrWhiteSpace(text)) + if (String.IsNullOrWhiteSpace(text)) { return ""; } @@ -50,32 +50,32 @@ public static string Ellipsize(this string text, int characterCount, string elli if (characterCount < 0 || text.Length <= characterCount) return text; - // search beginning of word + // Search beginning of word. var backup = characterCount; while (characterCount > 0 && text[characterCount - 1].IsLetter()) { characterCount--; } - // search previous word + // Search previous word. while (characterCount > 0 && text[characterCount - 1].IsSpace()) { characterCount--; } - // if it was the last word, recover it, unless boundary is requested + // If it was the last word, recover it, unless boundary is requested. if (characterCount == 0 && !wordBoundary) { characterCount = backup; } - var trimmed = text.Substring(0, characterCount); + var trimmed = text[..characterCount]; return trimmed + ellipsis; } public static string HtmlClassify(this string text) { - if (string.IsNullOrWhiteSpace(text)) + if (String.IsNullOrWhiteSpace(text)) { return ""; } @@ -88,15 +88,15 @@ public static string HtmlClassify(this string text) var previousIsNotLetter = false; for (var i = 0; i < friendlier.Length; i++) { - char current = friendlier[i]; - if (IsLetter(current) || (char.IsDigit(current) && cursor > 0)) + var current = friendlier[i]; + if (IsLetter(current) || (Char.IsDigit(current) && cursor > 0)) { if (previousIsNotLetter && i != 0 && cursor > 0) { result[cursor++] = '-'; } - result[cursor++] = char.ToLowerInvariant(current); + result[cursor++] = Char.ToLowerInvariant(current); previousIsNotLetter = false; } else @@ -110,7 +110,7 @@ public static string HtmlClassify(this string text) public static LocalizedString OrDefault(this string text, LocalizedString defaultValue) { - return string.IsNullOrEmpty(text) + return String.IsNullOrEmpty(text) ? defaultValue : new LocalizedString(null, text); } @@ -128,7 +128,7 @@ public static string RemoveTags(this string html, bool htmlDecode = false) var inside = false; for (var i = 0; i < html.Length; i++) { - char current = html[i]; + var current = html[i]; switch (current) { @@ -156,7 +156,7 @@ public static string RemoveTags(this string html, bool htmlDecode = false) return stringResult; } - // not accounting for only \r (e.g. Apple OS 9 carriage return only new lines) + // Not accounting for only \r (e.g. Apple OS 9 carriage return only new lines). public static string ReplaceNewLinesWith(this string text, string replacement) { return String.IsNullOrWhiteSpace(text) @@ -167,11 +167,11 @@ public static string ReplaceNewLinesWith(this string text, string replacement) .Replace("\r\r", String.Format(replacement, "\r\n")); } - private static readonly char[] validSegmentChars = "/?#[]@\"^{}|`<>\t\r\n\f ".ToCharArray(); + 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 - // the relevant bits: + // Valid isegment from rfc3987 - http://tools.ietf.org/html/rfc3987#page-8 + // The relevant bits: // isegment = *ipchar // ipchar = iunreserved / pct-encoded / sub-delims / ":" / "@" // iunreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" / ucschar @@ -181,7 +181,7 @@ public static bool IsValidUrlSegment(this string segment) // // rough blacklist regex == m/^[^/?#[]@"^{}|\s`<>]+$/ (leaving off % to keep the regex simple) - return !segment.Any(validSegmentChars); + return !segment.Any(_validSegmentChars); } /// @@ -192,33 +192,35 @@ public static bool IsValidUrlSegment(this string segment) /// public static string ToSafeName(this string name) { - if (string.IsNullOrWhiteSpace(name)) + if (String.IsNullOrWhiteSpace(name)) { - return string.Empty; + return String.Empty; } name = RemoveDiacritics(name); name = name.Strip(c => !c.IsLetter() - && !char.IsDigit(c) + && !Char.IsDigit(c) ); name = name.Trim(); - // don't allow non A-Z chars as first letter, as they are not allowed in prefixes + // Don't allow non A-Z chars as first letter, as they are not allowed in prefixes. while (name.Length > 0 && !IsLetter(name[0])) { - name = name.Substring(1); + name = name[1..]; } if (name.Length > 128) - name = name.Substring(0, 128); + { + name = name[..128]; + } return name; } /// - /// Whether the char is a letter between A and Z or not + /// Whether the char is a letter between A and Z or not. /// public static bool IsLetter(this char c) { @@ -248,7 +250,7 @@ public static string RemoveDiacritics(this string name) } /// - /// Transforms the culture of a letter to its equivalent representation in the 0-127 ascii table, such as the letter 'é' is substituted by an 'e' + /// Transforms the culture of a letter to its equivalent representation in the 0-127 ascii table, such as the letter 'é' is substituted by an 'e'. /// /// /// @@ -256,11 +258,10 @@ public static string ReplaceDiacritics(this string s) { var stringBuilder = new StringBuilder(); var normalizedString = s.Normalize(NormalizationForm.FormD); - var c = '\0'; for (var i = 0; i <= normalizedString.Length - 1; i++) { - c = normalizedString[i]; + var c = normalizedString[i]; if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) { stringBuilder.Append(c); @@ -272,7 +273,7 @@ public static string ReplaceDiacritics(this string s) public static string Strip(this string subject, params char[] stripped) { - if (stripped == null || stripped.Length == 0 || string.IsNullOrEmpty(subject)) + if (stripped == null || stripped.Length == 0 || String.IsNullOrEmpty(subject)) { return subject; } @@ -311,7 +312,7 @@ public static string Strip(this string subject, Func predicate) public static bool Any(this string subject, params char[] chars) { - if (string.IsNullOrEmpty(subject) || chars == null || chars.Length == 0) + if (String.IsNullOrEmpty(subject) || chars == null || chars.Length == 0) { return false; } @@ -330,7 +331,7 @@ public static bool Any(this string subject, params char[] chars) public static bool All(this string subject, params char[] chars) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { return true; } @@ -354,14 +355,19 @@ public static bool All(this string subject, params char[] chars) public static string Translate(this string subject, char[] from, char[] to) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { return subject; } - if (from == null || to == null) + if (from == null) + { + throw new ArgumentNullException(nameof(from)); + } + + if (to == null) { - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(to)); } if (from.Length != to.Length) @@ -395,17 +401,19 @@ public static string Translate(this string subject, char[] from, char[] to) public static string ReplaceAll(this string original, IDictionary replacements) { - var pattern = $"{string.Join("|", replacements.Keys)}"; + var pattern = $"{String.Join("|", replacements.Keys)}"; return Regex.Replace(original, pattern, match => replacements[match.Value]); } public static string TrimEnd(this string rough, string trim = "") { if (rough == null) + { return null; + } return rough.EndsWith(trim, StringComparison.Ordinal) - ? rough.Substring(0, rough.Length - trim.Length) + ? rough[..^trim.Length] : rough; } @@ -433,7 +441,7 @@ public static string ToPascalCaseUnderscore(this string attribute) } /// - /// Converts an html attribute to pascal case + /// Converts an html attribute to pascal case. /// public static string ToPascalCaseDash(this string attribute) { diff --git a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs index 7c923fe048b..f32bc683b80 100644 --- a/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs +++ b/src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs @@ -59,7 +59,7 @@ public async Task> BuildMenuAsync(string name, ActionConte // Merge all menu hierarchies into a single one. Merge(menuItems); - // Remove unauthorized menu items + // Remove unauthorized menu items. menuItems = await AuthorizeAsync(menuItems, actionContext.HttpContext.User); // Compute Url and RouteValues properties to Href. @@ -209,7 +209,6 @@ private string GetUrl(string menuItemUrl, RouteValueDictionary routeValueDiction private async Task> AuthorizeAsync(IEnumerable items, ClaimsPrincipal user) { var filtered = new List(); - foreach (var item in items) { // TODO: Attach actual user and remove this clause. diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs b/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs index 1d404897047..c474cc2b507 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/Indexes/NotificationIndex.cs @@ -66,10 +66,10 @@ public override void Describe(DescribeContext context) }); } - private static readonly Regex HtmlRegex = new("<.*?>", RegexOptions.Compiled); + private static readonly Regex _htmlRegex = new("<.*?>", RegexOptions.Compiled); public static string StripHTML(string html) { - return HtmlRegex.Replace(html, String.Empty); + return _htmlRegex.Replace(html, String.Empty); } } diff --git a/src/OrchardCore/OrchardCore.Notifications.Core/Services/EmailNotificationProvider.cs b/src/OrchardCore/OrchardCore.Notifications.Core/Services/EmailNotificationProvider.cs index 8de11ef1837..8a55e4563a2 100644 --- a/src/OrchardCore/OrchardCore.Notifications.Core/Services/EmailNotificationProvider.cs +++ b/src/OrchardCore/OrchardCore.Notifications.Core/Services/EmailNotificationProvider.cs @@ -9,7 +9,7 @@ namespace OrchardCore.Notifications.Services; public class EmailNotificationProvider : INotificationMethodProvider { private readonly ISmtpService _smtpService; - private readonly IStringLocalizer S; + protected readonly IStringLocalizer S; public EmailNotificationProvider( ISmtpService smtpService, diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdScopeManager.cs b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdScopeManager.cs index a774856e22e..0ece764cddf 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdScopeManager.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdScopeManager.cs @@ -32,7 +32,7 @@ public class OpenIdScopeManager : OpenIddictScopeManager, IOpenI /// public virtual ValueTask FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken = default) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdTokenManager.cs b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdTokenManager.cs index a2fdaab9922..6252bf4294d 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdTokenManager.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/Services/Managers/OpenIdTokenManager.cs @@ -32,7 +32,7 @@ public class OpenIdTokenManager : OpenIddictTokenManager, IOpenI /// public virtual ValueTask FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken = default) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdApplicationStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdApplicationStore.cs index 68e5c2f0d3b..e7b9f7ccde0 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdApplicationStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdApplicationStore.cs @@ -71,7 +71,7 @@ public virtual async ValueTask DeleteAsync(TApplication application, Cancellatio /// public virtual async ValueTask FindByIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } @@ -84,7 +84,7 @@ public virtual async ValueTask FindByIdAsync(string identifier, Ca /// public virtual async ValueTask FindByClientIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } @@ -97,20 +97,20 @@ public virtual async ValueTask FindByClientIdAsync(string identifi /// public virtual async ValueTask FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } cancellationToken.ThrowIfCancellationRequested(); - return await _session.GetAsync(int.Parse(identifier, CultureInfo.InvariantCulture), collection: OpenIdCollection); + return await _session.GetAsync(Int32.Parse(identifier, CultureInfo.InvariantCulture), collection: OpenIdCollection); } /// public virtual IAsyncEnumerable FindByPostLogoutRedirectUriAsync(string uri, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(uri)) + if (String.IsNullOrEmpty(uri)) { throw new ArgumentException("The URI cannot be null or empty.", nameof(uri)); } @@ -125,7 +125,7 @@ public virtual IAsyncEnumerable FindByPostLogoutRedirectUriAsync(s /// public virtual IAsyncEnumerable FindByRedirectUriAsync(string uri, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(uri)) + if (String.IsNullOrEmpty(uri)) { throw new ArgumentException("The URI cannot be null or empty.", nameof(uri)); } @@ -300,7 +300,7 @@ public virtual ValueTask> GetRequirementsAsync(TApplicati /// public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) - => new ValueTask(new TApplication { ApplicationId = Guid.NewGuid().ToString("n") }); + => new(new TApplication { ApplicationId = Guid.NewGuid().ToString("n") }); /// public virtual IAsyncEnumerable ListAsync(int? count, int? offset, CancellationToken cancellationToken) @@ -523,7 +523,7 @@ public virtual ValueTask> GetRolesAsync(TApplication appl /// public virtual IAsyncEnumerable ListInRoleAsync(string role, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(role)) + if (String.IsNullOrEmpty(role)) { throw new ArgumentException("The role name cannot be null or empty.", nameof(role)); } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdAuthorizationStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdAuthorizationStore.cs index 7f45cf81bdb..9e69dcd6b97 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdAuthorizationStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdAuthorizationStore.cs @@ -74,12 +74,12 @@ public virtual async ValueTask DeleteAsync(TAuthorization authorization, Cancell public virtual IAsyncEnumerable FindAsync( string subject, string client, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } - if (string.IsNullOrEmpty(client)) + if (String.IsNullOrEmpty(client)) { throw new ArgumentException("The client cannot be null or empty.", nameof(client)); } @@ -95,17 +95,17 @@ public virtual async ValueTask DeleteAsync(TAuthorization authorization, Cancell public virtual IAsyncEnumerable FindAsync( string subject, string client, string status, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } - if (string.IsNullOrEmpty(client)) + if (String.IsNullOrEmpty(client)) { throw new ArgumentException("The client identifier cannot be null or empty.", nameof(client)); } - if (string.IsNullOrEmpty(status)) + if (String.IsNullOrEmpty(status)) { throw new ArgumentException("The status cannot be null or empty.", nameof(client)); } @@ -122,22 +122,22 @@ public virtual async ValueTask DeleteAsync(TAuthorization authorization, Cancell string subject, string client, string status, string type, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } - if (string.IsNullOrEmpty(client)) + if (String.IsNullOrEmpty(client)) { throw new ArgumentException("The client identifier cannot be null or empty.", nameof(client)); } - if (string.IsNullOrEmpty(status)) + if (String.IsNullOrEmpty(status)) { throw new ArgumentException("The status cannot be null or empty.", nameof(client)); } - if (string.IsNullOrEmpty(type)) + if (String.IsNullOrEmpty(type)) { throw new ArgumentException("The type cannot be null or empty.", nameof(client)); } @@ -168,7 +168,7 @@ await foreach (var authorization in FindAsync(subject, client, status, type, can public virtual IAsyncEnumerable FindByApplicationIdAsync( string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } @@ -183,7 +183,7 @@ await foreach (var authorization in FindAsync(subject, client, status, type, can /// public virtual async ValueTask FindByIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } @@ -198,21 +198,21 @@ public virtual async ValueTask FindByIdAsync(string identifier, /// public virtual async ValueTask FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } cancellationToken.ThrowIfCancellationRequested(); - return await _session.GetAsync(int.Parse(identifier, CultureInfo.InvariantCulture), collection: OpenIdCollection); + return await _session.GetAsync(Int32.Parse(identifier, CultureInfo.InvariantCulture), collection: OpenIdCollection); } /// public virtual IAsyncEnumerable FindBySubjectAsync( string subject, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } @@ -342,7 +342,7 @@ public virtual ValueTask GetTypeAsync(TAuthorization authorization, Canc /// public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) - => new ValueTask(new TAuthorization { AuthorizationId = Guid.NewGuid().ToString("n") }); + => new(new TAuthorization { AuthorizationId = Guid.NewGuid().ToString("n") }); /// public virtual IAsyncEnumerable ListAsync(int? count, int? offset, CancellationToken cancellationToken) @@ -406,10 +406,7 @@ public virtual async ValueTask PruneAsync(DateTimeOffset threshold, Cancellation } catch (Exception exception) { - if (exceptions == null) - { - exceptions = new List(capacity: 1); - } + exceptions ??= new List(capacity: 1); exceptions.Add(exception); } @@ -430,7 +427,7 @@ public virtual async ValueTask PruneAsync(DateTimeOffset threshold, Cancellation throw new ArgumentNullException(nameof(authorization)); } - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { authorization.ApplicationId = null; } diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdScopeStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdScopeStore.cs index 6a73be73d9e..e4b7d85dfda 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdScopeStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdScopeStore.cs @@ -72,7 +72,7 @@ public virtual async ValueTask DeleteAsync(TScope scope, CancellationToken cance /// public virtual async ValueTask FindByIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } @@ -85,7 +85,7 @@ public virtual async ValueTask FindByIdAsync(string identifier, Cancella /// public virtual async ValueTask FindByNameAsync(string name, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(name)) + if (String.IsNullOrEmpty(name)) { throw new ArgumentException("The scope name cannot be null or empty.", nameof(name)); } @@ -99,7 +99,7 @@ public virtual async ValueTask FindByNameAsync(string name, Cancellation public virtual IAsyncEnumerable FindByNamesAsync( ImmutableArray names, CancellationToken cancellationToken) { - if (names.Any(name => string.IsNullOrEmpty(name))) + if (names.Any(name => String.IsNullOrEmpty(name))) { throw new ArgumentException("Scope names cannot be null or empty.", nameof(names)); } @@ -112,20 +112,20 @@ public virtual async ValueTask FindByNameAsync(string name, Cancellation /// public virtual async ValueTask FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } cancellationToken.ThrowIfCancellationRequested(); - return await _session.GetAsync(int.Parse(identifier, CultureInfo.InvariantCulture), collection: OpenIdCollection); + return await _session.GetAsync(Int32.Parse(identifier, CultureInfo.InvariantCulture), collection: OpenIdCollection); } /// public virtual IAsyncEnumerable FindByResourceAsync(string resource, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(resource)) + if (String.IsNullOrEmpty(resource)) { throw new ArgumentException("The resource cannot be null or empty.", nameof(resource)); } @@ -262,7 +262,7 @@ public virtual ValueTask> GetResourcesAsync(TScope scope, /// public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) - => new ValueTask(new TScope { ScopeId = Guid.NewGuid().ToString("n") }); + => new(new TScope { ScopeId = Guid.NewGuid().ToString("n") }); /// public virtual IAsyncEnumerable ListAsync(int? count, int? offset, CancellationToken cancellationToken) diff --git a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdTokenStore.cs b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdTokenStore.cs index cccb63e7387..f044bcaad5e 100644 --- a/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdTokenStore.cs +++ b/src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Stores/OpenIdTokenStore.cs @@ -74,12 +74,12 @@ public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cance public virtual IAsyncEnumerable FindAsync( string subject, string client, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } - if (string.IsNullOrEmpty(client)) + if (String.IsNullOrEmpty(client)) { throw new ArgumentException("The client cannot be null or empty.", nameof(client)); } @@ -94,17 +94,17 @@ public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cance public virtual IAsyncEnumerable FindAsync( string subject, string client, string status, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } - if (string.IsNullOrEmpty(client)) + if (String.IsNullOrEmpty(client)) { throw new ArgumentException("The client identifier cannot be null or empty.", nameof(client)); } - if (string.IsNullOrEmpty(status)) + if (String.IsNullOrEmpty(status)) { throw new ArgumentException("The status cannot be null or empty.", nameof(status)); } @@ -119,22 +119,22 @@ public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cance public virtual IAsyncEnumerable FindAsync( string subject, string client, string status, string type, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } - if (string.IsNullOrEmpty(client)) + if (String.IsNullOrEmpty(client)) { throw new ArgumentException("The client identifier cannot be null or empty.", nameof(client)); } - if (string.IsNullOrEmpty(status)) + if (String.IsNullOrEmpty(status)) { throw new ArgumentException("The status cannot be null or empty.", nameof(status)); } - if (string.IsNullOrEmpty(type)) + if (String.IsNullOrEmpty(type)) { throw new ArgumentException("The type cannot be null or empty.", nameof(type)); } @@ -149,7 +149,7 @@ public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cance /// public virtual IAsyncEnumerable FindByApplicationIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } @@ -162,7 +162,7 @@ public virtual IAsyncEnumerable FindByApplicationIdAsync(string identifi /// public virtual IAsyncEnumerable FindByAuthorizationIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } @@ -175,7 +175,7 @@ public virtual IAsyncEnumerable FindByAuthorizationIdAsync(string identi /// public virtual async ValueTask FindByReferenceIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } @@ -188,7 +188,7 @@ public virtual async ValueTask FindByReferenceIdAsync(string identifier, /// public virtual async ValueTask FindByIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } @@ -201,20 +201,20 @@ public virtual async ValueTask FindByIdAsync(string identifier, Cancella /// public virtual async ValueTask FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } cancellationToken.ThrowIfCancellationRequested(); - return await _session.GetAsync(int.Parse(identifier, CultureInfo.InvariantCulture), collection: OpenIdCollection); + return await _session.GetAsync(Int32.Parse(identifier, CultureInfo.InvariantCulture), collection: OpenIdCollection); } /// public virtual IAsyncEnumerable FindBySubjectAsync(string subject, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } @@ -396,7 +396,7 @@ public virtual ValueTask GetTypeAsync(TToken token, CancellationToken ca /// public virtual ValueTask InstantiateAsync(CancellationToken cancellationToken) - => new ValueTask(new TToken { TokenId = Guid.NewGuid().ToString("n") }); + => new(new TToken { TokenId = Guid.NewGuid().ToString("n") }); /// public virtual IAsyncEnumerable ListAsync(int? count, int? offset, CancellationToken cancellationToken) @@ -458,10 +458,7 @@ public virtual async ValueTask PruneAsync(DateTimeOffset threshold, Cancellation } catch (Exception exception) { - if (exceptions == null) - { - exceptions = new List(capacity: 1); - } + exceptions ??= new List(capacity: 1); exceptions.Add(exception); } @@ -481,7 +478,7 @@ public virtual ValueTask SetApplicationIdAsync(TToken token, string identifier, throw new ArgumentNullException(nameof(token)); } - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { token.ApplicationId = null; } @@ -501,7 +498,7 @@ public virtual ValueTask SetAuthorizationIdAsync(TToken token, string identifier throw new ArgumentNullException(nameof(token)); } - if (string.IsNullOrEmpty(identifier)) + if (String.IsNullOrEmpty(identifier)) { token.AuthorizationId = null; } @@ -610,7 +607,7 @@ public virtual ValueTask SetStatusAsync(TToken token, string status, Cancellatio throw new ArgumentNullException(nameof(token)); } - if (string.IsNullOrEmpty(status)) + if (String.IsNullOrEmpty(status)) { throw new ArgumentException("The status cannot be null or empty.", nameof(status)); } @@ -628,7 +625,7 @@ public virtual ValueTask SetSubjectAsync(TToken token, string subject, Cancellat throw new ArgumentNullException(nameof(token)); } - if (string.IsNullOrEmpty(subject)) + if (String.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } @@ -646,7 +643,7 @@ public virtual ValueTask SetTypeAsync(TToken token, string type, CancellationTok throw new ArgumentNullException(nameof(token)); } - if (string.IsNullOrEmpty(type)) + if (String.IsNullOrEmpty(type)) { throw new ArgumentException("The token type cannot be null or empty.", nameof(type)); } diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IDetectRobots.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IDetectRobots.cs index 26d72e2f3a0..422386d300f 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IDetectRobots.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IDetectRobots.cs @@ -6,18 +6,18 @@ namespace OrchardCore.ReCaptcha.ActionFilters.Detection public interface IDetectRobots { /// - /// Performs a check to see if the current request could be submitted by a robot + /// Performs a check to see if the current request could be submitted by a robot. /// - /// Detection result + /// Detection result. RobotDetectionResult DetectRobot(); /// - /// Clear the detectors internal state, we are not dealing with a robot + /// Clear the detectors internal state, we are not dealing with a robot. /// void IsNotARobot(); /// - /// We are dealing with a robot, shields up + /// We are dealing with a robot, shields up. /// void FlagAsRobot(); } diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IpAddressRobotDetector.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IpAddressRobotDetector.cs index a3749f73d05..a0ebb8d2e61 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IpAddressRobotDetector.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IpAddressRobotDetector.cs @@ -51,7 +51,7 @@ public void FlagAsRobot() { var ipAddressKey = GetIpAddressCacheKey(); - // this has race conditions, but it's ok + // This has race conditions, but it's ok. var faultyRequestCount = _memoryCache.GetOrCreate(ipAddressKey, fact => 0); faultyRequestCount++; _memoryCache.Set(ipAddressKey, faultyRequestCount); diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/ReCaptchaMode.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/ReCaptchaMode.cs index ec999f239a9..ff5dc158b5d 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/ReCaptchaMode.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/ReCaptchaMode.cs @@ -3,12 +3,12 @@ namespace OrchardCore.ReCaptcha.ActionFilters public enum ReCaptchaMode { /// - /// Captcha is always shown + /// Captcha is always shown. /// AlwaysShow, /// - /// Captcha initially is not shown, but when a robot is detected it will show on until dismissed + /// Captcha initially is not shown, but when a robot is detected it will show on until dismissed. /// PreventRobots } diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettings.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettings.cs index bc4bc7a922a..c73ff7bf087 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettings.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Configuration/ReCaptchaSettings.cs @@ -1,3 +1,5 @@ +using System; + namespace OrchardCore.ReCaptcha.Configuration { public class ReCaptchaSettings @@ -11,13 +13,13 @@ public class ReCaptchaSettings public string ReCaptchaApiUri { get; set; } = Constants.ReCaptchaApiUri; /// - /// Value for supplying the amount of lenience we are willing to show robots + /// Value for supplying the amount of lenience we are willing to show robots. /// public int DetectionThreshold { get; set; } = 5; public bool IsValid() { - return !string.IsNullOrWhiteSpace(SiteKey) && !string.IsNullOrWhiteSpace(SecretKey); + return !String.IsNullOrWhiteSpace(SiteKey) && !String.IsNullOrWhiteSpace(SecretKey); } } } diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaClient.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaClient.cs index 5a0c9b31d43..92e8560fb90 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaClient.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaClient.cs @@ -23,14 +23,14 @@ public ReCaptchaClient(HttpClient httpClient, IOptions option } /// - /// Verifies the supplied token with ReCaptcha Api + /// Verifies the supplied token with ReCaptcha Api. /// - /// Token received from the ReCaptcha UI - /// Key entered by user in the secrets - /// A boolean indicating if the token is valid + /// Token received from the ReCaptcha UI. + /// Key entered by user in the secrets. + /// A boolean indicating if the token is valid. public async Task VerifyAsync(string responseToken, string secretKey) { - if (string.IsNullOrWhiteSpace(responseToken)) + if (String.IsNullOrWhiteSpace(responseToken)) { return false; } @@ -51,7 +51,7 @@ public async Task VerifyAsync(string responseToken, string secretKey) } catch (HttpRequestException e) { - _logger.LogError(e, "Could not contact Google to verify captcha"); + _logger.LogError(e, "Could not contact Google to verify captcha."); } return false; diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaService.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaService.cs index b6c77762a67..8c1178adde6 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaService.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/Services/ReCaptchaService.cs @@ -19,7 +19,7 @@ public class ReCaptchaService private readonly IEnumerable _robotDetectors; private readonly IHttpContextAccessor _httpContextAccessor; private readonly ILogger _logger; - private readonly IStringLocalizer S; + protected readonly IStringLocalizer S; public ReCaptchaService(ReCaptchaClient reCaptchaClient, IOptions optionsAccessor, IEnumerable robotDetectors, IHttpContextAccessor httpContextAccessor, ILogger logger, IStringLocalizer stringLocalizer) { @@ -32,7 +32,7 @@ public ReCaptchaService(ReCaptchaClient reCaptchaClient, IOptions - /// Flags the behavior as that of a robot + /// Flags the behavior as that of a robot. /// public void MaybeThisIsARobot() { @@ -40,9 +40,9 @@ public void MaybeThisIsARobot() } /// - /// Determines if the request has been made by a robot + /// Determines if the request has been made by a robot. /// - /// Yes (true) or no (false) + /// Yes (true) or no (false). public bool IsThisARobot() { var result = _robotDetectors.Invoke(i => i.DetectRobot(), _logger); @@ -50,7 +50,7 @@ public bool IsThisARobot() } /// - /// Clears all robot markers, we are dealing with a human + /// Clears all robot markers, we are dealing with a human. /// /// public void ThisIsAHuman() @@ -59,7 +59,7 @@ public void ThisIsAHuman() } /// - /// Verifies the ReCaptcha response with the ReCaptcha webservice + /// Verifies the ReCaptcha response with the ReCaptcha webservice. /// /// /// @@ -69,9 +69,9 @@ public async Task VerifyCaptchaResponseAsync(string reCaptchaResponse) } /// - /// Validates the captcha that is in the Form of the current request + /// Validates the captcha that is in the Form of the current request. /// - /// Lambda for reporting errors + /// Lambda for reporting errors. public async Task ValidateCaptchaAsync(Action reportError) { if (!_settings.IsValid()) @@ -83,7 +83,7 @@ public async Task ValidateCaptchaAsync(Action reportError) // We use the header value as default if it's passed var reCaptchaResponse = _httpContextAccessor.HttpContext?.Request.Headers[Constants.ReCaptchaServerResponseHeaderName]; - // If this is a standard form post we get the token from the form values if not affected previously in the header + // If this is a standard form post we get the token from the form values if not affected previously in the header. if (String.IsNullOrEmpty(reCaptchaResponse) && (_httpContextAccessor.HttpContext?.Request.HasFormContentType ?? false)) { reCaptchaResponse = _httpContextAccessor.HttpContext.Request.Form[Constants.ReCaptchaServerResponseHeaderName].ToString(); diff --git a/src/OrchardCore/OrchardCore.ReCaptcha.Core/TagHelpers/ReCaptchaTagHelper.cs b/src/OrchardCore/OrchardCore.ReCaptcha.Core/TagHelpers/ReCaptchaTagHelper.cs index e14ef46451b..8c125f9d2fc 100644 --- a/src/OrchardCore/OrchardCore.ReCaptcha.Core/TagHelpers/ReCaptchaTagHelper.cs +++ b/src/OrchardCore/OrchardCore.ReCaptcha.Core/TagHelpers/ReCaptchaTagHelper.cs @@ -1,3 +1,4 @@ +using System; using System.Globalization; using System.Linq; using System.Threading.Tasks; @@ -5,7 +6,6 @@ using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OrchardCore.Localization; @@ -26,25 +26,28 @@ public class ReCaptchaTagHelper : TagHelper private readonly ReCaptchaSettings _settings; private readonly ILogger _logger; private readonly ILocalizationService _localizationService; - private readonly IStringLocalizer S; - public ReCaptchaTagHelper(IOptions optionsAccessor, IResourceManager resourceManager, ILocalizationService localizationService, IHttpContextAccessor httpContextAccessor, ILogger logger, IStringLocalizer localizer) + public ReCaptchaTagHelper( + IOptions optionsAccessor, + IResourceManager resourceManager, + ILocalizationService localizationService, + IHttpContextAccessor httpContextAccessor, + ILogger logger) { _resourceManager = resourceManager; _httpContextAccessor = httpContextAccessor; _settings = optionsAccessor.Value; Mode = ReCaptchaMode.PreventRobots; - _logger = logger; _localizationService = localizationService; - S = localizer; + _logger = logger; } [HtmlAttributeName("mode")] public ReCaptchaMode Mode { get; set; } /// - /// The two letter ISO code of the language the captcha should be displayed in - /// When left blank it will fall back to the default OrchardCore language + /// The two letter ISO code of the language the captcha should be displayed in. + /// When left blank it will fall back to the default OrchardCore language. /// [HtmlAttributeName("language")] public string Language { get; set; } @@ -87,8 +90,10 @@ private async Task GetCultureAsync() var language = Language; CultureInfo culture = null; - if (string.IsNullOrWhiteSpace(language)) + if (String.IsNullOrWhiteSpace(language)) + { language = await _localizationService.GetDefaultCultureAsync(); + } try { @@ -96,7 +101,7 @@ private async Task GetCultureAsync() } catch (CultureNotFoundException) { - _logger.LogWarning(S["Language with name {0} not found", language]); + _logger.LogWarning("Language with name {LanguageName} not found.", language); } return culture; diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/ConfigurationMethodProvider.cs b/src/OrchardCore/OrchardCore.Recipes.Core/ConfigurationMethodProvider.cs index 4fbf66b9d01..1de5fe57039 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/ConfigurationMethodProvider.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/ConfigurationMethodProvider.cs @@ -15,7 +15,7 @@ public ConfigurationMethodProvider(IShellConfiguration configuration) _globalMethod = new GlobalMethod { Name = "configuration", - Method = serviceprovider => (Func)((key, defaultValue) => configuration.GetValue(key, defaultValue)) + Method = serviceprovider => (Func)((key, defaultValue) => configuration.GetValue(key, defaultValue)), }; } diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/ParametersMethodProvider.cs b/src/OrchardCore/OrchardCore.Recipes.Core/ParametersMethodProvider.cs index d0fa858ff6d..904ad170181 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/ParametersMethodProvider.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/ParametersMethodProvider.cs @@ -19,7 +19,7 @@ public ParametersMethodProvider(object environment) Method = serviceprovider => (Func)(name => { return environmentObject.SelectToken(name)?.Value(); - }) + }), }; } diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeExecutor.cs b/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeExecutor.cs index f1cdaddaefe..046a20601a8 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeExecutor.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeExecutor.cs @@ -25,7 +25,7 @@ public class RecipeExecutor : IRecipeExecutor private readonly IEnumerable _recipeEventHandlers; private readonly ILogger _logger; - private readonly Dictionary> _methodProviders = new Dictionary>(); + private readonly Dictionary> _methodProviders = new(); public RecipeExecutor( IShellHost shellHost, @@ -59,24 +59,24 @@ public async Task ExecuteAsync(string executionId, RecipeDescriptor reci using var reader = new JsonTextReader(file); // Go to Steps, then iterate. - while (await reader.ReadAsync()) + while (await reader.ReadAsync(cancellationToken)) { if (reader.Path == "variables") { - await reader.ReadAsync(); + await reader.ReadAsync(cancellationToken); - var variables = await JObject.LoadAsync(reader); + var variables = await JObject.LoadAsync(reader, cancellationToken); methodProviders.Add(new VariablesMethodProvider(variables, methodProviders)); } if (reader.Path == "steps" && reader.TokenType == JsonToken.StartArray) { - while (await reader.ReadAsync() && reader.Depth > 1) + while (await reader.ReadAsync(cancellationToken) && reader.Depth > 1) { if (reader.Depth == 2) { - var child = await JObject.LoadAsync(reader); + var child = await JObject.LoadAsync(reader, cancellationToken); var recipeStep = new RecipeExecutionContext { @@ -162,7 +162,7 @@ private async Task ExecuteStepAsync(RecipeExecutionContext recipeStep) var recipeStepHandlers = scope.ServiceProvider.GetServices(); var scriptingManager = scope.ServiceProvider.GetRequiredService(); - // Substitutes the script elements by their actual values + // Substitutes the script elements by their actual values. EvaluateJsonTree(scriptingManager, recipeStep, recipeStep.Step); if (_logger.IsEnabled(LogLevel.Information)) @@ -212,11 +212,12 @@ private void EvaluateJsonTree(IScriptingManager scriptingManager, RecipeExecutio const char scriptSeparator = ':'; var value = node.Value(); - // Evaluate the expression while the result is another expression + // Evaluate the expression while the result is another expression. while (value.StartsWith('[') && value.EndsWith(']')) { var scriptSeparatorIndex = value.IndexOf(scriptSeparator); - // Only remove brackets if this is a valid script expression, e.g. '[js:xxx]', or '[file:xxx]' + + // Only remove brackets if this is a valid script expression, e.g. '[js:xxx]', or '[file:xxx]'. if (!(scriptSeparatorIndex > -1 && value[1..scriptSeparatorIndex].All(c => Char.IsLetter(c)))) { break; diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeReader.cs b/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeReader.cs index 7caa7cce1fc..b7f0d18c42f 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeReader.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/Services/RecipeReader.cs @@ -11,24 +11,19 @@ public class RecipeReader : IRecipeReader { public async Task GetRecipeDescriptorAsync(string recipeBasePath, IFileInfo recipeFileInfo, IFileProvider recipeFileProvider) { - // TODO: Try to optimize by only reading the required metadata instead of the whole file + // TODO: Try to optimize by only reading the required metadata instead of the whole file. - using (var stream = recipeFileInfo.CreateReadStream()) - { - using (var reader = new StreamReader(stream)) - { - using (var jsonReader = new JsonTextReader(reader)) - { - var recipeDescriptor = (await JObject.LoadAsync(jsonReader)).ToObject(); + using var stream = recipeFileInfo.CreateReadStream(); + using var reader = new StreamReader(stream); + using var jsonReader = new JsonTextReader(reader); - recipeDescriptor.FileProvider = recipeFileProvider; - recipeDescriptor.BasePath = recipeBasePath; - recipeDescriptor.RecipeFileInfo = recipeFileInfo; + var recipeDescriptor = (await JObject.LoadAsync(jsonReader)).ToObject(); - return recipeDescriptor; - } - } - } + recipeDescriptor.FileProvider = recipeFileProvider; + recipeDescriptor.BasePath = recipeBasePath; + recipeDescriptor.RecipeFileInfo = recipeFileInfo; + + return recipeDescriptor; } } } diff --git a/src/OrchardCore/OrchardCore.Recipes.Core/VariablesMethodProvider.cs b/src/OrchardCore/OrchardCore.Recipes.Core/VariablesMethodProvider.cs index e38669d3107..8c60f44bf82 100644 --- a/src/OrchardCore/OrchardCore.Recipes.Core/VariablesMethodProvider.cs +++ b/src/OrchardCore/OrchardCore.Recipes.Core/VariablesMethodProvider.cs @@ -32,7 +32,7 @@ public VariablesMethodProvider(JObject variables, List sc var value = variable.Value(); - // Replace variable value while the result returns another script + // Replace variable value while the result returns another script. while (value.StartsWith('[') && value.EndsWith(']')) { value = value.Trim('[', ']'); @@ -41,11 +41,11 @@ public VariablesMethodProvider(JObject variables, List sc } return value; - }) + }), }; } - public IScriptingManager ScriptingManager => ShellScope.Services.GetRequiredService(); + public static IScriptingManager ScriptingManager => ShellScope.Services.GetRequiredService(); public IEnumerable GetMethods() { diff --git a/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/LinkEntry.cs b/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/LinkEntry.cs index 9be10829d16..5a34e19651e 100644 --- a/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/LinkEntry.cs +++ b/src/OrchardCore/OrchardCore.ResourceManagement.Abstractions/LinkEntry.cs @@ -1,3 +1,4 @@ +using System; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; @@ -5,7 +6,7 @@ namespace OrchardCore.ResourceManagement { public class LinkEntry { - private readonly TagBuilder _builder = new TagBuilder("link"); + private readonly TagBuilder _builder = new("link"); public string Condition { get; set; } @@ -62,7 +63,7 @@ public string Href public IHtmlContent GetTag() { - if (!string.IsNullOrEmpty(Condition)) + if (!String.IsNullOrEmpty(Condition)) { var htmlBuilder = new HtmlContentBuilder(); htmlBuilder.AppendHtml("