From ac575662ac9a553bd07979f1515f274cb4d8d197 Mon Sep 17 00:00:00 2001 From: Emma L Garland Date: Tue, 24 Sep 2024 12:56:28 +0100 Subject: [PATCH] Resolved more warnings, and marked more warning types as errors (#16991) * Fix warnings SA1111, SA1028, SA1500, IDE1270 in Umbraco.Web.Website, and updated rules. * Remove warnings: IDE0270: Null check can be simplified * More SqlServer project warnings resolved * CS0105 namespace appeared already * Suppress warning until implementation: #pragma warning disable CS0162 // Unreachable code detected #pragma warning disable CS0618 // Type or member is obsolete CS0162 remove unreachable code SA1028 remove trailing whitespace SA1106 no empty statements CS1570 malformed XML CS1572 corrected xml parameter CS1573 param tag added IDE0007 var not explicit IDE0008 explicit not var IDE0057 simplify substring IDE0074 compound assignment CA1825 array.empty Down to 3479 warnings * - SA1116, SA117 params on same line - IDE0057 substring simplified Specific warnings for Umbraco.Tests.Benchmarks * Fixed IDE0074 compound assignment and added specific warnings for Umbraco.Tests.Common * Specific warnings for Umbraco.Tests.Integration and Umbraco.Tests.Common Fixed: - SA1111, SA1116, SA117 params and line formatting (not all as there are many) - SA1122 string.Empty - IDE0057 simplify substring - IDE0044,IDE0044 make field readonly - IDE1006 naming rule violation (add _) - SA1111 closing parenthesis on line of last parameter - SA1649 filename match type name - SA1312,SA1306 lowercase variable and field names * Fixed various warnings where they are more straight-forward, including: - SA1649 file name match type name - SA111 parenthesis on line of last parameter - IDE0028 simplify collection initializer - SA1306 lower-case letter field - IDE044 readonly field - SA1122 string.Empty - SA1116 params same line - IDE1006 upper casing - IDE0041 simplify null check Updated the following projects to only list their remaining specific warning codes: - Umbraco.Tests.UnitTests Typo in `Umbraco.Web.Website` project * Reverted test change * Now 1556 warnings. Fixed various warnings where they are more straight-forward, including: - SA1111/SA1116/SA1119 parenthesis - SA1117 params - SA1312 lowercase variable - SA1121 built-in type - SA1500/SA1513/SA1503 formatting braces - SA1400 declare access modifier - SA1122 string.Empty - SA1310 no underscore - IDE0049 name simplified - IDE0057 simplify substring - IDE0074 compound assignment - IDE0032 use auto-property - IDE0037 simplify member name - IDE0008 explicit type not var - IDE0016/IDE0270/IDE0041 simplify null checks - IDE0048/SA1407 clarity in arithmetic - IDE1006 correct param names - IDE0042 deconstruct variable - IDE0044 readonly - IDE0018 inline variable declarations - IDE0074/IDE0054 compound assignment - IDE1006 naming - CS1573 param XML - CS0168 unused variable Comment formatting in project files for consistency. Updated all projects to only list remaining specific warning codes as warnings instead of errors (errors is now default). * Type not var, and more warning exceptions * Tweaked merge issue, readded comment about rollback * Readded comment re rollback. * Readded comments * Comment tweak * Comment tweak --- .../Umbraco.Cms.Api.Delivery.csproj | 3 +- .../Security/BackOfficeController.cs | 6 +- .../Upgrade/UpgradeControllerBase.cs | 5 +- .../BackOfficeAuthPolicyBuilderExtensions.cs | 9 +- .../UmbracoBuilder.BackOffice.cs | 3 +- .../UmbracoBuilder.BackOfficeIdentity.cs | 9 +- .../OpenApi/NotificationHeaderFilter.cs | 9 +- .../BackOfficeAuthenticationBuilder.cs | 6 +- .../IBackOfficeExternalLoginService.cs | 3 +- .../Umbraco.Cms.Api.Management.csproj | 11 +- .../Umbraco.Cms.Persistence.EFCore.csproj | 6 +- .../Umbraco.Cms.Persistence.SqlServer.csproj | 13 +- .../Umbraco.Cms.StaticAssets.csproj | 2 +- .../Umbraco.Cms.Targets.csproj | 4 +- .../Extensions/StringExtensions.cs | 28 ++-- src/Umbraco.Core/HashGenerator.cs | 6 +- src/Umbraco.Core/IO/ViewHelper.cs | 4 +- .../ConfigurationEditorOfTConfiguration.cs | 3 +- src/Umbraco.Core/Semver/Semver.cs | 33 ++--- src/Umbraco.Core/Services/ContentService.cs | 43 +++--- .../Services/CultureImpactFactory.cs | 5 +- .../Services/IPackageDataInstallation.cs | 3 +- src/Umbraco.Core/Services/UserGroupService.cs | 19 +-- src/Umbraco.Core/Templates/HtmlUrlParser.cs | 6 +- src/Umbraco.Core/Umbraco.Core.csproj | 16 +- src/Umbraco.Core/Xml/DynamicContext.cs | 11 +- .../Jobs/ServerRegistration/TouchServerJob.cs | 3 +- .../Examine/DeferredActions.cs | 5 +- .../Examine/ExamineUmbracoIndexingHandler.cs | 59 +++++--- .../Install/FilePermissionHelper.cs | 4 +- .../Install/InstallHelper.cs | 3 +- .../Migrations/Install/DatabaseBuilder.cs | 28 ++-- .../Install/DatabaseSchemaCreator.cs | 6 +- .../Migrations/MigrationPlanExecutor.cs | 2 +- .../Upgrade/UmbracoPremigrationPlan.cs | 2 +- .../Packaging/PackageDataInstallation.cs | 140 ++++++++++-------- .../Persistence/NPocoSqlExtensions.cs | 31 ++-- .../Implement/ContentTypeRepositoryBase.cs | 36 ++--- .../Implement/DataTypeRepository.cs | 8 +- .../Implement/DocumentRepository.cs | 137 ++++++++++------- .../Implement/DynamicRootRepository.cs | 9 +- .../Implement/EntityContainerRepository.cs | 29 +--- .../Implement/EntityRepository.cs | 32 ++-- .../Repositories/Implement/MediaRepository.cs | 17 ++- .../Implement/MemberRepository.cs | 7 +- .../Repositories/Implement/TagRepository.cs | 6 +- .../Implement/TrackedReferencesRepository.cs | 135 ++++++++++------- .../Implement/UserGroupRepository.cs | 5 +- .../Repositories/Implement/UserRepository.cs | 81 +++++----- .../ImageCropperPropertyValueEditor.cs | 2 +- .../PublishedContentQuery.cs | 12 +- .../Runtime/FileSystemMainDomLock.cs | 3 +- .../Runtime/SqlMainDomLock.cs | 78 +++++----- .../Scoping/ScopeProvider.cs | 18 +-- .../BackOfficeClaimsPrincipalFactory.cs | 3 +- .../Security/MemberUserStore.cs | 3 +- .../Security/UmbracoUserManager.cs | 9 +- .../Umbraco.Infrastructure.csproj | 13 +- .../ContentCache.cs | 38 ++--- .../ContentStore.cs | 29 ++-- .../DataSource/BTree.ContentDataSerializer.cs | 13 +- .../BTree.ContentNodeKitSerializer.cs | 7 +- ...Tree.DictionaryOfPropertyDataSerializer.cs | 4 +- .../Umbraco.PublishedCache.NuCache.csproj | 6 +- .../Logging/RegisteredReloadableLogger.cs | 10 +- .../Middleware/UmbracoRequestMiddleware.cs | 4 + .../InMemoryAuto/ChecksumValidator.cs | 16 +- .../CollectibleRuntimeViewCompiler.cs | 59 +++----- .../UmbracoViewCompilerProvider.cs | 4 +- .../Profiler/WebProfiler.cs | 2 +- .../Security/MemberManager.cs | 17 +-- .../Umbraco.Web.Common.csproj | 10 +- .../Umbraco.Web.Website.csproj | 6 +- .../LoggerAllocationBenchmark.cs | 18 ++- .../StringReplaceFirstBenchmarks.cs | 5 +- .../Umbraco.Tests.Benchmarks.csproj | 5 +- tests/Umbraco.Tests.Common/TestHelperBase.cs | 5 +- .../Umbraco.Tests.Common.csproj | 5 +- .../ManagementApi/ManagementApiTest.cs | 3 +- .../Umbraco.Core/IO/ShadowFileSystemTests.cs | 8 +- .../Umbraco.Core/RuntimeStateTests.cs | 3 +- .../Services/ContentServiceTests.cs | 3 +- .../ContentTypeEditingServiceTests.Create.cs | 26 ++-- .../Services/ElementSwitchValidatorTests.cs | 47 +++++- .../Services/LogViewerServiceTests.cs | 16 +- .../MediaTypeEditingServiceTests.Create.cs | 8 +- ...Tests.cs => SuppressNotificationsTests.cs} | 4 +- .../Security/BackOfficeUserStoreTests.cs | 4 +- .../Services/CacheInstructionServiceTests.cs | 15 +- .../ContentServicePublishBranchTests.cs | 3 +- .../Services/ContentServiceTagsTests.cs | 3 +- .../Services/ContentTypeServiceTests.cs | 6 +- .../ContentTypeServiceVariantsTests.cs | 8 +- .../Services/DictionaryItemServiceTests.cs | 8 +- .../Services/EntityServiceTests.cs | 12 +- .../Services/EntityXmlSerializerTests.cs | 13 +- .../Services/LocalizationServiceTests.cs | 3 +- .../MediaTypeContainerServiceTests.cs | 8 +- .../Services/MediaTypeServiceTests.cs | 12 +- ...=> CustomDbContextUmbracoProviderTests.cs} | 2 +- .../Umbraco.Tests.Integration.csproj | 10 +- ...outeTests.cs => SurfaceControllerTests.cs} | 2 +- ... SqlAzureDatabaseProviderMetadataTests.cs} | 2 +- .../Umbraco.Core/DeliveryApi/CacheTests.cs | 15 +- .../DeliveryApi/DeliveryApiTests.cs | 9 +- .../ImageCropperValueConverterTests.cs | 3 +- .../DeliveryApi/MediaBuilderTests.cs | 5 +- .../Extensions/TypeExtensionsTests.cs | 26 ++-- .../Umbraco.Core/Models/Collections/Item.cs | 2 +- .../Umbraco.Core/Models/CultureImpactTests.cs | 10 +- .../Umbraco.Core/ReflectionUtilitiesTests.cs | 2 + .../StringExtensionsTests.cs | 2 +- .../BackOfficeClaimsPrincipalFactoryTests.cs | 6 +- ...heTests.cs => PublishContentCacheTests.cs} | 2 +- .../Umbraco.Tests.UnitTests.csproj | 13 +- .../UmbracoRouteValueTransformerTests.cs | 3 +- tools/Umbraco.JsonSchema/Program.cs | 2 +- .../Umbraco.JsonSchema.csproj | 5 +- 118 files changed, 990 insertions(+), 799 deletions(-) rename tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/{SupressNotificationsTests.cs => SuppressNotificationsTests.cs} (96%) rename tests/Umbraco.Tests.Integration/Umbraco.Persistence.EFCore/DbContext/{CustomDbContextTests.cs => CustomDbContextUmbracoProviderTests.cs} (98%) rename tests/Umbraco.Tests.Integration/Umbraco.Web.Website/Routing/{FrontEndRouteTests.cs => SurfaceControllerTests.cs} (99%) rename tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Persistence.SqlServer/{SqAzureDatabaseProviderMetadataTests.cs => SqlAzureDatabaseProviderMetadataTests.cs} (98%) rename tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/{PublishedContentCacheTests.cs => PublishContentCacheTests.cs} (98%) diff --git a/src/Umbraco.Cms.Api.Delivery/Umbraco.Cms.Api.Delivery.csproj b/src/Umbraco.Cms.Api.Delivery/Umbraco.Cms.Api.Delivery.csproj index 5e32b81eeb..4479bc92e2 100644 --- a/src/Umbraco.Cms.Api.Delivery/Umbraco.Cms.Api.Delivery.csproj +++ b/src/Umbraco.Cms.Api.Delivery/Umbraco.Cms.Api.Delivery.csproj @@ -4,7 +4,8 @@ Contains the presentation layer for the Umbraco CMS Delivery API. - + ASP0019 diff --git a/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs b/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs index 5a247a647c..03504a5099 100644 --- a/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs +++ b/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs @@ -189,8 +189,10 @@ public class BackOfficeController : SecurityControllerBase await _backOfficeSignInManager.SignOutAsync(); - _logger.LogInformation("User {UserName} from IP address {RemoteIpAddress} has logged out", - userName ?? "UNKNOWN", HttpContext.Connection.RemoteIpAddress); + _logger.LogInformation( + "User {UserName} from IP address {RemoteIpAddress} has logged out", + userName ?? "UNKNOWN", + HttpContext.Connection.RemoteIpAddress); // Returning a SignOutResult will ask OpenIddict to redirect the user agent // to the post_logout_redirect_uri specified by the client application. diff --git a/src/Umbraco.Cms.Api.Management/Controllers/Upgrade/UpgradeControllerBase.cs b/src/Umbraco.Cms.Api.Management/Controllers/Upgrade/UpgradeControllerBase.cs index bf720a4e44..ddbef42b3d 100644 --- a/src/Umbraco.Cms.Api.Management/Controllers/Upgrade/UpgradeControllerBase.cs +++ b/src/Umbraco.Cms.Api.Management/Controllers/Upgrade/UpgradeControllerBase.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Umbraco.Cms.Api.Management.Filters; @@ -21,7 +21,8 @@ public abstract class UpgradeControllerBase : ManagementApiControllerBase ? Ok() : OperationStatusResult(status, problemDetailsBuilder => status switch { - UpgradeOperationStatus.UpgradeFailed => StatusCode(StatusCodes.Status500InternalServerError, + UpgradeOperationStatus.UpgradeFailed => StatusCode( + StatusCodes.Status500InternalServerError, problemDetailsBuilder .WithTitle("Upgrade failed") .WithDetail(result?.ErrorMessage ?? "An unknown error occurred.") diff --git a/src/Umbraco.Cms.Api.Management/DependencyInjection/BackOfficeAuthPolicyBuilderExtensions.cs b/src/Umbraco.Cms.Api.Management/DependencyInjection/BackOfficeAuthPolicyBuilderExtensions.cs index 04a9150ed6..e56dadb400 100644 --- a/src/Umbraco.Cms.Api.Management/DependencyInjection/BackOfficeAuthPolicyBuilderExtensions.cs +++ b/src/Umbraco.Cms.Api.Management/DependencyInjection/BackOfficeAuthPolicyBuilderExtensions.cs @@ -57,13 +57,16 @@ internal static class BackOfficeAuthPolicyBuilderExtensions AddAllowedApplicationsPolicy(AuthorizationPolicies.SectionAccessContent, Constants.Applications.Content); AddAllowedApplicationsPolicy(AuthorizationPolicies.SectionAccessContentOrMedia, Constants.Applications.Content, Constants.Applications.Media); - AddAllowedApplicationsPolicy(AuthorizationPolicies.SectionAccessForContentTree, + AddAllowedApplicationsPolicy( + AuthorizationPolicies.SectionAccessForContentTree, Constants.Applications.Content, Constants.Applications.Media, Constants.Applications.Users, Constants.Applications.Settings, Constants.Applications.Packages, Constants.Applications.Members); - AddAllowedApplicationsPolicy(AuthorizationPolicies.SectionAccessForMediaTree, + AddAllowedApplicationsPolicy( + AuthorizationPolicies.SectionAccessForMediaTree, Constants.Applications.Content, Constants.Applications.Media, Constants.Applications.Users, Constants.Applications.Settings, Constants.Applications.Packages, Constants.Applications.Members); - AddAllowedApplicationsPolicy(AuthorizationPolicies.SectionAccessForMemberTree, + AddAllowedApplicationsPolicy( + AuthorizationPolicies.SectionAccessForMemberTree, Constants.Applications.Content, Constants.Applications.Media, Constants.Applications.Members); AddAllowedApplicationsPolicy(AuthorizationPolicies.SectionAccessMedia, Constants.Applications.Media); AddAllowedApplicationsPolicy(AuthorizationPolicies.SectionAccessMembers, Constants.Applications.Members); diff --git a/src/Umbraco.Cms.Api.Management/DependencyInjection/UmbracoBuilder.BackOffice.cs b/src/Umbraco.Cms.Api.Management/DependencyInjection/UmbracoBuilder.BackOffice.cs index 907e3057af..32ae43b1d1 100644 --- a/src/Umbraco.Cms.Api.Management/DependencyInjection/UmbracoBuilder.BackOffice.cs +++ b/src/Umbraco.Cms.Api.Management/DependencyInjection/UmbracoBuilder.BackOffice.cs @@ -52,8 +52,7 @@ public static partial class UmbracoBuilderExtensions hostingEnvironment, factory.GetRequiredService>(), hostingEnvironment.MapPathContentRoot(path), - hostingEnvironment.ToAbsolute(path) - ); + hostingEnvironment.ToAbsolute(path)); }); return builder; diff --git a/src/Umbraco.Cms.Api.Management/DependencyInjection/UmbracoBuilder.BackOfficeIdentity.cs b/src/Umbraco.Cms.Api.Management/DependencyInjection/UmbracoBuilder.BackOfficeIdentity.cs index a445268db7..baf8c2ebcb 100644 --- a/src/Umbraco.Cms.Api.Management/DependencyInjection/UmbracoBuilder.BackOfficeIdentity.cs +++ b/src/Umbraco.Cms.Api.Management/DependencyInjection/UmbracoBuilder.BackOfficeIdentity.cs @@ -52,8 +52,7 @@ public static partial class UmbracoBuilderExtensions factory.GetRequiredService(), factory.GetRequiredService(), factory.GetRequiredService(), - factory.GetRequiredService>() - )) + factory.GetRequiredService>())) .AddUserManager() .AddSignInManager() .AddClaimsPrincipalFactory() @@ -94,14 +93,16 @@ public static partial class UmbracoBuilderExtensions /// /// Adds support for external login providers in Umbraco /// - public static IUmbracoBuilder AddBackOfficeExternalLogins(this IUmbracoBuilder umbracoBuilder, + public static IUmbracoBuilder AddBackOfficeExternalLogins( + this IUmbracoBuilder umbracoBuilder, Action builder) { builder(new BackOfficeExternalLoginsBuilder(umbracoBuilder.Services)); return umbracoBuilder; } - public static BackOfficeIdentityBuilder AddTwoFactorProvider(this BackOfficeIdentityBuilder identityBuilder, + public static BackOfficeIdentityBuilder AddTwoFactorProvider( + this BackOfficeIdentityBuilder identityBuilder, string providerName) where T : class, ITwoFactorProvider { identityBuilder.Services.AddSingleton(); diff --git a/src/Umbraco.Cms.Api.Management/OpenApi/NotificationHeaderFilter.cs b/src/Umbraco.Cms.Api.Management/OpenApi/NotificationHeaderFilter.cs index 80ed73317a..bee1910f2c 100644 --- a/src/Umbraco.Cms.Api.Management/OpenApi/NotificationHeaderFilter.cs +++ b/src/Umbraco.Cms.Api.Management/OpenApi/NotificationHeaderFilter.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using Umbraco.Cms.Api.Management.ViewModels; @@ -32,7 +32,12 @@ internal class NotificationHeaderFilter : IOperationFilter response.Headers.TryAdd(Constants.Headers.Notifications, new OpenApiHeader { Description = "The list of notifications produced during the request.", - Schema = new OpenApiSchema { Type = "array" , Nullable = true, Items = new OpenApiSchema(){ + Schema = new OpenApiSchema + { + Type = "array", + Nullable = true, + Items = new OpenApiSchema() + { Reference = new OpenApiReference() { Type = ReferenceType.Schema, diff --git a/src/Umbraco.Cms.Api.Management/Security/BackOfficeAuthenticationBuilder.cs b/src/Umbraco.Cms.Api.Management/Security/BackOfficeAuthenticationBuilder.cs index 98489a849c..0c00fa7e51 100644 --- a/src/Umbraco.Cms.Api.Management/Security/BackOfficeAuthenticationBuilder.cs +++ b/src/Umbraco.Cms.Api.Management/Security/BackOfficeAuthenticationBuilder.cs @@ -32,8 +32,10 @@ public class BackOfficeAuthenticationBuilder : AuthenticationBuilder /// /// /// - public override AuthenticationBuilder AddRemoteScheme(string authenticationScheme, - string? displayName, Action? configureOptions) + public override AuthenticationBuilder AddRemoteScheme( + string authenticationScheme, + string? displayName, + Action? configureOptions) { // Validate that the prefix is set if (!authenticationScheme.StartsWith(Constants.Security.BackOfficeExternalAuthenticationTypePrefix)) diff --git a/src/Umbraco.Cms.Api.Management/Services/IBackOfficeExternalLoginService.cs b/src/Umbraco.Cms.Api.Management/Services/IBackOfficeExternalLoginService.cs index 7b14656bf2..648e2fc39a 100644 --- a/src/Umbraco.Cms.Api.Management/Services/IBackOfficeExternalLoginService.cs +++ b/src/Umbraco.Cms.Api.Management/Services/IBackOfficeExternalLoginService.cs @@ -15,7 +15,8 @@ public interface IBackOfficeExternalLoginService Task, ExternalLoginOperationStatus>> HandleLoginCallbackAsync(HttpContext httpContext); - Task> GenerateLoginProviderSecretAsync(ClaimsPrincipal claimsPrincipal, + Task> GenerateLoginProviderSecretAsync( + ClaimsPrincipal claimsPrincipal, string loginProvider); Task> ClaimsPrincipleFromLoginProviderLinkKeyAsync( diff --git a/src/Umbraco.Cms.Api.Management/Umbraco.Cms.Api.Management.csproj b/src/Umbraco.Cms.Api.Management/Umbraco.Cms.Api.Management.csproj index 88ee0cef62..e2060938c6 100644 --- a/src/Umbraco.Cms.Api.Management/Umbraco.Cms.Api.Management.csproj +++ b/src/Umbraco.Cms.Api.Management/Umbraco.Cms.Api.Management.csproj @@ -8,8 +8,15 @@ Umbraco.Cms.Api.Management - - false + + + SA1117,SA1401,SA1134,CS0108,CS0618,CS1998,CS8524,CS9042,IDE0060,SA1649,CS0419, + CS1573,CS1574 + diff --git a/src/Umbraco.Cms.Persistence.EFCore/Umbraco.Cms.Persistence.EFCore.csproj b/src/Umbraco.Cms.Persistence.EFCore/Umbraco.Cms.Persistence.EFCore.csproj index d5fc7229b0..4b01e4154a 100644 --- a/src/Umbraco.Cms.Persistence.EFCore/Umbraco.Cms.Persistence.EFCore.csproj +++ b/src/Umbraco.Cms.Persistence.EFCore/Umbraco.Cms.Persistence.EFCore.csproj @@ -4,11 +4,11 @@ Adds support for Entity Framework Core to Umbraco CMS. - + IDE0270,CS0108,CS1998 - + diff --git a/src/Umbraco.Cms.Persistence.SqlServer/Umbraco.Cms.Persistence.SqlServer.csproj b/src/Umbraco.Cms.Persistence.SqlServer/Umbraco.Cms.Persistence.SqlServer.csproj index d62aea6ceb..084c1b3b95 100644 --- a/src/Umbraco.Cms.Persistence.SqlServer/Umbraco.Cms.Persistence.SqlServer.csproj +++ b/src/Umbraco.Cms.Persistence.SqlServer/Umbraco.Cms.Persistence.SqlServer.csproj @@ -4,10 +4,15 @@ Adds support for SQL Server to Umbraco CMS. - - SA1405,SA1121,SA1117,SA1116,IDE1006,CS0618,IDE0270,IDE0057,IDE0054,CSO618,IDE0048,CS1574 + + + SA1405,SA1121,SA1117,SA1116,IDE1006,CS0618,IDE0270,IDE0057,IDE0054,CSO618,IDE0048, + CS1574 + diff --git a/src/Umbraco.Cms.StaticAssets/Umbraco.Cms.StaticAssets.csproj b/src/Umbraco.Cms.StaticAssets/Umbraco.Cms.StaticAssets.csproj index 80b7bc0211..b567868e11 100644 --- a/src/Umbraco.Cms.StaticAssets/Umbraco.Cms.StaticAssets.csproj +++ b/src/Umbraco.Cms.StaticAssets/Umbraco.Cms.StaticAssets.csproj @@ -7,7 +7,7 @@ - + NU5123 diff --git a/src/Umbraco.Cms.Targets/Umbraco.Cms.Targets.csproj b/src/Umbraco.Cms.Targets/Umbraco.Cms.Targets.csproj index e9e0df050d..ac3b5b2c4e 100644 --- a/src/Umbraco.Cms.Targets/Umbraco.Cms.Targets.csproj +++ b/src/Umbraco.Cms.Targets/Umbraco.Cms.Targets.csproj @@ -6,8 +6,8 @@ false - + IDE0270,CS0108,CS1998 diff --git a/src/Umbraco.Core/Extensions/StringExtensions.cs b/src/Umbraco.Core/Extensions/StringExtensions.cs index 732e25ecc2..7c144138b0 100644 --- a/src/Umbraco.Core/Extensions/StringExtensions.cs +++ b/src/Umbraco.Core/Extensions/StringExtensions.cs @@ -83,11 +83,11 @@ public static class StringExtensions return fileName; } - var spanFileName = fileName.AsSpan(); + ReadOnlySpan spanFileName = fileName.AsSpan(); var lastIndex = spanFileName.LastIndexOf('.'); if (lastIndex > 0) { - var ext = spanFileName[lastIndex..]; + ReadOnlySpan ext = spanFileName[lastIndex..]; // file extensions cannot contain whitespace if (ext.Contains(' ')) @@ -377,7 +377,7 @@ public static class StringExtensions while (value.StartsWith(forRemoving, StringComparison.InvariantCultureIgnoreCase)) { - value = value.Substring(forRemoving.Length); + value = value[forRemoving.Length..]; } return value; @@ -497,7 +497,7 @@ public static class StringExtensions var convertToHex = input.ConvertToHex(); var hexLength = convertToHex.Length < 32 ? convertToHex.Length : 32; - var hex = convertToHex.Substring(0, hexLength).PadLeft(32, '0'); + var hex = convertToHex[..hexLength].PadLeft(32, '0'); Guid output = Guid.Empty; return Guid.TryParse(hex, out output) ? output : Guid.Empty; } @@ -528,8 +528,8 @@ public static class StringExtensions var strValue = string.Empty; while (hexValue.Length > 0) { - strValue += Convert.ToChar(Convert.ToUInt32(hexValue.Substring(0, 2), 16)).ToString(); - hexValue = hexValue.Substring(2, hexValue.Length - 2); + strValue += Convert.ToChar(Convert.ToUInt32(hexValue[..2], 16)).ToString(); + hexValue = hexValue[2..]; } return strValue; @@ -871,7 +871,7 @@ public static class StringExtensions return truncatedString; } - truncatedString = text.Substring(0, strLength); + truncatedString = text[..strLength]; truncatedString = truncatedString.TrimEnd(); truncatedString += suffix; @@ -914,7 +914,7 @@ public static class StringExtensions public static string ToFirstUpper(this string input) => string.IsNullOrWhiteSpace(input) ? input - : input.Substring(0, 1).ToUpper() + input.Substring(1); + : input[..1].ToUpper() + input[1..]; /// /// Returns a copy of the string with the first character converted to lowercase. @@ -924,7 +924,7 @@ public static class StringExtensions public static string ToFirstLower(this string input) => string.IsNullOrWhiteSpace(input) ? input - : input.Substring(0, 1).ToLower() + input.Substring(1); + : input[..1].ToLower() + input[1..]; /// /// Returns a copy of the string with the first character converted to uppercase using the casing rules of the @@ -936,7 +936,7 @@ public static class StringExtensions public static string ToFirstUpper(this string input, CultureInfo culture) => string.IsNullOrWhiteSpace(input) ? input - : input.Substring(0, 1).ToUpper(culture) + input.Substring(1); + : input[..1].ToUpper(culture) + input[1..]; /// /// Returns a copy of the string with the first character converted to lowercase using the casing rules of the @@ -948,7 +948,7 @@ public static class StringExtensions public static string ToFirstLower(this string input, CultureInfo culture) => string.IsNullOrWhiteSpace(input) ? input - : input.Substring(0, 1).ToLower(culture) + input.Substring(1); + : input[..1].ToLower(culture) + input[1..]; /// /// Returns a copy of the string with the first character converted to uppercase using the casing rules of the @@ -959,7 +959,7 @@ public static class StringExtensions public static string ToFirstUpperInvariant(this string input) => string.IsNullOrWhiteSpace(input) ? input - : input.Substring(0, 1).ToUpperInvariant() + input.Substring(1); + : input[..1].ToUpperInvariant() + input[1..]; /// /// Returns a copy of the string with the first character converted to lowercase using the casing rules of the @@ -970,7 +970,7 @@ public static class StringExtensions public static string ToFirstLowerInvariant(this string input) => string.IsNullOrWhiteSpace(input) ? input - : input.Substring(0, 1).ToLowerInvariant() + input.Substring(1); + : input[..1].ToLowerInvariant() + input[1..]; /// /// Returns a new string in which all occurrences of specified strings are replaced by other specified strings. @@ -1355,7 +1355,7 @@ public static class StringExtensions return a; } - return char.ToLowerInvariant(a[0]) + a.Substring(1); + return char.ToLowerInvariant(a[0]) + a[1..]; } /// diff --git a/src/Umbraco.Core/HashGenerator.cs b/src/Umbraco.Core/HashGenerator.cs index cad3d4b6b8..b2038058b2 100644 --- a/src/Umbraco.Core/HashGenerator.cs +++ b/src/Umbraco.Core/HashGenerator.cs @@ -99,11 +99,7 @@ public class HashGenerator : DisposableObjectSlim var hashType = CryptoConfig.AllowOnlyFipsAlgorithms ? "SHA1" : "MD5"; // create an instance of the correct hashing provider based on the type passed in - var hasher = HashAlgorithm.Create(hashType); - if (hasher == null) - { - throw new InvalidOperationException("No hashing type found by name " + hashType); - } + HashAlgorithm hasher = HashAlgorithm.Create(hashType) ?? throw new InvalidOperationException("No hashing type found by name " + hashType); using (hasher) { diff --git a/src/Umbraco.Core/IO/ViewHelper.cs b/src/Umbraco.Core/IO/ViewHelper.cs index 0d4fcce3dc..a02beaac09 100644 --- a/src/Umbraco.Core/IO/ViewHelper.cs +++ b/src/Umbraco.Core/IO/ViewHelper.cs @@ -15,7 +15,9 @@ public class ViewHelper : IViewHelper { _viewFileSystem = fileSystems.MvcViewsFileSystem ?? throw new ArgumentNullException(nameof(fileSystems)); _defaultViewContentProvider = defaultViewContentProvider ?? throw new ArgumentNullException(nameof(defaultViewContentProvider)); - }[Obsolete("Inject IDefaultViewContentProvider instead")] + } + + [Obsolete("Inject IDefaultViewContentProvider instead")] public static string GetDefaultFileContent(string? layoutPageAlias = null, string? modelClassName = null, string? modelNamespace = null, string? modelNamespaceAlias = null) { IDefaultViewContentProvider viewContentProvider = diff --git a/src/Umbraco.Core/PropertyEditors/ConfigurationEditorOfTConfiguration.cs b/src/Umbraco.Core/PropertyEditors/ConfigurationEditorOfTConfiguration.cs index fa135e2ead..041ad59514 100644 --- a/src/Umbraco.Core/PropertyEditors/ConfigurationEditorOfTConfiguration.cs +++ b/src/Umbraco.Core/PropertyEditors/ConfigurationEditorOfTConfiguration.cs @@ -46,7 +46,8 @@ public abstract class ConfigurationEditor : ConfigurationEditor } } - protected TConfiguration? AsConfigurationObject(IDictionary configuration, + protected TConfiguration? AsConfigurationObject( + IDictionary configuration, IConfigurationEditorJsonSerializer configurationEditorJsonSerializer) => ToConfigurationObject(configuration, configurationEditorJsonSerializer) is TConfiguration configurationObject ? configurationObject diff --git a/src/Umbraco.Core/Semver/Semver.cs b/src/Umbraco.Core/Semver/Semver.cs index a8261f3054..2b24ba5952 100644 --- a/src/Umbraco.Core/Semver/Semver.cs +++ b/src/Umbraco.Core/Semver/Semver.cs @@ -40,7 +40,7 @@ namespace Umbraco.Cms.Core.Semver public sealed class SemVersion : IComparable, IComparable, ISerializable #endif { - private static Regex parseEx = + private static readonly Regex _parseEx = new( @"^(?\d+)" + @"(\.(?\d+))?" + @@ -137,7 +137,7 @@ namespace Umbraco.Cms.Core.Semver /// When a invalid version string is passed. public static SemVersion Parse(string version, bool strict = false) { - Match match = parseEx.Match(version); + Match match = _parseEx.Match(version); if (!match.Success) { throw new ArgumentException("Invalid version.", "version"); @@ -218,9 +218,9 @@ namespace Umbraco.Cms.Core.Semver /// If versionA is equal to versionB true, else false. public static bool Equals(SemVersion versionA, SemVersion versionB) { - if (ReferenceEquals(versionA, null)) + if (versionA is null) { - return ReferenceEquals(versionB, null); + return versionB is null; } return versionA.Equals(versionB); @@ -237,9 +237,9 @@ namespace Umbraco.Cms.Core.Semver /// public static int Compare(SemVersion versionA, SemVersion versionB) { - if (ReferenceEquals(versionA, null)) + if (versionA is null) { - return ReferenceEquals(versionB, null) ? 0 : -1; + return versionB is null ? 0 : -1; } return versionA.CompareTo(versionB); @@ -303,10 +303,10 @@ namespace Umbraco.Cms.Core.Semver public string Build { get; private set; } /// - /// Returns a that represents this instance. + /// Returns a that represents this instance. /// /// - /// A that represents this instance. + /// A that represents this instance. /// public override string ToString() { @@ -354,7 +354,7 @@ namespace Umbraco.Cms.Core.Semver /// public int CompareTo(SemVersion? other) { - if (ReferenceEquals(other, null)) + if (other is null) { return 1; } @@ -389,7 +389,7 @@ namespace Umbraco.Cms.Core.Semver /// public int CompareByPrecedence(SemVersion other) { - if (ReferenceEquals(other, null)) + if (other is null) { return 1; } @@ -443,9 +443,8 @@ namespace Umbraco.Cms.Core.Semver { var ac = aComps[i]; var bc = bComps[i]; - int anum, bnum; - var isanum = int.TryParse(ac, out anum); - var isbnum = int.TryParse(bc, out bnum); + var isanum = int.TryParse(ac, out int anum); + var isbnum = int.TryParse(bc, out int bnum); int r; if (isanum && isbnum) { @@ -479,15 +478,15 @@ namespace Umbraco.Cms.Core.Semver } /// - /// Determines whether the specified is equal to this instance. + /// Determines whether the specified is equal to this instance. /// - /// The to compare with this instance. + /// The to compare with this instance. /// - /// true if the specified is equal to this instance; otherwise, false. + /// true if the specified is equal to this instance; otherwise, false. /// public override bool Equals(object? obj) { - if (ReferenceEquals(obj, null)) + if (obj is null) { return false; } diff --git a/src/Umbraco.Core/Services/ContentService.cs b/src/Umbraco.Core/Services/ContentService.cs index cd005b576c..d903d46501 100644 --- a/src/Umbraco.Core/Services/ContentService.cs +++ b/src/Umbraco.Core/Services/ContentService.cs @@ -354,11 +354,9 @@ public class ContentService : RepositoryService, IContentService throw new ArgumentNullException(nameof(parent)); } - IContentType contentType = GetContentType(contentTypeAlias); - if (contentType == null) - { - throw new ArgumentException("No content type with that alias.", nameof(contentTypeAlias)); // causes rollback - } + IContentType contentType = GetContentType(contentTypeAlias) + // causes rollback + ?? throw new ArgumentException("No content type with that alias.", nameof(contentTypeAlias)); var content = new Content(name, parent, contentType, userId); @@ -382,11 +380,11 @@ public class ContentService : RepositoryService, IContentService // locking the content tree secures content types too scope.WriteLock(Constants.Locks.ContentTree); - IContentType contentType = GetContentType(contentTypeAlias); // + locks - if (contentType == null) - { - throw new ArgumentException("No content type with that alias.", nameof(contentTypeAlias)); // causes rollback - } + IContentType contentType = GetContentType(contentTypeAlias) + // + locks + ?? + // causes rollback + throw new ArgumentException("No content type with that alias.", nameof(contentTypeAlias)); IContent? parent = parentId > 0 ? GetById(parentId) : null; // + locks if (parentId > 0 && parent == null) @@ -428,11 +426,11 @@ public class ContentService : RepositoryService, IContentService // locking the content tree secures content types too scope.WriteLock(Constants.Locks.ContentTree); - IContentType contentType = GetContentType(contentTypeAlias); // + locks - if (contentType == null) - { - throw new ArgumentException("No content type with that alias.", nameof(contentTypeAlias)); // causes rollback - } + IContentType contentType = GetContentType(contentTypeAlias) + // + locks + ?? + // causes rollback + throw new ArgumentException("No content type with that alias.", nameof(contentTypeAlias)); var content = new Content(name, parent, contentType, userId); @@ -1997,7 +1995,7 @@ public class ContentService : RepositoryService, IContentService { // note: EditedValue and PublishedValue are objects here, so it is important to .Equals() // and not to == them, else we would be comparing references, and that is a bad thing - cultures = cultures ?? Array.Empty(); + cultures ??= Array.Empty(); if (content.ContentType.VariesByCulture() is false && cultures.Length == 0) { @@ -3036,6 +3034,7 @@ public class ContentService : RepositoryService, IContentService /// /// /// + /// /// private PublishResult StrategyCanPublish( ICoreScope scope, @@ -3466,13 +3465,11 @@ public class ContentService : RepositoryService, IContentService scope.ReadLock(Constants.Locks.ContentTypes); IQuery query = Query().Where(x => x.Alias == contentTypeAlias); - IContentType? contentType = _contentTypeRepository.Get(query).FirstOrDefault(); - - if (contentType == null) - { - throw new Exception( - $"No ContentType matching the passed in Alias: '{contentTypeAlias}' was found"); // causes rollback - } + IContentType? contentType = _contentTypeRepository.Get(query).FirstOrDefault() + ?? + // causes rollback + throw new Exception($"No ContentType matching the passed in Alias: '{contentTypeAlias}'" + + $" was found"); return contentType; } diff --git a/src/Umbraco.Core/Services/CultureImpactFactory.cs b/src/Umbraco.Core/Services/CultureImpactFactory.cs index cda33889c9..3dd9b6b1f0 100644 --- a/src/Umbraco.Core/Services/CultureImpactFactory.cs +++ b/src/Umbraco.Core/Services/CultureImpactFactory.cs @@ -1,4 +1,4 @@ -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.DependencyInjection; @@ -135,7 +135,10 @@ public class CultureImpactFactory : ICultureImpactFactory if (isDefault) { if (throwOnFail) + { throw new InvalidOperationException("The 'all' culture can not be the default culture."); + } + return false; } diff --git a/src/Umbraco.Core/Services/IPackageDataInstallation.cs b/src/Umbraco.Core/Services/IPackageDataInstallation.cs index 27eee95f32..5d9eaa22d2 100644 --- a/src/Umbraco.Core/Services/IPackageDataInstallation.cs +++ b/src/Umbraco.Core/Services/IPackageDataInstallation.cs @@ -51,7 +51,8 @@ public interface IPackageDataInstallation /// Xml to import /// /// An enumerable list of dictionary items - IReadOnlyList ImportDictionaryItems(IEnumerable dictionaryItemElementList, + IReadOnlyList ImportDictionaryItems( + IEnumerable dictionaryItemElementList, int userId); IEnumerable ImportDictionaryItem(XElement dictionaryItemElement, int userId, Guid? parentId); diff --git a/src/Umbraco.Core/Services/UserGroupService.cs b/src/Umbraco.Core/Services/UserGroupService.cs index fbe6a52386..959d24a51c 100644 --- a/src/Umbraco.Core/Services/UserGroupService.cs +++ b/src/Umbraco.Core/Services/UserGroupService.cs @@ -1,4 +1,4 @@ -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Membership; @@ -422,13 +422,10 @@ internal sealed class UserGroupService : RepositoryService, IUserGroupService return Attempt.Fail(resolveAttempt.Status); } - ResolvedUserToUserGroupManipulationModel? resolvedModel = resolveAttempt.Result; + ResolvedUserToUserGroupManipulationModel? resolvedModel = resolveAttempt.Result ?? - // This should never happen, but we need to check it to avoid null reference exceptions - if (resolvedModel is null) - { + // This should never happen, but we need to check it to avoid null reference exceptions throw new InvalidOperationException("The resolved model should not be null."); - } IReadOnlyUserGroup readOnlyGroup = resolvedModel.UserGroup.ToReadOnlyGroup(); @@ -455,13 +452,10 @@ internal sealed class UserGroupService : RepositoryService, IUserGroupService return Attempt.Fail(resolveAttempt.Status); } - ResolvedUserToUserGroupManipulationModel? resolvedModel = resolveAttempt.Result; + ResolvedUserToUserGroupManipulationModel? resolvedModel = resolveAttempt.Result // This should never happen, but we need to check it to avoid null reference exceptions - if (resolvedModel is null) - { - throw new InvalidOperationException("The resolved model should not be null."); - } + ?? throw new InvalidOperationException("The resolved model should not be null."); foreach (IUser user in resolvedModel.Users) { @@ -642,7 +636,8 @@ internal sealed class UserGroupService : RepositoryService, IUserGroupService /// /// This is to ensure that the user can access the group they themselves created at a later point and modify it. /// - private IEnumerable EnsureNonAdminUserIsInSavedUserGroup(IUser performingUser, + private IEnumerable EnsureNonAdminUserIsInSavedUserGroup( + IUser performingUser, IEnumerable groupMembersUserKeys) { var userKeys = groupMembersUserKeys.ToList(); diff --git a/src/Umbraco.Core/Templates/HtmlUrlParser.cs b/src/Umbraco.Core/Templates/HtmlUrlParser.cs index 16d27eb205..80dc47a27c 100644 --- a/src/Umbraco.Core/Templates/HtmlUrlParser.cs +++ b/src/Umbraco.Core/Templates/HtmlUrlParser.cs @@ -9,7 +9,7 @@ namespace Umbraco.Cms.Core.Templates; public sealed class HtmlUrlParser { - private static readonly Regex ResolveUrlPattern = new( + private static readonly Regex _resolveUrlPattern = new( "(=[\"\']?)(\\W?\\~(?:.(?![\"\']?\\s+(?:\\S+)=|[>\"\']))+.)[\"\']?", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); @@ -46,13 +46,13 @@ public sealed class HtmlUrlParser return text; } - using (DisposableTimer? timer = !(_profilingLogger.IsEnabled(Core.Logging.LogLevel.Debug)) ? null : _profilingLogger.DebugDuration( + using (DisposableTimer? timer = !_profilingLogger.IsEnabled(Core.Logging.LogLevel.Debug) ? null : _profilingLogger.DebugDuration( typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete")) { // find all relative URLs (ie. URLs that contain ~) - MatchCollection tags = ResolveUrlPattern.Matches(text); + MatchCollection tags = _resolveUrlPattern.Matches(text); if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { _logger.LogDebug("After regex: {Duration} matched: {TagsCount}", timer?.Stopwatch.ElapsedMilliseconds, tags.Count); diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index e4b3a7cd04..a05649bb3f 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -6,8 +6,20 @@ Umbraco.Cms.Core - - false + + + SA1117,SA1401,SA1134,SA1649,CS0618,CS0067,SA1405,SA1600,CS0168,CS0169,CS0183,SYSLIB0045,SYSLIB0051, + SYSLIB0044,SYSLIB0023,SYSLIB0003,SA1111,SA1649,CA2017,CS0108,CS0649,CS0672,CS1574,CS1998,CS8073,IDE0060, + IDE1006,SA1306,CS1723,CS0419 + diff --git a/src/Umbraco.Core/Xml/DynamicContext.cs b/src/Umbraco.Core/Xml/DynamicContext.cs index 7af4c5d233..3cd638dd1c 100644 --- a/src/Umbraco.Core/Xml/DynamicContext.cs +++ b/src/Umbraco.Core/Xml/DynamicContext.cs @@ -1,4 +1,4 @@ -using System.Xml; +using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; @@ -20,7 +20,7 @@ namespace Umbraco.Cms.Core.Xml { #region Private vars - readonly IDictionary _variables = + private readonly IDictionary _variables = new Dictionary(); #endregion Private @@ -96,7 +96,7 @@ namespace Umbraco.Cms.Core.Xml /// Implementation equal to . /// public override int CompareDocument(string baseUri, string nextbaseUri) => - String.Compare(baseUri, nextbaseUri, false, System.Globalization.CultureInfo.InvariantCulture); + string.Compare(baseUri, nextbaseUri, false, System.Globalization.CultureInfo.InvariantCulture); /// /// Same as . @@ -211,12 +211,11 @@ namespace Umbraco.Cms.Core.Xml /// internal class DynamicVariable : IXsltContextVariable { - private readonly string _name; private readonly object _value; #region Public Members - public string Name { get { return _name; } } + public string Name { get; } /// /// Initializes a new instance of the class. @@ -226,7 +225,7 @@ namespace Umbraco.Cms.Core.Xml public DynamicVariable(string name, object value) { - _name = name; + Name = name; _value = value; if (value is string) diff --git a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/TouchServerJob.cs b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/TouchServerJob.cs index 8258da1a35..fb5b23e9db 100644 --- a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/TouchServerJob.cs +++ b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/TouchServerJob.cs @@ -24,7 +24,8 @@ public class TouchServerJob : IRecurringBackgroundJob public ServerRole[] ServerRoles { get => Enum.GetValues(); } private event EventHandler? _periodChanged; - public event EventHandler PeriodChanged { + public event EventHandler PeriodChanged + { add { _periodChanged += value; } remove { _periodChanged -= value; } } diff --git a/src/Umbraco.Infrastructure/Examine/DeferredActions.cs b/src/Umbraco.Infrastructure/Examine/DeferredActions.cs index 6ef8d7d34d..495c12e7a7 100644 --- a/src/Umbraco.Infrastructure/Examine/DeferredActions.cs +++ b/src/Umbraco.Infrastructure/Examine/DeferredActions.cs @@ -1,4 +1,4 @@ -using Umbraco.Cms.Core.Scoping; +using Umbraco.Cms.Core.Scoping; namespace Umbraco.Cms.Infrastructure.Examine; @@ -15,7 +15,8 @@ internal class DeferredActions { IScopeContext? scopeContext = scopeProvider.Context; - return scopeContext?.Enlist("examineEvents", + return scopeContext?.Enlist( + "examineEvents", () => new DeferredActions(), // creator (completed, actions) => // action { diff --git a/src/Umbraco.Infrastructure/Examine/ExamineUmbracoIndexingHandler.cs b/src/Umbraco.Infrastructure/Examine/ExamineUmbracoIndexingHandler.cs index c77606e97a..4efdf9ff12 100644 --- a/src/Umbraco.Infrastructure/Examine/ExamineUmbracoIndexingHandler.cs +++ b/src/Umbraco.Infrastructure/Examine/ExamineUmbracoIndexingHandler.cs @@ -190,7 +190,8 @@ internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler var registeredIndexers = _examineManager.Indexes.OfType().Count(x => x.EnableDefaultEventHandler); - _logger.LogInformation("Adding examine event handlers for {RegisteredIndexers} index providers.", + _logger.LogInformation( + "Adding examine event handlers for {RegisteredIndexers} index providers.", registeredIndexers); // don't bind event handlers if we're not suppose to listen @@ -214,8 +215,11 @@ internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler private readonly ExamineUmbracoIndexingHandler _examineUmbracoIndexingHandler; private readonly bool _isPublished; - public DeferredReIndexForContent(IBackgroundTaskQueue backgroundTaskQueue, - ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IContent content, bool isPublished) + public DeferredReIndexForContent( + IBackgroundTaskQueue backgroundTaskQueue, + ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, + IContent content, + bool isPublished) { _backgroundTaskQueue = backgroundTaskQueue; _examineUmbracoIndexingHandler = examineUmbracoIndexingHandler; @@ -226,8 +230,11 @@ internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler public void Execute() => Execute(_backgroundTaskQueue, _examineUmbracoIndexingHandler, _content, _isPublished); - public static void Execute(IBackgroundTaskQueue backgroundTaskQueue, - ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IContent content, bool isPublished) + public static void Execute( + IBackgroundTaskQueue backgroundTaskQueue, + ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, + IContent content, + bool isPublished) => backgroundTaskQueue.QueueBackgroundWorkItem(cancellationToken => { using ICoreScope scope = @@ -271,8 +278,11 @@ internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler private readonly bool _isPublished; private readonly IMedia _media; - public DeferredReIndexForMedia(IBackgroundTaskQueue backgroundTaskQueue, - ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IMedia media, bool isPublished) + public DeferredReIndexForMedia( + IBackgroundTaskQueue backgroundTaskQueue, + ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, + IMedia media, + bool isPublished) { _backgroundTaskQueue = backgroundTaskQueue; _examineUmbracoIndexingHandler = examineUmbracoIndexingHandler; @@ -283,8 +293,11 @@ internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler public void Execute() => Execute(_backgroundTaskQueue, _examineUmbracoIndexingHandler, _media, _isPublished); - public static void Execute(IBackgroundTaskQueue backgroundTaskQueue, - ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IMedia media, bool isPublished) => + public static void Execute( + IBackgroundTaskQueue backgroundTaskQueue, + ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, + IMedia media, + bool isPublished) => // perform the ValueSet lookup on a background thread backgroundTaskQueue.QueueBackgroundWorkItem(cancellationToken => { @@ -316,8 +329,10 @@ internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler private readonly ExamineUmbracoIndexingHandler _examineUmbracoIndexingHandler; private readonly IMember _member; - public DeferredReIndexForMember(IBackgroundTaskQueue backgroundTaskQueue, - ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IMember member) + public DeferredReIndexForMember( + IBackgroundTaskQueue backgroundTaskQueue, + ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, + IMember member) { _examineUmbracoIndexingHandler = examineUmbracoIndexingHandler; _member = member; @@ -326,8 +341,10 @@ internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler public void Execute() => Execute(_backgroundTaskQueue, _examineUmbracoIndexingHandler, _member); - public static void Execute(IBackgroundTaskQueue backgroundTaskQueue, - ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IMember member) => + public static void Execute( + IBackgroundTaskQueue backgroundTaskQueue, + ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, + IMember member) => // perform the ValueSet lookup on a background thread backgroundTaskQueue.QueueBackgroundWorkItem(cancellationToken => { @@ -356,7 +373,9 @@ internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler private readonly IReadOnlyCollection? _ids; private readonly bool _keepIfUnpublished; - public DeferredDeleteIndex(ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, int id, + public DeferredDeleteIndex( + ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, + int id, bool keepIfUnpublished) { _examineUmbracoIndexingHandler = examineUmbracoIndexingHandler; @@ -364,8 +383,10 @@ internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler _keepIfUnpublished = keepIfUnpublished; } - public DeferredDeleteIndex(ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, - IReadOnlyCollection ids, bool keepIfUnpublished) + public DeferredDeleteIndex( + ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, + IReadOnlyCollection ids, + bool keepIfUnpublished) { _examineUmbracoIndexingHandler = examineUmbracoIndexingHandler; _ids = ids; @@ -396,8 +417,10 @@ internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler } } - public static void Execute(ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, - IReadOnlyCollection ids, bool keepIfUnpublished) + public static void Execute( + ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, + IReadOnlyCollection ids, + bool keepIfUnpublished) { foreach (IUmbracoIndex index in examineUmbracoIndexingHandler._examineManager.Indexes .OfType() diff --git a/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs b/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs index aab9c71acd..fa5a51bc72 100644 --- a/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs +++ b/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs @@ -32,7 +32,9 @@ public class FilePermissionHelper : IFilePermissionHelper /// /// Initializes a new instance of the class. /// - public FilePermissionHelper(IOptions globalSettings, IIOHelper ioHelper, + public FilePermissionHelper( + IOptions globalSettings, + IIOHelper ioHelper, IHostingEnvironment hostingEnvironment) { _globalSettings = globalSettings.Value; diff --git a/src/Umbraco.Infrastructure/Install/InstallHelper.cs b/src/Umbraco.Infrastructure/Install/InstallHelper.cs index 0b5e04a60f..33152fbfac 100644 --- a/src/Umbraco.Infrastructure/Install/InstallHelper.cs +++ b/src/Umbraco.Infrastructure/Install/InstallHelper.cs @@ -26,7 +26,8 @@ namespace Umbraco.Cms.Infrastructure.Install private readonly IFireAndForgetRunner _fireAndForgetRunner; private readonly IEnumerable _databaseProviderMetadata; - public InstallHelper(DatabaseBuilder databaseBuilder, + public InstallHelper( + DatabaseBuilder databaseBuilder, ILogger logger, IUmbracoVersion umbracoVersion, IOptionsMonitor connectionStrings, diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs index e2930e49bd..fffa0ced9f 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs @@ -105,7 +105,7 @@ namespace Umbraco.Cms.Infrastructure.Migrations.Install using (ICoreScope scope = _scopeProvider.CreateCoreScope()) { // look for the super user with default password - var sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql() + NPoco.Sql? sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql() .SelectCount() .From() .Where(x => x.Id == Constants.Security.SuperUserId && x.Password == "default"); @@ -251,9 +251,9 @@ namespace Umbraco.Cms.Infrastructure.Migrations.Install /// public DatabaseSchemaResult? ValidateSchema() { - using (var scope = _scopeProvider.CreateCoreScope()) + using (ICoreScope scope = _scopeProvider.CreateCoreScope()) { - var result = ValidateSchema(scope); + DatabaseSchemaResult? result = ValidateSchema(scope); scope.Complete(); return result; } @@ -262,10 +262,14 @@ namespace Umbraco.Cms.Infrastructure.Migrations.Install private DatabaseSchemaResult? ValidateSchema(ICoreScope scope) { if (_databaseFactory.Initialized == false) + { return new DatabaseSchemaResult(); + } if (_databaseSchemaValidationResult != null) + { return _databaseSchemaValidationResult; + } _databaseSchemaValidationResult = _scopeAccessor.AmbientScope?.Database.ValidateSchema(); @@ -283,9 +287,9 @@ namespace Umbraco.Cms.Infrastructure.Migrations.Install /// public Result? CreateSchemaAndData() { - using (var scope = _scopeProvider.CreateCoreScope()) + using (ICoreScope scope = _scopeProvider.CreateCoreScope()) { - var result = CreateSchemaAndData(scope); + Result? result = CreateSchemaAndData(scope); if (result?.Success is true) { scope.Notifications.Publish(new DatabaseSchemaAndDataCreatedNotification(result!.RequiresUpgrade)); @@ -299,7 +303,7 @@ namespace Umbraco.Cms.Infrastructure.Migrations.Install { try { - var readyForInstall = CheckReadyForInstall(); + Attempt readyForInstall = CheckReadyForInstall(); if (readyForInstall.Success == false) { return readyForInstall.Result; @@ -307,23 +311,25 @@ namespace Umbraco.Cms.Infrastructure.Migrations.Install _logger.LogInformation("Database configuration status: Started"); - var database = _scopeAccessor.AmbientScope?.Database; + IUmbracoDatabase? database = _scopeAccessor.AmbientScope?.Database; var message = string.Empty; - var schemaResult = ValidateSchema(); + DatabaseSchemaResult? schemaResult = ValidateSchema(); var hasInstalledVersion = schemaResult?.DetermineHasInstalledVersion() ?? false; //If the determined version is "empty" its a new install - otherwise upgrade the existing if (!hasInstalledVersion) { if (_runtimeState.Level == RuntimeLevel.Run) + { throw new Exception("Umbraco is already configured!"); + } - var creator = _databaseSchemaCreatorFactory.Create(database); + DatabaseSchemaCreator creator = _databaseSchemaCreatorFactory.Create(database); creator.InitializeDatabaseSchema(); - message = message + "

Installation completed!

"; + message += "

Installation completed!

"; //now that everything is done, we need to determine the version of SQL server that is executing _logger.LogInformation("Database configuration status: {DbConfigStatus}", message); @@ -361,7 +367,7 @@ namespace Umbraco.Cms.Infrastructure.Migrations.Install { try { - var readyForInstall = CheckReadyForInstall(); + Attempt readyForInstall = CheckReadyForInstall(); if (readyForInstall.Success == false) { return readyForInstall.Result; diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs index a16e16f535..c1edbe5f54 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs @@ -225,8 +225,7 @@ public class DatabaseSchemaCreator var unknownConstraintsInDatabase = constraintsInDatabase.Where( x => x.Item3.InvariantStartsWith("FK_") == false && x.Item3.InvariantStartsWith("PK_") == false && - x.Item3.InvariantStartsWith("IX_") == false - ).Select(x => x.Item3).ToList(); + x.Item3.InvariantStartsWith("IX_") == false).Select(x => x.Item3).ToList(); var foreignKeysInSchema = result.TableDefinitions.SelectMany(x => x.ForeignKeys.Select(y => y.Name)) .Where(x => x is not null).ToList(); @@ -303,7 +302,8 @@ public class DatabaseSchemaCreator IEnumerable invalidColumnDifferences = columnsPerTableInDatabase.Except(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase) - .Union(columnsPerTableInSchema.Except(columnsPerTableInDatabase, + .Union(columnsPerTableInSchema.Except( + columnsPerTableInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var column in invalidColumnDifferences) { diff --git a/src/Umbraco.Infrastructure/Migrations/MigrationPlanExecutor.cs b/src/Umbraco.Infrastructure/Migrations/MigrationPlanExecutor.cs index bf2d734305..1af5f13c3c 100644 --- a/src/Umbraco.Infrastructure/Migrations/MigrationPlanExecutor.cs +++ b/src/Umbraco.Infrastructure/Migrations/MigrationPlanExecutor.cs @@ -159,7 +159,7 @@ public class MigrationPlanExecutor : IMigrationPlanExecutor // prepare and de-duplicate post-migrations, only keeping the 1st occurence var executedTypes = new HashSet(); - foreach (var executedMigrationContext in result.ExecutedMigrationContexts) + foreach (IMigrationContext executedMigrationContext in result.ExecutedMigrationContexts) { if (executedMigrationContext is MigrationContext migrationContext) { diff --git a/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPremigrationPlan.cs b/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPremigrationPlan.cs index c9d23acb90..58f3084231 100644 --- a/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPremigrationPlan.cs +++ b/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPremigrationPlan.cs @@ -20,7 +20,7 @@ public class UmbracoPremigrationPlan : MigrationPlan /// /// This is set to the final migration state of 13.0, making that the lowest supported version to upgrade from. /// - public override string InitialState => ""; + public override string InitialState => string.Empty; /// /// Defines the plan. diff --git a/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs b/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs index a6c3ea453e..00e97a6ad1 100644 --- a/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs +++ b/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs @@ -99,7 +99,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging contentTypeService, contentService, propertyEditors, - (Umbraco.Cms.Infrastructure.Scoping.IScopeProvider) scopeProvider, + (Umbraco.Cms.Infrastructure.Scoping.IScopeProvider)scopeProvider, shortStringHelper, serializer, mediaService, @@ -108,7 +108,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging #region Install/Uninstall - public InstallationSummary InstallPackageData(CompiledPackage compiledPackage, int userId) + public InstallationSummary InstallPackageData(CompiledPackage compiledPackage, int userId) { using (IScope scope = _scopeProvider.CreateScope()) { @@ -252,12 +252,9 @@ namespace Umbraco.Cms.Infrastructure.Packaging if (!importedContentTypes.ContainsKey(contentTypeAlias)) { - TContentTypeComposition contentType = FindContentTypeByAlias(contentTypeAlias, typeService); - if (contentType == null) - { - throw new InvalidOperationException( - "Could not find content type with alias " + contentTypeAlias); - } + TContentTypeComposition contentType = FindContentTypeByAlias(contentTypeAlias, typeService) + ?? throw new InvalidOperationException("Could not find content type with alias " + + contentTypeAlias); importedContentTypes.Add(contentTypeAlias, contentType); } @@ -345,8 +342,8 @@ namespace Umbraco.Cms.Infrastructure.Packaging var templateId = element.AttributeValue("template"); IEnumerable? properties = from property in element.Elements() - where property.Attribute("isDoc") == null - select property; + where property.Attribute("isDoc") == null + select property; //TODO: This will almost never work, we can't reference a template by an INT Id within a package manifest, we need to change the // packager to package templates by UDI and resolve by the same, in 98% of cases, this isn't going to work, or it will resolve the wrong template. @@ -371,12 +368,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging key, int.Parse(level, CultureInfo.InvariantCulture), int.Parse(sortOrder, CultureInfo.InvariantCulture), - template?.Id); - - if (content is null) - { - throw new InvalidOperationException("Cloud not create content"); - } + template?.Id) ?? throw new InvalidOperationException("Cloud not create content"); // Handle culture specific node names const string nodeNamePrefix = "nodeName-"; @@ -386,7 +378,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging foreach (XAttribute localizedNodeName in element.Attributes() .Where(a => a.Name.LocalName.InvariantStartsWith(nodeNamePrefix))) { - var newCulture = localizedNodeName.Name.LocalName.Substring(nodeNamePrefix.Length); + var newCulture = localizedNodeName.Name.LocalName[nodeNamePrefix.Length..]; // Skip the culture if it does not exist in the current project if (installedLanguages.InvariantContains(newCulture)) { @@ -416,7 +408,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging // set property value // Skip unsupported language variation, otherwise we'll get a "not supported error" // We allow null, because that's invariant - if ( propertyLang is null || installedLanguages.InvariantContains(propertyLang)) + if (propertyLang is null || installedLanguages.InvariantContains(propertyLang)) { content.SetValue(propertyTypeAlias, propertyValue, propertyLang); } @@ -449,15 +441,23 @@ namespace Umbraco.Cms.Infrastructure.Packaging { return new Content(name, parentId, c) { - Key = key, Level = level, SortOrder = sortOrder, TemplateId = templateId, - } as TContentBase; + Key = key, + Level = level, + SortOrder = sortOrder, + TemplateId = templateId, + } + as TContentBase; } else { return new Content(name, (IContent)parent, c) { - Key = key, Level = level, SortOrder = sortOrder, TemplateId = templateId, - } as TContentBase; + Key = key, + Level = level, + SortOrder = sortOrder, + TemplateId = templateId, + } + as TContentBase; } case IMediaType m: @@ -465,15 +465,21 @@ namespace Umbraco.Cms.Infrastructure.Packaging { return new Core.Models.Media(name, parentId, m) { - Key = key, Level = level, SortOrder = sortOrder, - } as TContentBase; + Key = key, + Level = level, + SortOrder = sortOrder, + } + as TContentBase; } else { return new Core.Models.Media(name, (IMedia)parent, m) { - Key = key, Level = level, SortOrder = sortOrder, - } as TContentBase; + Key = key, + Level = level, + SortOrder = sortOrder, + } + as TContentBase; } default: @@ -486,7 +492,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging #region DocumentTypes public IReadOnlyList ImportDocumentType(XElement docTypeElement, int userId) - => ImportDocumentTypes(new[] {docTypeElement}, userId, out _); + => ImportDocumentTypes(new[] { docTypeElement }, userId, out _); /// /// Imports and saves package xml as @@ -646,7 +652,8 @@ namespace Umbraco.Cms.Infrastructure.Packaging return list; } - private Dictionary CreateContentTypeFolderStructure(IEnumerable unsortedDocumentTypes, + private Dictionary CreateContentTypeFolderStructure( + IEnumerable unsortedDocumentTypes, out IEnumerable entityContainersInstalled) { var importedFolders = new Dictionary(); @@ -756,7 +763,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging IContentTypeBaseService service) where T : class, IContentTypeComposition { - var key = GetContentTypeKey(documentType); + Guid key = GetContentTypeKey(documentType); XElement infoElement = documentType.Element("Info")!; @@ -790,11 +797,11 @@ namespace Umbraco.Cms.Infrastructure.Packaging { if (parent is null) { - return new ContentType(_shortStringHelper, parentId) {Alias = alias, Key = key} as T; + return new ContentType(_shortStringHelper, parentId) { Alias = alias, Key = key } as T; } else { - return new ContentType(_shortStringHelper, (IContentType)parent, alias) {Key = key} as T; + return new ContentType(_shortStringHelper, (IContentType)parent, alias) { Key = key } as T; } } @@ -802,11 +809,11 @@ namespace Umbraco.Cms.Infrastructure.Packaging { if (parent is null) { - return new MediaType(_shortStringHelper, parentId) {Alias = alias, Key = key} as T; + return new MediaType(_shortStringHelper, parentId) { Alias = alias, Key = key } as T; } else { - return new MediaType(_shortStringHelper, (IMediaType)parent, alias) {Key = key} as T; + return new MediaType(_shortStringHelper, (IMediaType)parent, alias) { Key = key } as T; } } @@ -1118,7 +1125,8 @@ namespace Umbraco.Cms.Infrastructure.Packaging : string.Empty, SortOrder = sortOrder, Variations = property.Element("Variations") != null - ? (ContentVariation)Enum.Parse(typeof(ContentVariation), + ? (ContentVariation)Enum.Parse( + typeof(ContentVariation), property.Element("Variations")!.Value) : ContentVariation.Nothing, LabelOnTop = property.Element("LabelOnTop") != null && property.Element("LabelOnTop")!.Value.ToLowerInvariant().Equals("true") @@ -1189,12 +1197,9 @@ namespace Umbraco.Cms.Infrastructure.Packaging private T FindContentTypeByAlias(string contentTypeAlias, IContentTypeBaseService typeService) where T : IContentTypeComposition { - T? contentType = typeService.Get(contentTypeAlias); - - if (contentType == null) - { - throw new Exception($"ContentType matching the passed in Alias: '{contentTypeAlias}' was null"); - } + T? contentType = typeService.Get(contentTypeAlias) + ?? throw new Exception($"ContentType matching the passed in Alias: '{contentTypeAlias}' " + + $"was null"); return contentType; } @@ -1254,7 +1259,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging var editorAlias = dataTypeElement.Attribute("Id")?.Value?.Trim(); if (!_propertyEditors.TryGet(editorAlias, out IDataEditor? editor)) { - editor = new VoidEditor(_dataValueEditorFactory) {Alias = editorAlias ?? string.Empty}; + editor = new VoidEditor(_dataValueEditorFactory) { Alias = editorAlias ?? string.Empty }; } var editorUiAlias = dataTypeElement.Attribute("EditorUiAlias")?.Value?.Trim() ?? editorAlias; @@ -1291,7 +1296,8 @@ namespace Umbraco.Cms.Infrastructure.Packaging return dataTypes; } - private Dictionary CreateDataTypeFolderStructure(IEnumerable datatypeElements, + private Dictionary CreateDataTypeFolderStructure( + IEnumerable datatypeElements, out IEnumerable entityContainersInstalled) { var importedFolders = new Dictionary(); @@ -1379,7 +1385,8 @@ namespace Umbraco.Cms.Infrastructure.Packaging /// Xml to import /// /// An enumerable list of dictionary items - public IReadOnlyList ImportDictionaryItems(IEnumerable dictionaryItemElementList, + public IReadOnlyList ImportDictionaryItems( + IEnumerable dictionaryItemElementList, int userId) { var languages = _localizationService.GetAllLanguages().ToList(); @@ -1392,8 +1399,11 @@ namespace Umbraco.Cms.Infrastructure.Packaging return ImportDictionaryItem(dictionaryItemElement, languages, parentId, userId); } - private IReadOnlyList ImportDictionaryItems(IEnumerable dictionaryItemElementList, - List languages, Guid? parentId, int userId) + private IReadOnlyList ImportDictionaryItems( + IEnumerable dictionaryItemElementList, + List languages, + Guid? parentId, + int userId) { var items = new List(); foreach (XElement dictionaryItemElement in dictionaryItemElementList) @@ -1404,8 +1414,11 @@ namespace Umbraco.Cms.Infrastructure.Packaging return items; } - private IEnumerable ImportDictionaryItem(XElement dictionaryItemElement, - List languages, Guid? parentId, int userId) + private IEnumerable ImportDictionaryItem( + XElement dictionaryItemElement, + List languages, + Guid? parentId, + int userId) { var items = new List(); @@ -1464,15 +1477,18 @@ namespace Umbraco.Cms.Infrastructure.Packaging return dictionaryItem; } - private static bool DictionaryValueIsNew(IEnumerable translations, + private static bool DictionaryValueIsNew( + IEnumerable translations, XElement valueElement) - => translations.All(t => string.Compare(t.LanguageIsoCode, - valueElement.Attribute("LanguageCultureAlias")?.Value, - StringComparison.InvariantCultureIgnoreCase) != - 0); + => translations.All(t => string.Compare( + t.LanguageIsoCode, + valueElement.Attribute("LanguageCultureAlias")?.Value, + StringComparison.InvariantCultureIgnoreCase) != 0); - private static void AddDictionaryTranslation(ICollection translations, - XElement valueElement, IEnumerable languages) + private static void AddDictionaryTranslation( + ICollection translations, + XElement valueElement, + IEnumerable languages) { var languageId = valueElement.Attribute("LanguageCultureAlias")?.Value; ILanguage? language = languages.SingleOrDefault(l => l.IsoCode == languageId); @@ -1548,7 +1564,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging continue; } - script = new Script(path!) {Content = content}; + script = new Script(path!) { Content = content }; _fileService.SaveScript(script, userId); result.Add(script); } @@ -1563,12 +1579,8 @@ namespace Umbraco.Cms.Infrastructure.Packaging foreach (XElement partialViewXml in partialViewElements) { - var path = partialViewXml.AttributeValue("path"); - - if (path == null) - { - throw new InvalidOperationException("No path attribute found"); - } + var path = partialViewXml.AttributeValue("path") + ?? throw new InvalidOperationException("No path attribute found"); IPartialView? partialView = _fileService.GetPartialView(path); @@ -1577,7 +1589,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging { var content = partialViewXml.Value ?? string.Empty; - partialView = new PartialView(path) {Content = content}; + partialView = new PartialView(path) { Content = content }; _fileService.SavePartialView(partialView, userId); result.Add(partialView); } @@ -1609,7 +1621,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging continue; } - s = new Stylesheet(stylesheetPath!) {Content = content}; + s = new Stylesheet(stylesheetPath!) { Content = content }; _fileService.SaveStylesheet(s, userId); } @@ -1652,7 +1664,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging #region Templates public IEnumerable ImportTemplate(XElement templateElement, int userId) - => ImportTemplates(new[] {templateElement}, userId); + => ImportTemplates(new[] { templateElement }, userId); /// /// Imports and saves package xml as diff --git a/src/Umbraco.Infrastructure/Persistence/NPocoSqlExtensions.cs b/src/Umbraco.Infrastructure/Persistence/NPocoSqlExtensions.cs index 645557cfe0..a899f443c6 100644 --- a/src/Umbraco.Infrastructure/Persistence/NPocoSqlExtensions.cs +++ b/src/Umbraco.Infrastructure/Persistence/NPocoSqlExtensions.cs @@ -25,7 +25,7 @@ namespace Umbraco.Extensions /// The Sql statement. public static Sql Where(this Sql sql, Expression> predicate, string? alias = null) { - var (s, a) = sql.SqlContext.VisitDto(predicate, alias); + (string s, object[] a) = sql.SqlContext.VisitDto(predicate, alias); return sql.Where(s, a); } @@ -41,7 +41,7 @@ namespace Umbraco.Extensions /// The Sql statement. public static Sql Where(this Sql sql, Expression> predicate, string? alias1 = null, string? alias2 = null) { - var (s, a) = sql.SqlContext.VisitDto(predicate, alias1, alias2); + (string s, object[] a) = sql.SqlContext.VisitDto(predicate, alias1, alias2); return sql.Where(s, a); } @@ -169,7 +169,7 @@ namespace Umbraco.Extensions private static Sql WhereIn(this Sql sql, Expression> fieldSelector, Sql? valuesSql, bool not, string? tableAlias) { var fieldName = sql.SqlContext.SqlSyntax.GetFieldName(fieldSelector, tableAlias); - sql.Where(fieldName + (not ? " NOT" : "") +" IN (" + valuesSql?.SQL + ")", valuesSql?.Arguments); + sql.Where(fieldName + (not ? " NOT" : string.Empty) + " IN (" + valuesSql?.SQL + ")", valuesSql?.Arguments); return sql; } @@ -225,7 +225,7 @@ namespace Umbraco.Extensions public static Sql WhereNull(this Sql sql, Expression> field, string? tableAlias = null, bool not = false) { var column = sql.GetColumns(columnExpressions: new[] { field }, tableAlias: tableAlias, withAlias: false).First(); - return sql.Where("(" + column + " IS " + (not ? "NOT " : "") + "NULL)"); + return sql.Where("(" + column + " IS " + (not ? "NOT " : string.Empty) + "NULL)"); } #endregion @@ -546,8 +546,10 @@ namespace Umbraco.Extensions /// An expression specifying the left field. /// An expression specifying the right field. /// The Sql statement. - public static Sql On(this Sql.SqlJoinClause sqlJoin, - Expression> leftField, Expression> rightField) + public static Sql On( + this Sql.SqlJoinClause sqlJoin, + Expression> leftField, + Expression> rightField) { // TODO: ugly - should define on SqlContext! @@ -1181,13 +1183,13 @@ namespace Umbraco.Extensions switch (setExpression.Item2) { case null: - sql.Append((first ? "" : ",") + " " + setExpression.Item1 + "=NULL"); + sql.Append((first ? string.Empty : ",") + " " + setExpression.Item1 + "=NULL"); break; case string s when s == string.Empty: - sql.Append((first ? "" : ",") + " " + setExpression.Item1 + "=''"); + sql.Append((first ? string.Empty : ",") + " " + setExpression.Item1 + "=''"); break; default: - sql.Append((first ? "" : ",") + " " + setExpression.Item1 + "=@0", setExpression.Item2); + sql.Append((first ? string.Empty : ",") + " " + setExpression.Item1 + "=@0", setExpression.Item2); break; } @@ -1205,7 +1207,6 @@ namespace Umbraco.Extensions public class SqlUpd { private readonly ISqlContext _sqlContext; - private readonly List> _setExpressions = new List>(); public SqlUpd(ISqlContext sqlContext) { @@ -1215,11 +1216,11 @@ namespace Umbraco.Extensions public SqlUpd Set(Expression> fieldSelector, object? value) { var fieldName = _sqlContext.SqlSyntax.GetFieldNameForUpdate(fieldSelector); - _setExpressions.Add(new Tuple(fieldName, value)); + SetExpressions.Add(new Tuple(fieldName, value)); return this; } - public List> SetExpressions => _setExpressions; + public List> SetExpressions { get; } = []; } #endregion @@ -1280,11 +1281,7 @@ namespace Umbraco.Extensions var fieldName = field?.GetColumnName(); if (alias != null && fieldName is not null) { - if (aliases == null) - { - aliases = new Dictionary(); - } - + aliases ??= new Dictionary(); aliases[fieldName] = alias; } return fieldName; diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs index c56c3e6934..0d68cd39bf 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs @@ -250,13 +250,13 @@ AND umbracoNode.nodeObjectType = @objectType", if (allowedContentTypes.Any()) { // Insert collection of allowed content types - foreach ((TEntity Entity, int SortOrder) allowedContentType in allowedContentTypes) + foreach ((TEntity entity1, int sortOrder1) in allowedContentTypes) { Database.Insert(new ContentTypeAllowedContentTypeDto { Id = entity.Id, - AllowedId = allowedContentType.Entity.Id, - SortOrder = allowedContentType.SortOrder, + AllowedId = entity1.Id, + SortOrder = sortOrder1, }); } } @@ -406,13 +406,13 @@ AND umbracoNode.id <> @id", (TEntity Entity, int SortOrder)[] allowedContentTypes = GetAllowedContentTypes(entity); if (allowedContentTypes.Any()) { - foreach ((TEntity Entity, int SortOrder) allowedContentType in allowedContentTypes) + foreach ((TEntity entity1, int sortOrder) in allowedContentTypes) { Database.Insert(new ContentTypeAllowedContentTypeDto { Id = entity.Id, - AllowedId = allowedContentType.Entity.Id, - SortOrder = allowedContentType.SortOrder, + AllowedId = entity1.Id, + SortOrder = sortOrder, }); } } @@ -539,11 +539,7 @@ AND umbracoNode.id <> @id", if (propertyType.IsPropertyDirty("Variations")) { // allocate the list only when needed - if (propertyTypeVariationDirty == null) - { - propertyTypeVariationDirty = new List(); - } - + propertyTypeVariationDirty ??= new List(); propertyTypeVariationDirty.Add(propertyType); } } @@ -797,11 +793,7 @@ AND umbracoNode.id <> @id", } // allocate the dictionary only when needed - if (changes == null) - { - changes = new Dictionary(); - } - + changes ??= new Dictionary(); changes[propertyType.Id] = (oldVariation, newVariation); } @@ -864,10 +856,10 @@ AND umbracoNode.id <> @id", propertyTypeChanges.GroupBy(x => x.Value)) { var propertyTypeIds = grouping.Select(x => x.Key).ToList(); - (ContentVariation FromVariation, ContentVariation ToVariation) = grouping.Key; + (ContentVariation fromVariation, ContentVariation toVariation) = grouping.Key; - var fromCultureEnabled = FromVariation.HasFlag(ContentVariation.Culture); - var toCultureEnabled = ToVariation.HasFlag(ContentVariation.Culture); + var fromCultureEnabled = fromVariation.HasFlag(ContentVariation.Culture); + var toCultureEnabled = toVariation.HasFlag(ContentVariation.Culture); if (!fromCultureEnabled && toCultureEnabled) { @@ -889,7 +881,9 @@ AND umbracoNode.id <> @id", /// /// Moves variant data for a content type variation change. /// - private void MoveContentTypeVariantData(IContentTypeComposition contentType, ContentVariation fromVariation, + private void MoveContentTypeVariantData( + IContentTypeComposition contentType, + ContentVariation fromVariation, ContentVariation toVariation) { var defaultLanguageId = GetDefaultLanguageId(); @@ -1510,7 +1504,7 @@ WHERE cmsContentType." + aliasColumn + @" LIKE @pattern", var sql = new Sql( $@"SELECT COUNT(*) FROM cmsContentType INNER JOIN {Constants.DatabaseSchema.Tables.Content} ON cmsContentType.nodeId={Constants.DatabaseSchema.Tables.Content}.contentTypeId -WHERE {Constants.DatabaseSchema.Tables.Content}.nodeId IN (@ids) AND cmsContentType.listView IS NULL", new { ids}); +WHERE {Constants.DatabaseSchema.Tables.Content}.nodeId IN (@ids) AND cmsContentType.listView IS NULL", new { ids }); return Database.ExecuteScalar(sql) > 0; } diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs index ce1b20ffef..a8f6031ca8 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs @@ -185,11 +185,17 @@ internal class DataTypeRepository : EntityRepositoryBase, IDataT var listViewType = new List(); if (dataType.Id.Equals(Constants.DataTypes.DefaultContentListView) && udi.EntityType == ObjectTypes.GetUdiType(UmbracoObjectTypes.DocumentType)) + { listViewType.Add(Constants.Conventions.DataTypes.ListViewPrefix + "Content"); + } else if (dataType.Id.Equals(Constants.DataTypes.DefaultMediaListView) && udi.EntityType == ObjectTypes.GetUdiType(UmbracoObjectTypes.MediaType)) + { listViewType.Add(Constants.Conventions.DataTypes.ListViewPrefix + "Media"); + } else if (dataType.Id.Equals(Constants.DataTypes.DefaultMembersListView) && udi.EntityType == ObjectTypes.GetUdiType(UmbracoObjectTypes.MemberType)) + { listViewType.Add(Constants.Conventions.DataTypes.ListViewPrefix + "Members"); + } if (listViewType.Any()) { @@ -402,7 +408,7 @@ internal class DataTypeRepository : EntityRepositoryBase, IDataT Database.Delete("WHERE nodeId = @Id", new { entity.Id }); // Remove Permissions - Database.Delete("WHERE uniqueId = @Key", new { Key = entity.Key }); + Database.Delete("WHERE uniqueId = @Key", new { entity.Key }); // Remove associated tags Database.Delete("WHERE nodeId = @Id", new { entity.Id }); diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentRepository.cs index ce9c659720..eb94ec127b 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentRepository.cs @@ -97,13 +97,11 @@ public class DocumentRepository : ContentRepositoryBase PermissionRepository => _permissionRepository - ?? (_permissionRepository = + private PermissionRepository PermissionRepository => _permissionRepository ??= new PermissionRepository( - _scopeAccessor, _appCaches, - _loggerFactory - .CreateLogger< - PermissionRepository>())); + _scopeAccessor, + _appCaches, + _loggerFactory.CreateLogger>()); /// public ContentScheduleCollection GetContentSchedule(int contentId) @@ -117,7 +115,8 @@ public class DocumentRepository : ContentRepositoryBase joins = Sql() .InnerJoin("updaterUser") - .On((version, user) => version.UserId == user.Id, + .On( + (version, user) => version.UserId == user.Id, aliasRight: "updaterUser"); // see notes in ApplyOrdering: the field MUST be selected + aliased @@ -166,13 +166,17 @@ public class DocumentRepository : ContentRepositoryBase content.ContentTypeId == contentType.NodeId, aliasRight: "ctype") // left join on optional culture variation //the magic "[[[ISOCODE]]]" parameter value will be replaced in ContentRepositoryBase.GetPage() by the actual ISO code - .LeftJoin(nested => - nested.InnerJoin("langp").On( - (ccv, lang) => ccv.LanguageId == lang.Id && lang.IsoCode == "[[[ISOCODE]]]", "ccvp", + .LeftJoin( + nested => nested.InnerJoin("langp") + .On( + (ccv, lang) => ccv.LanguageId == lang.Id && lang.IsoCode == "[[[ISOCODE]]]", + "ccvp", "langp"), "ccvp") - .On((version, ccv) => version.Id == ccv.VersionId, - "pcv", "ccvp"); + .On( + (version, ccv) => version.Id == ccv.VersionId, + "pcv", + "ccvp"); sql = InsertJoins(sql, joins); @@ -192,7 +196,8 @@ public class DocumentRepository : ContentRepositoryBase MapDtosToContent(List dtos, + private IEnumerable MapDtosToContent( + List dtos, bool withCache = false, bool loadProperties = true, bool loadTemplates = true, @@ -361,7 +366,7 @@ public class DocumentRepository : ContentRepositoryBase(dto.NodeId, versionId, publishedVersionId, contentType); - var ltemp = new List> {temp}; + var ltemp = new List> { temp }; IDictionary properties = GetPropertyCollections(ltemp); content.Properties = properties[dto.DocumentVersionDto.Id]; @@ -450,7 +455,9 @@ public class DocumentRepository : ContentRepositoryBase ids = temps.Select(x => x.Id); - IEnumerable dtos = Database.FetchByGroups(ids, - Constants.Sql.MaxParameterCount, batch => - Sql() - .Select() - .From() - .WhereIn(x => x.NodeId, batch)); + IEnumerable dtos = Database.FetchByGroups( + ids, + Constants.Sql.MaxParameterCount, + batch => Sql() + .Select() + .From() + .WhereIn(x => x.NodeId, batch)); var variations = new Dictionary>(); @@ -480,7 +488,8 @@ public class DocumentRepository : ContentRepositoryBase GetDocumentVariationDtos(IContent content, + private IEnumerable GetDocumentVariationDtos( + IContent content, HashSet editedCultures) { IEnumerable @@ -669,20 +679,27 @@ public class DocumentRepository : ContentRepositoryBase((left, right) => left.Id == right.Id) // left join on optional published version - .LeftJoin(nested => - nested.InnerJoin("pdv") - .On((left, right) => left.Id == right.Id && right.Published, - "pcv", "pdv"), "pcv") - .On((left, right) => left.NodeId == right.NodeId, aliasRight: "pcv") + .LeftJoin( + nested => nested.InnerJoin("pdv") + .On( + (left, right) => left.Id == right.Id && right.Published, + "pcv", + "pdv"), + "pcv") + .On( + (left, right) => left.NodeId == right.NodeId, + aliasRight: "pcv") // TODO: should we be joining this when the query type is not single/many? // left join on optional culture variation //the magic "[[[ISOCODE]]]" parameter value will be replaced in ContentRepositoryBase.GetPage() by the actual ISO code - .LeftJoin(nested => - nested.InnerJoin("lang").On( - (ccv, lang) => ccv.LanguageId == lang.Id && lang.IsoCode == "[[[ISOCODE]]]", "ccv", "lang"), "ccv") - .On((version, ccv) => version.Id == ccv.VersionId, - aliasRight: "ccv"); + .LeftJoin( + nested => nested.InnerJoin("lang") + .On( + (ccv, lang) => ccv.LanguageId == lang.Id && lang.IsoCode == "[[[ISOCODE]]]", "ccv", "lang"), "ccv") + .On( + (version, ccv) => version.Id == ccv.VersionId, + aliasRight: "ccv"); sql .Where(x => x.NodeObjectType == NodeObjectTypeId); @@ -811,10 +828,9 @@ public class DocumentRepository : ContentRepositoryBase() .InnerJoin() .On((c, d) => c.Id == d.Id) - .Where(x => x.Id == SqlTemplate.Arg("versionId")) - ); + .Where(x => x.Id == SqlTemplate.Arg("versionId"))); DocumentVersionDto? versionDto = - Database.Fetch(template.Sql(new {versionId})).FirstOrDefault(); + Database.Fetch(template.Sql(new { versionId })).FirstOrDefault(); // nothing to delete if (versionDto == null) @@ -850,10 +866,9 @@ public class DocumentRepository : ContentRepositoryBase(x => x.NodeId == SqlTemplate.Arg("nodeId") && !x.Current && x.VersionDate < SqlTemplate.Arg("versionDate")) - .Where(x => !x.Published) - ); + .Where(x => !x.Published)); List? versionDtos = - Database.Fetch(template.Sql(new {nodeId, versionDate})); + Database.Fetch(template.Sql(new { nodeId, versionDate })); foreach (ContentVersionDto? versionDto in versionDtos) { PerformDeleteVersion(versionDto.NodeId, versionDto.Id); @@ -862,10 +877,10 @@ public class DocumentRepository : ContentRepositoryBase("WHERE versionId = @versionId", new {versionId}); - Database.Delete("WHERE versionId = @versionId", new {versionId}); - Database.Delete("WHERE id = @versionId", new {versionId}); - Database.Delete("WHERE id = @versionId", new {versionId}); + Database.Delete("WHERE versionId = @versionId", new { versionId }); + Database.Delete("WHERE versionId = @versionId", new { versionId }); + Database.Delete("WHERE id = @versionId", new { versionId }); + Database.Delete("WHERE id = @versionId", new { versionId }); } #endregion @@ -968,8 +983,13 @@ public class DocumentRepository : ContentRepositoryBase propertyDataDtos = PropertyFactory.BuildDtos(entity.ContentType.Variations, - entity.VersionId, entity.PublishedVersionId, entity.Properties, LanguageRepository, out var edited, + IEnumerable propertyDataDtos = PropertyFactory.BuildDtos( + entity.ContentType.Variations, + entity.VersionId, + entity.PublishedVersionId, + entity.Properties, + LanguageRepository, + out var edited, out HashSet? editedCultures); foreach (PropertyDataDto propertyDataDto in propertyDataDtos) { @@ -1342,16 +1362,16 @@ public class DocumentRepository : ContentRepositoryBase(x => x.Id, ids)); //add/update the rest - foreach ((ContentSchedule Model, ContentScheduleDto Dto) schedule in schedules) + foreach ((ContentSchedule model, ContentScheduleDto dto) in schedules) { - if (schedule.Model.Id == Guid.Empty) + if (model.Id == Guid.Empty) { - schedule.Model.Id = schedule.Dto.Id = Guid.NewGuid(); - Database.Insert(schedule.Dto); + model.Id = dto.Id = Guid.NewGuid(); + Database.Insert(dto); } else { - Database.Update(schedule.Dto); + Database.Update(dto); } } } @@ -1431,9 +1451,13 @@ public class DocumentRepository : ContentRepositoryBase PermissionRepository.Save(permission); /// - public override IEnumerable GetPage(IQuery? query, - long pageIndex, int pageSize, out long totalRecords, - IQuery? filter, Ordering? ordering) + public override IEnumerable GetPage( + IQuery? query, + long pageIndex, + int pageSize, + out long totalRecords, + IQuery? filter, + Ordering? ordering) { Sql? filterSql = null; @@ -1601,7 +1625,8 @@ public class DocumentRepository : ContentRepositoryBase tsql .SelectCount() .From() @@ -1771,7 +1796,7 @@ public class DocumentRepository : ContentRepositoryBase otherNames = - cultureNames.Select(x => new SimilarNodeName {Id = x.Id, Name = x.Name}); + cultureNames.Select(x => new SimilarNodeName { Id = x.Id, Name = x.Name }); var uniqueName = SimilarNodeName.GetUniqueName(otherNames, 0, cultureInfo.Name); if (uniqueName == content.GetCultureName(cultureInfo.Culture)) diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DynamicRootRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DynamicRootRepository.cs index 0d2b90aa0e..ee9cbf0bd2 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DynamicRootRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DynamicRootRepository.cs @@ -6,7 +6,7 @@ using Umbraco.Extensions; namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement; -public class DynamicRootRepository: IDynamicRootRepository +public class DynamicRootRepository : IDynamicRootRepository { private readonly IScopeAccessor _scopeAccessor; @@ -35,7 +35,8 @@ public class DynamicRootRepository: IDynamicRootRepository return await Database.SingleOrDefaultAsync(query); } - public async Task FurthestAncestorOrSelfAsync(IEnumerable origins, DynamicRootQueryStep filter) { + public async Task FurthestAncestorOrSelfAsync(IEnumerable origins, DynamicRootQueryStep filter) + { Sql query = Database.SqlContext.SqlSyntax.SelectTop( GetAncestorOrSelfBaseQuery(origins, filter) .Append($"ORDER BY n.level ASC"), @@ -46,7 +47,7 @@ public class DynamicRootRepository: IDynamicRootRepository private Sql GetAncestorOrSelfBaseQuery(IEnumerable origins, DynamicRootQueryStep filter) { - var query = Database.SqlContext.Sql() + Sql query = Database.SqlContext.Sql() .Select("n", n => n.UniqueId) .From("norigin") .Append( // hack because npoco do not support this @@ -103,7 +104,7 @@ internal static class HelperExtensions { internal static Sql DescendantOrSelfBaseQuery(this Sql sql, IEnumerable origins, DynamicRootQueryStep filter) { - var query = sql + Sql query = sql .From("norigin") .Append(// hack because npoco do not support this $"INNER JOIN {sql.SqlContext.SqlSyntax.GetQuotedTableName(NodeDto.TableName)} n ON {sql.SqlContext.SqlSyntax.Substring}(N.path, 1, {sql.SqlContext.SqlSyntax.Length}(norigin.path)) = norigin.path") diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityContainerRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityContainerRepository.cs index 11bd4b53e1..cb1cf56a72 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityContainerRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityContainerRepository.cs @@ -140,8 +140,7 @@ internal class EntityContainerRepository : EntityRepositoryBase( (node, parent) => node.ParentId == parent.NodeId, aliasRight: "parent") .Where(dto => dto.Text == name && dto.NodeObjectType == NodeObjectTypeId) - .Where(parent => parent.UniqueId == parentKey, alias: "parent") - ); + .Where(parent => parent.UniqueId == parentKey, alias: "parent")); return nodeDto is not null; } @@ -150,8 +149,7 @@ internal class EntityContainerRepository : EntityRepositoryBase(Sql().SelectAll() .From() - .Where(dto => dto.Text == name && dto.NodeObjectType == NodeObjectTypeId && dto.ParentId == parentId) - ); + .Where(dto => dto.Text == name && dto.NodeObjectType == NodeObjectTypeId && dto.ParentId == parentId)); return nodeDto is not null; } @@ -239,12 +237,8 @@ internal class EntityContainerRepository : EntityRepositoryBase(Sql().SelectAll() .From() .Where(dto => - dto.NodeId == entity.ParentId && dto.NodeObjectType == entity.ContainerObjectType)); - - if (parentDto == null) - { - throw new InvalidOperationException("Could not find parent container with id " + entity.ParentId); - } + dto.NodeId == entity.ParentId && dto.NodeObjectType == entity.ContainerObjectType)) + ?? throw new InvalidOperationException("Could not find parent container with id " + entity.ParentId); level = parentDto.Level; path = parentDto.Path; @@ -304,11 +298,8 @@ internal class EntityContainerRepository : EntityRepositoryBase(Sql().SelectAll() .From() - .Where(dto => dto.NodeId == entity.Id && dto.NodeObjectType == entity.ContainerObjectType)); - if (nodeDto == null) - { - throw new InvalidOperationException("Could not find container with id " + entity.Id); - } + .Where(dto => dto.NodeId == entity.Id && dto.NodeObjectType == entity.ContainerObjectType)) + ?? throw new InvalidOperationException("Could not find container with id " + entity.Id); // guard against duplicates NodeDto dupNodeDto = Database.FirstOrDefault(Sql().SelectAll() @@ -332,13 +323,9 @@ internal class EntityContainerRepository : EntityRepositoryBase(Sql().SelectAll() .From() .Where(dto => - dto.NodeId == entity.ParentId && dto.NodeObjectType == entity.ContainerObjectType)); - - if (parent == null) - { - throw new InvalidOperationException( + dto.NodeId == entity.ParentId && dto.NodeObjectType == entity.ContainerObjectType)) + ?? throw new InvalidOperationException( "Could not find parent container with id " + entity.ParentId); - } nodeDto.Level = Convert.ToInt16(parent.Level + 1); nodeDto.Path = parent.Path + "," + nodeDto.NodeId; diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepository.cs index ec0b06a451..fdaadb3027 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepository.cs @@ -36,7 +36,7 @@ internal class EntityRepository : RepositoryBase, IEntityRepositoryExtended sql.SelectCount(); sql .From(); - sql.WhereIn(x => x.NodeObjectType, objectTypes ); + sql.WhereIn(x => x.NodeObjectType, objectTypes); foreach (Tuple queryClause in query.GetWhereClauses()) { @@ -83,7 +83,7 @@ internal class EntityRepository : RepositoryBase, IEntityRepositoryExtended } }, objectTypes); - ordering = ordering ?? Ordering.ByDefault(); + ordering ??= Ordering.ByDefault(); var translator = new SqlTranslator(sql, query); sql = translator.Translate(); @@ -252,7 +252,7 @@ internal class EntityRepository : RepositoryBase, IEntityRepositoryExtended var isMedia = objectType == Constants.ObjectTypes.Media; var isMember = objectType == Constants.ObjectTypes.Member; - Sql sql = GetBaseWhere(isContent, isMedia, isMember, false, null, new[] {objectType}); + Sql sql = GetBaseWhere(isContent, isMedia, isMember, false, null, new[] { objectType }); var translator = new SqlTranslator(sql, query); sql = translator.Translate(); @@ -316,7 +316,7 @@ internal class EntityRepository : RepositoryBase, IEntityRepositoryExtended public bool Exists(IEnumerable keys) { - var distictKeys = keys.Distinct(); + IEnumerable distictKeys = keys.Distinct(); Sql sql = Sql().SelectCount().From().Where(x => distictKeys.Contains(x.UniqueId)); return Database.ExecuteScalar(sql) == distictKeys.Count(); } @@ -349,7 +349,7 @@ internal class EntityRepository : RepositoryBase, IEntityRepositoryExtended } private DocumentEntitySlim BuildVariants(DocumentEntitySlim entity) - => BuildVariants(new[] {entity}).First(); + => BuildVariants(new[] { entity }).First(); private IEnumerable BuildVariants(IEnumerable entities) { @@ -359,7 +359,7 @@ internal class EntityRepository : RepositoryBase, IEntityRepositoryExtended { if (e.Variations.VariesByCulture()) { - (v ?? (v = new List())).Add(e); + (v ??= new List()).Add(e); } } @@ -369,8 +369,10 @@ internal class EntityRepository : RepositoryBase, IEntityRepositoryExtended } // fetch all variant info dtos - IEnumerable dtos = Database.FetchByGroups(v.Select(x => x.Id), - Constants.Sql.MaxParameterCount, GetVariantInfos); + IEnumerable dtos = Database.FetchByGroups( + v.Select(x => x.Id), + Constants.Sql.MaxParameterCount, + GetVariantInfos); // group by node id (each group contains all languages) var xdtos = dtos.GroupBy(x => x.NodeId).ToDictionary(x => x.Key, x => x); @@ -396,10 +398,16 @@ internal class EntityRepository : RepositoryBase, IEntityRepositoryExtended Sql() .Select(x => x.NodeId) .AndSelect(x => x.IsoCode) - .AndSelect("doc", x => Alias(x.Published, "DocumentPublished"), + .AndSelect( + "doc", + x => Alias( + x.Published, + "DocumentPublished"), x => Alias(x.Edited, "DocumentEdited")) - .AndSelect("dcv", - x => Alias(x.Available, "CultureAvailable"), x => Alias(x.Published, "CulturePublished"), + .AndSelect( + "dcv", + x => Alias(x.Available, "CultureAvailable"), + x => Alias(x.Published, "CulturePublished"), x => Alias(x.Edited, "CultureEdited"), x => Alias(x.Name, "Name")) @@ -440,7 +448,7 @@ internal class EntityRepository : RepositoryBase, IEntityRepositoryExtended protected Sql GetFullSqlForEntityType(bool isContent, bool isMedia, bool isMember, Guid objectType, Action>? filter) { - Sql sql = GetBaseWhere(isContent, isMedia, isMember, false, filter, new[] {objectType}); + Sql sql = GetBaseWhere(isContent, isMedia, isMember, false, filter, new[] { objectType }); return AddGroupBy(isContent, isMedia, isMember, sql, true); } diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MediaRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MediaRepository.cs index 744a55591f..2f037653a7 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MediaRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MediaRepository.cs @@ -57,16 +57,23 @@ public class MediaRepository : ContentRepositoryBase()); } protected override MediaRepository This => this; /// - public override IEnumerable GetPage(IQuery? query, - long pageIndex, int pageSize, out long totalRecords, - IQuery? filter, Ordering? ordering) + public override IEnumerable GetPage( + IQuery? query, + long pageIndex, + int pageSize, + out long totalRecords, + IQuery? filter, + Ordering? ordering) { Sql? filterSql = null; @@ -313,7 +320,7 @@ public class MediaRepository : ContentRepositoryBase sql = GetBaseQuery(QueryType.Single, joinMediaVersion: true) diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MemberRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MemberRepository.cs index a382cd2a27..6be4c36376 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MemberRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MemberRepository.cs @@ -300,8 +300,11 @@ public class MemberRepository : ContentRepositoryBase /// Gets paged member results. /// - public override IEnumerable GetPage(IQuery? query, - long pageIndex, int pageSize, out long totalRecords, + public override IEnumerable GetPage( + IQuery? query, + long pageIndex, + int pageSize, + out long totalRecords, IQuery? filter, Ordering? ordering) { diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TagRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TagRepository.cs index ecc6600d4c..0c2980a2ab 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TagRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TagRepository.cs @@ -175,7 +175,8 @@ WHERE r.tagId IS NULL"; /// public void RemoveAll(int contentId) => - Database.Execute("DELETE FROM cmsTagRelationship WHERE nodeId = @nodeId", + Database.Execute( + "DELETE FROM cmsTagRelationship WHERE nodeId = @nodeId", new {nodeId = contentId}); // this is a clever way to produce an SQL statement like this: @@ -336,7 +337,8 @@ WHERE r.tagId IS NULL"; { Sql sql = Sql() .Select(x => Alias(x.NodeId, "NodeId")) - .AndSelect(x => Alias(x.Alias, "PropertyTypeAlias"), + .AndSelect( + x => Alias(x.Alias, "PropertyTypeAlias"), x => Alias(x.Id, "PropertyTypeId")) .AndSelect(x => Alias(x.Id, "TagId"), x => Alias(x.Text, "TagText"), x => Alias(x.Group, "TagGroup"), x => Alias(x.LanguageId, "TagLanguage")) diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TrackedReferencesRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TrackedReferencesRepository.cs index 62d3f3acd6..90e3fde207 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TrackedReferencesRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TrackedReferencesRepository.cs @@ -27,7 +27,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement { Sql innerUnionSql = GetInnerUnionSql(); - var sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql() + Sql? sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql() .SelectDistinct( "[x].[id] as nodeId", "[n].[uniqueId] as nodeKey", @@ -78,7 +78,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement // Ordering is required for paging sql = sql?.OrderBy(x => x.Alias, "x"); - var pagedResult = _scopeAccessor.AmbientScope?.Database.Page(pageIndex + 1, pageSize, sql); + Page? pagedResult = _scopeAccessor.AmbientScope?.Database.Page(pageIndex + 1, pageSize, sql); totalRecords = Convert.ToInt32(pagedResult?.TotalItems); return pagedResult?.Items.Select(MapDtoToEntity) ?? Enumerable.Empty(); @@ -91,7 +91,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement throw new InvalidOperationException("No Ambient Scope available"); } - var innerUnionSqlChild = _scopeAccessor.AmbientScope.Database.SqlContext.Sql().Select( + Sql innerUnionSqlChild = _scopeAccessor.AmbientScope.Database.SqlContext.Sql().Select( "[cn].uniqueId as [key]", "[pn].uniqueId as otherKey, [cr].childId as id", "[cr].parentId as otherId", "[rt].[alias]", "[rt].[name]", "[rt].[isDependency]", "[rt].[dual]") .From("cr") @@ -102,7 +102,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement .InnerJoin("pn") .On((cr, pn) => cr.ParentId == pn.NodeId, "cr", "pn"); - var innerUnionSqlDualParent = _scopeAccessor.AmbientScope.Database.SqlContext.Sql().Select( + Sql innerUnionSqlDualParent = _scopeAccessor.AmbientScope.Database.SqlContext.Sql().Select( "[pn].uniqueId as [key]", "[cn].uniqueId as otherKey, [dpr].parentId as id", "[dpr].childId as otherId", "[dprt].[alias]", "[dprt].[name]", "[dprt].[isDependency]", "[dprt].[dual]") .From("dpr") @@ -114,7 +114,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement .InnerJoin("pn") .On((dpr, pn) => dpr.ParentId == pn.NodeId, "dpr", "pn"); - var innerUnionSql3 = _scopeAccessor.AmbientScope.Database.SqlContext.Sql().Select( + Sql innerUnionSql3 = _scopeAccessor.AmbientScope.Database.SqlContext.Sql().Select( "[cn].uniqueId as [key]", "[pn].uniqueId as otherKey, [dcr].childId as id", "[dcr].parentId as otherId", "[dcrt].[alias]", "[dcrt].[name]", "[dcrt].[isDependency]", "[dcrt].[dual]") .From("dcr") @@ -126,7 +126,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement .InnerJoin("pn") .On((dcr, pn) => dcr.ParentId == pn.NodeId, "dcr", "pn"); - var innerUnionSql = innerUnionSqlChild.Union(innerUnionSqlDualParent).Union(innerUnionSql3); + Sql innerUnionSql = innerUnionSqlChild.Union(innerUnionSqlDualParent).Union(innerUnionSql3); return innerUnionSql; } @@ -134,13 +134,17 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement /// /// Gets a page of the descending items that have any references, given a parent id. /// - public IEnumerable GetPagedDescendantsInReferences(int parentId, long pageIndex, int pageSize, - bool filterMustBeIsDependency, out long totalRecords) + public IEnumerable GetPagedDescendantsInReferences( + int parentId, + long pageIndex, + int pageSize, + bool filterMustBeIsDependency, + out long totalRecords) { - var syntax = _scopeAccessor.AmbientScope?.Database.SqlContext.SqlSyntax; + SqlSyntax.ISqlSyntaxProvider? syntax = _scopeAccessor.AmbientScope?.Database.SqlContext.SqlSyntax; // Gets the path of the parent with ",%" added - var subsubQuery = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql() + Sql? subsubQuery = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql() .Select(syntax?.GetConcat("[node].[path]", "',%'")) .From("node") .Where(x => x.NodeId == parentId, "node"); @@ -153,7 +157,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement Sql innerUnionSql = GetInnerUnionSql(); - var sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( + Sql? sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( "[x].[id] as nodeId", "[n].[uniqueId] as nodeKey", "[n].[text] as nodeName", @@ -200,7 +204,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement // Ordering is required for paging sql = sql?.OrderBy(x => x.Alias, "x"); - var pagedResult = _scopeAccessor.AmbientScope?.Database.Page(pageIndex + 1, pageSize, sql); + Page? pagedResult = _scopeAccessor.AmbientScope?.Database.Page(pageIndex + 1, pageSize, sql); totalRecords = Convert.ToInt32(pagedResult?.TotalItems); return pagedResult?.Items.Select(MapDtoToEntity) ?? Enumerable.Empty(); @@ -215,7 +219,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement bool filterMustBeIsDependency, out long totalRecords) { Sql innerUnionSql = GetInnerUnionSql(); - var sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( + Sql? sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( "[x].[otherId] as nodeId", "[n].[uniqueId] as nodeKey", "[n].[text] as nodeName", @@ -261,7 +265,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement // Ordering is required for paging sql = sql?.OrderBy(x => x.Alias, "x"); - var pagedResult = _scopeAccessor.AmbientScope?.Database.Page(pageIndex + 1, pageSize, sql); + Page? pagedResult = _scopeAccessor.AmbientScope?.Database.Page(pageIndex + 1, pageSize, sql); totalRecords = Convert.ToInt32(pagedResult?.TotalItems); return pagedResult?.Items.Select(MapDtoToEntity) ?? Enumerable.Empty(); @@ -274,8 +278,8 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement bool filterMustBeIsDependency, out long totalRecords) { - Sql innerUnionSql = GetInnerUnionSql(); - var sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( + Sql innerUnionSql = GetInnerUnionSql(); + Sql? sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( "[x].[otherId] as nodeId", "[n].[uniqueId] as nodeKey", "[n].[text] as nodeName", @@ -351,7 +355,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement out long totalRecords) { Sql innerUnionSql = GetInnerUnionSql(); - var sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( + Sql? sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( "[x].[otherId] as nodeId", "[n].[uniqueId] as nodeKey", "[n].[text] as nodeName", @@ -366,14 +370,19 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement .From("n") .InnerJoinNested(innerUnionSql, "x") .On((n, x) => n.NodeId == x.OtherId, "n", "x") - .LeftJoin("c").On((left, right) => left.NodeId == right.NodeId, + .LeftJoin("c").On( + (left, right) => left.NodeId == right.NodeId, aliasLeft: "n", aliasRight: "c") .LeftJoin("ct") - .On((left, right) => left.ContentTypeId == right.NodeId, aliasLeft: "c", + .On( + (left, right) => left.ContentTypeId == right.NodeId, + aliasLeft: "c", aliasRight: "ct") - .LeftJoin("ctn").On((left, right) => left.NodeId == right.NodeId, - aliasLeft: "ct", aliasRight: "ctn") + .LeftJoin("ctn").On( + (left, right) => left.NodeId == right.NodeId, + aliasLeft: "ct", + aliasRight: "ctn") .Where(x => x.Id == id, "x"); if (filterMustBeIsDependency) @@ -404,12 +413,12 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement return _umbracoMapper.MapEnumerable(pagedResult); } - public IEnumerable GetPagedItemsWithRelations( - ISet keys, - long skip, - long take, - bool filterMustBeIsDependency, - out long totalRecords) + public IEnumerable GetPagedItemsWithRelations( + ISet keys, + long skip, + long take, + bool filterMustBeIsDependency, + out long totalRecords) { Sql innerUnionSql = GetInnerUnionSql(); Sql? sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( @@ -468,13 +477,17 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement return _umbracoMapper.MapEnumerable(pagedResult); } - public IEnumerable GetPagedDescendantsInReferences(Guid parentKey, long skip, long take, bool filterMustBeIsDependency, - out long totalRecords) - { - var syntax = _scopeAccessor.AmbientScope?.Database.SqlContext.SqlSyntax; + public IEnumerable GetPagedDescendantsInReferences( + Guid parentKey, + long skip, + long take, + bool filterMustBeIsDependency, + out long totalRecords) + { + SqlSyntax.ISqlSyntaxProvider? syntax = _scopeAccessor.AmbientScope?.Database.SqlContext.SqlSyntax; // Gets the path of the parent with ",%" added - var subsubQuery = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql() + Sql? subsubQuery = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql() .Select(syntax?.GetConcat("[node].[path]", "',%'")) .From("node") .Where(x => x.UniqueId == parentKey, "node"); @@ -486,7 +499,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement .WhereLike(x => x.Path, subsubQuery); Sql innerUnionSql = GetInnerUnionSql(); - var sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( + Sql? sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( "[x].[id] as nodeId", "[n].[uniqueId] as nodeKey", "[n].[text] as nodeName", @@ -502,20 +515,28 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement .From("n") .InnerJoinNested(innerUnionSql, "x") .On((n, x) => n.NodeId == x.Id, "n", "x") - .LeftJoin("c").On((left, right) => left.NodeId == right.NodeId, - aliasLeft: "n", aliasRight: "c") + .LeftJoin("c").On( + (left, right) => left.NodeId == right.NodeId, + aliasLeft: "n", + aliasRight: "c") .LeftJoin("ct") - .On((left, right) => left.ContentTypeId == right.NodeId, aliasLeft: "c", + .On( + (left, right) => left.ContentTypeId == right.NodeId, + aliasLeft: "c", aliasRight: "ct") .LeftJoin("ctn") - .On((left, right) => left.NodeId == right.NodeId, aliasLeft: "ct", + .On( + (left, right) => left.NodeId == right.NodeId, + aliasLeft: "ct", aliasRight: "ctn") .LeftJoin("d") .On( (left, right) => left.NodeId == right.NodeId, aliasLeft: "n", aliasRight: "d"); - sql = sql?.WhereIn((System.Linq.Expressions.Expression>)(x => x.NodeId), subQuery, + sql = sql?.WhereIn( + (System.Linq.Expressions.Expression>)(x => x.NodeId), + subQuery, "n"); if (filterMustBeIsDependency) @@ -544,15 +565,15 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement } return _umbracoMapper.MapEnumerable(pagedResult); - } + } - [Obsolete("Use overload that takes keys instead of ids. This will be removed in Umbraco 15.")] + [Obsolete("Use overload that takes keys instead of ids. This will be removed in Umbraco 15.")] public IEnumerable GetPagedItemsWithRelations( - int[] ids, - long skip, - long take, - bool filterMustBeIsDependency, - out long totalRecords) + int[] ids, + long skip, + long take, + bool filterMustBeIsDependency, + out long totalRecords) { Sql innerUnionSql = GetInnerUnionSql(); Sql? sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( @@ -618,10 +639,10 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement bool filterMustBeIsDependency, out long totalRecords) { - var syntax = _scopeAccessor.AmbientScope?.Database.SqlContext.SqlSyntax; + SqlSyntax.ISqlSyntaxProvider? syntax = _scopeAccessor.AmbientScope?.Database.SqlContext.SqlSyntax; // Gets the path of the parent with ",%" added - var subsubQuery = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql() + Sql? subsubQuery = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql() .Select(syntax?.GetConcat("[node].[path]", "',%'")) .From("node") .Where(x => x.NodeId == parentId, "node"); @@ -633,7 +654,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement .WhereLike(x => x.Path, subsubQuery); Sql innerUnionSql = GetInnerUnionSql(); - var sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( + Sql? sql = _scopeAccessor.AmbientScope?.Database.SqlContext.Sql().SelectDistinct( "[x].[id] as nodeId", "[n].[uniqueId] as nodeKey", "[n].[text] as nodeName", @@ -648,15 +669,23 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement .From("n") .InnerJoinNested(innerUnionSql, "x") .On((n, x) => n.NodeId == x.Id, "n", "x") - .LeftJoin("c").On((left, right) => left.NodeId == right.NodeId, - aliasLeft: "n", aliasRight: "c") + .LeftJoin("c").On( + (left, right) => left.NodeId == right.NodeId, + aliasLeft: "n", + aliasRight: "c") .LeftJoin("ct") - .On((left, right) => left.ContentTypeId == right.NodeId, aliasLeft: "c", + .On( + (left, right) => left.ContentTypeId == right.NodeId, + aliasLeft: "c", aliasRight: "ct") .LeftJoin("ctn") - .On((left, right) => left.NodeId == right.NodeId, aliasLeft: "ct", + .On( + (left, right) => left.NodeId == right.NodeId, + aliasLeft: "ct", aliasRight: "ctn"); - sql = sql?.WhereIn((System.Linq.Expressions.Expression>)(x => x.NodeId), subQuery, + sql = sql?.WhereIn( + (System.Linq.Expressions.Expression>)(x => x.NodeId), + subQuery, "n"); if (filterMustBeIsDependency) diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserGroupRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserGroupRepository.cs index c277ac25fc..7a6b213291 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserGroupRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserGroupRepository.cs @@ -434,8 +434,7 @@ public class UserGroupRepository : EntityRepositoryBase, IUserG x => x.Name, x => x.HasAccessToAllLanguages, x => x.Key, - x => x.DefaultPermissions - ) + x => x.DefaultPermissions) .AndBy(x => x.AppAlias, x => x.UserGroupId); protected override string GetBaseWhereClause() => $"{Constants.DatabaseSchema.Tables.UserGroup}.id = @id"; @@ -504,7 +503,7 @@ public class UserGroupRepository : EntityRepositoryBase, IUserG private void PersistAllowedLanguages(IUserGroup entity) { - var userGroup = entity; + IUserGroup userGroup = entity; // First delete all Database.Delete("WHERE UserGroupId = @UserGroupId", new { UserGroupId = userGroup.Id }); diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs index 892fa78ae4..02628f91c3 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs @@ -263,23 +263,23 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 public bool ValidateLoginSession(int userId, Guid sessionId) { // HACK: Avoid a deadlock - BackOfficeCookieOptions OnValidatePrincipal - // After existing session times out and user logs in again ~ 4 requests come in at once that hit the - // "update the validate date" code path, check up the call stack there are a few variables that can make this not occur. - // TODO: more generic fix, do something with ForUpdate? wait on a mutex? add a distributed lock? etc. - if (Database.DatabaseType.IsSqlite()) + // After existing session times out and user logs in again ~ 4 requests come in at once that hit the + // "update the validate date" code path, check up the call stack there are a few variables that can make this not occur. + // TODO: more generic fix, do something with ForUpdate? wait on a mutex? add a distributed lock? etc. + if (Database.DatabaseType.IsSqlite()) + { + lock (_sqliteValidateSessionLock) { - lock (_sqliteValidateSessionLock) - { - return ValidateLoginSessionInternal(userId, sessionId); - } + return ValidateLoginSessionInternal(userId, sessionId); } - - return ValidateLoginSessionInternal(userId, sessionId); } - private bool ValidateLoginSessionInternal(int userId, Guid sessionId) - { - // with RepeatableRead transaction mode, read-then-update operations can + return ValidateLoginSessionInternal(userId, sessionId); + } + + private bool ValidateLoginSessionInternal(int userId, Guid sessionId) + { + // with RepeatableRead transaction mode, read-then-update operations can // cause deadlocks, and the ForUpdate() hint is required to tell the database // to acquire an exclusive lock when reading @@ -304,7 +304,8 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 { //timeout detected, update the record if (Logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) - {Logger.LogDebug("ClearLoginSession for sessionId {sessionId}", sessionId); + { + Logger.LogDebug("ClearLoginSession for sessionId {sessionId}", sessionId); } ClearLoginSession(sessionId); return false; @@ -408,7 +409,7 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 return; } - List userIds = dtos.Count == 1 ? new List {dtos[0].Id} : dtos.Select(x => x.Id).ToList(); + List userIds = dtos.Count == 1 ? new List { dtos[0].Id } : dtos.Select(x => x.Id).ToList(); Dictionary? xUsers = dtos.Count == 1 ? null : dtos.ToDictionary(x => x.Id, x => x); var groupIds = new List(); @@ -417,7 +418,7 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 try { sql = SqlContext.Sql() - .Select(x=>x.Id, x=>x.Key) + .Select(x => x.Id, x => x.Key) .From() .InnerJoin().On((left, right) => left.Id == right.UserGroupId) .WhereIn(x => x.UserId, userIds); @@ -425,10 +426,10 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 List? userGroups = Database.Fetch(sql); - groupKeys= userGroups.Select(x => x.Key).ToList(); + groupKeys = userGroups.Select(x => x.Key).ToList(); } - catch (DbException e) + catch (DbException) { // ignore doing upgrade, as we know the Key potentially do not exists if (_runtimeState.Level != RuntimeLevel.Upgrade) @@ -450,7 +451,7 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 if (groupIds.Any() is false) { //this can happen if we are upgrading, so we try do read from this table, as we counn't because of the key earlier - groupIds = user2Groups.Select(x=>x.UserGroupId).Distinct().ToList(); + groupIds = user2Groups.Select(x => x.UserGroupId).Distinct().ToList(); } @@ -467,12 +468,12 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 groups = Database.Fetch(sql) .ToDictionary(x => x.Id, x => x); } - catch(Exception e) + catch (Exception e) { Logger.LogDebug(e, "Couldn't get user groups. This should only happens doing the migration that add new columns to user groups"); sql = SqlContext.Sql() - .Select(x=>x.Id, x=>x.Alias, x=>x.StartContentId, x=>x.StartMediaId) + .Select(x => x.Id, x => x.Alias, x => x.StartContentId, x => x.StartMediaId) .From() .WhereIn(x => x.Id, groupIds); @@ -550,9 +551,9 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 Dictionary> groups2GranularPermissions; try { - groups2GranularPermissions = Database.Fetch(sql) - .GroupBy(x => x.UserGroupKey) - .ToDictionary(x => x.Key, x => x); + groups2GranularPermissions = Database.Fetch(sql) + .GroupBy(x => x.UserGroupKey) + .ToDictionary(x => x.Key, x => x); } catch { @@ -721,12 +722,13 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 // lookup all assigned List? assigned = entity.Groups == null || entity.Groups.Any() == false ? new List() - : Database.Fetch("SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", - new {aliases = entity.Groups.Select(x => x.Alias)}); + : Database.Fetch( + "SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", + new { aliases = entity.Groups.Select(x => x.Alias) }); foreach (UserGroupDto? groupDto in assigned) { - var dto = new User2UserGroupDto {UserGroupId = groupDto.Id, UserId = entity.Id}; + var dto = new User2UserGroupDto { UserGroupId = groupDto.Id, UserId = entity.Id }; Database.Insert(dto); } } @@ -823,8 +825,9 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 if (entity.IsPropertyDirty("StartContentIds") || entity.IsPropertyDirty("StartMediaIds")) { List? assignedStartNodes = - Database.Fetch("SELECT * FROM umbracoUserStartNode WHERE userId = @userId", - new {userId = entity.Id}); + Database.Fetch( + "SELECT * FROM umbracoUserStartNode WHERE userId = @userId", + new { userId = entity.Id }); if (entity.IsPropertyDirty("StartContentIds")) { AddingOrUpdateStartNodes(entity, assignedStartNodes, UserStartNodeDto.StartNodeTypeValue.Content, @@ -843,16 +846,17 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 //lookup all assigned List? assigned = entity.Groups == null || entity.Groups.Any() == false ? new List() - : Database.Fetch("SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", - new {aliases = entity.Groups.Select(x => x.Alias)}); + : Database.Fetch( + "SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", + new { aliases = entity.Groups.Select(x => x.Alias) }); //first delete all // TODO: We could do this a nicer way instead of "Nuke and Pave" - Database.Delete("WHERE UserId = @UserId", new {UserId = entity.Id}); + Database.Delete("WHERE UserId = @UserId", new { UserId = entity.Id }); foreach (UserGroupDto? groupDto in assigned) { - var dto = new User2UserGroupDto {UserGroupId = groupDto.Id, UserId = entity.Id}; + var dto = new User2UserGroupDto { UserGroupId = groupDto.Id, UserId = entity.Id }; Database.Insert(dto); } } @@ -874,15 +878,16 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 var toDelete = assignedIds.Except(entityStartIds).ToArray(); if (toDelete.Length > 0) { - Database.Delete("WHERE UserId = @UserId AND startNode IN (@startNodes)", - new {UserId = entity.Id, startNodes = toDelete}); + Database.Delete( + "WHERE UserId = @UserId AND startNode IN (@startNodes)", + new { UserId = entity.Id, startNodes = toDelete }); } //add the ones not currently in the db var toAdd = entityStartIds.Except(assignedIds).ToArray(); foreach (var i in toAdd) { - var dto = new UserStartNodeDto {StartNode = i, StartNodeType = (int)startNodeType, UserId = entity.Id}; + var dto = new UserStartNodeDto { StartNode = i, StartNodeType = (int)startNodeType, UserId = entity.Id }; Database.Insert(dto); } } @@ -1068,7 +1073,7 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 INNER JOIN umbracoUser2UserGroup ON umbracoUser2UserGroup.userId = umbracoUser.id INNER JOIN umbracoUserGroup ON umbracoUserGroup.id = umbracoUser2UserGroup.userGroupId WHERE umbracoUserGroup.userGroupAlias IN (@userGroups)))"; - filterSql?.Append(subQuery, new {userGroups = includeUserGroups}); + filterSql?.Append(subQuery, new { userGroups = includeUserGroups }); } if (excludeUserGroups != null && excludeUserGroups.Length > 0) @@ -1078,7 +1083,7 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0 INNER JOIN umbracoUser2UserGroup ON umbracoUser2UserGroup.userId = umbracoUser.id INNER JOIN umbracoUserGroup ON umbracoUserGroup.id = umbracoUser2UserGroup.userGroupId WHERE umbracoUserGroup.userGroupAlias IN (@userGroups)))"; - filterSql?.Append(subQuery, new {userGroups = excludeUserGroups}); + filterSql?.Append(subQuery, new { userGroups = excludeUserGroups }); } if (userState != null && userState.Length > 0) diff --git a/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyValueEditor.cs b/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyValueEditor.cs index 60fa7d0889..ffbdacc16a 100644 --- a/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyValueEditor.cs +++ b/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyValueEditor.cs @@ -83,7 +83,7 @@ internal class ImageCropperPropertyValueEditor : DataValueEditor // TODO: core v value = new ImageCropperValue { Src = val.ToString() }; } - var configuration = _dataTypeConfigurationCache.GetConfigurationAs(property.PropertyType.DataTypeKey); + ImageCropperConfiguration? configuration = _dataTypeConfigurationCache.GetConfigurationAs(property.PropertyType.DataTypeKey); if (configuration is not null) { value?.ApplyConfiguration(configuration); diff --git a/src/Umbraco.Infrastructure/PublishedContentQuery.cs b/src/Umbraco.Infrastructure/PublishedContentQuery.cs index e0cc0a97bd..578831252b 100644 --- a/src/Umbraco.Infrastructure/PublishedContentQuery.cs +++ b/src/Umbraco.Infrastructure/PublishedContentQuery.cs @@ -25,8 +25,10 @@ public class PublishedContentQuery : IPublishedContentQuery /// /// Initializes a new instance of the class. /// - public PublishedContentQuery(IPublishedSnapshot publishedSnapshot, - IVariationContextAccessor variationContextAccessor, IExamineManager examineManager) + public PublishedContentQuery( + IPublishedSnapshot publishedSnapshot, + IVariationContextAccessor variationContextAccessor, + IExamineManager examineManager) { _publishedSnapshot = publishedSnapshot ?? throw new ArgumentNullException(nameof(publishedSnapshot)); _variationContextAccessor = variationContextAccessor ?? @@ -331,8 +333,10 @@ public class PublishedContentQuery : IPublishedContentQuery private readonly IVariationContextAccessor _variationContextAccessor; private readonly IEnumerable _wrapped; - public CultureContextualSearchResults(IEnumerable wrapped, - IVariationContextAccessor variationContextAccessor, string culture) + public CultureContextualSearchResults( + IEnumerable wrapped, + IVariationContextAccessor variationContextAccessor, + string culture) { _wrapped = wrapped; _variationContextAccessor = variationContextAccessor; diff --git a/src/Umbraco.Infrastructure/Runtime/FileSystemMainDomLock.cs b/src/Umbraco.Infrastructure/Runtime/FileSystemMainDomLock.cs index 6dcd3ef9b0..61fac260be 100644 --- a/src/Umbraco.Infrastructure/Runtime/FileSystemMainDomLock.cs +++ b/src/Umbraco.Infrastructure/Runtime/FileSystemMainDomLock.cs @@ -71,7 +71,8 @@ internal class FileSystemMainDomLock : IMainDomLock _lockFileStream?.Close(); return Task.FromResult(false); } - } while (stopwatch.ElapsedMilliseconds < millisecondsTimeout); + } + while (stopwatch.ElapsedMilliseconds < millisecondsTimeout); return Task.FromResult(false); } diff --git a/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs b/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs index a3d6456d0b..9576bad10c 100644 --- a/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs +++ b/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs @@ -101,7 +101,8 @@ public class SqlMainDomLock : IMainDomLock db.BeginTransaction(IsolationLevel.Serializable); RecordPersistenceType - result = InsertLockRecord(tempId, + result = InsertLockRecord( + tempId, db); //we change the row to a random Id to signal other MainDom to shutdown if (result == RecordPersistenceType.Insert) { @@ -244,39 +245,43 @@ public class SqlMainDomLock : IMainDomLock using (ExecutionContext.SuppressFlow()) { - return Task.Run(() => - { - try + return Task.Run( + () => { - using IUmbracoDatabase db = _dbFactory.CreateDatabase(); - - var watch = new Stopwatch(); - watch.Start(); - while (true) + try { - // poll very often, we need to take over as fast as we can - // local testing shows the actual query to be executed from client/server is approx 300ms but would change depending on environment/IO - Thread.Sleep(1000); + using IUmbracoDatabase db = _dbFactory.CreateDatabase(); - var acquired = TryAcquire(db, tempId, updatedTempId); - if (acquired.HasValue) + var watch = new Stopwatch(); + watch.Start(); + while (true) { - return acquired.Value; - } + // poll very often, we need to take over as fast as we can + // local testing shows the actual query to be executed from client/server is approx 300ms but would change depending on environment/IO + Thread.Sleep(1000); - if (watch.ElapsedMilliseconds >= millisecondsTimeout) - { - return AcquireWhenMaxWaitTimeElapsed(db); + var acquired = TryAcquire(db, tempId, updatedTempId); + if (acquired.HasValue) + { + return acquired.Value; + } + + if (watch.ElapsedMilliseconds >= millisecondsTimeout) + { + return AcquireWhenMaxWaitTimeElapsed(db); + } } } - } - catch (Exception ex) - { - _logger.LogError(ex, - "An error occurred trying to acquire and waiting for existing SqlMainDomLock to shutdown"); - return false; - } - }, _cancellationTokenSource.Token); + catch (Exception ex) + { + _logger.LogError( + ex, + "An error occurred trying to acquire and waiting for existing SqlMainDomLock " + + "to shutdown"); + return false; + } + }, + _cancellationTokenSource.Token); } } @@ -292,8 +297,9 @@ public class SqlMainDomLock : IMainDomLock transaction = db.GetTransaction(IsolationLevel.Serializable); // the row - List? mainDomRows = db.Fetch("SELECT * FROM umbracoKeyValue WHERE [key] = @key", - new {key = MainDomKey}); + List? mainDomRows = db.Fetch( + "SELECT * FROM umbracoKeyValue WHERE [key] = @key", + new { key = MainDomKey }); if (mainDomRows.Count == 0 || mainDomRows[0].Value == updatedTempId) { @@ -375,15 +381,16 @@ public class SqlMainDomLock : IMainDomLock /// Inserts or updates the key/value row /// private RecordPersistenceType InsertLockRecord(string id, IUmbracoDatabase db) => - db.InsertOrUpdate(new KeyValueDto {Key = MainDomKey, Value = id, UpdateDate = DateTime.Now}); + db.InsertOrUpdate(new KeyValueDto { Key = MainDomKey, Value = id, UpdateDate = DateTime.Now }); /// /// Checks if the DB row value is equals the value /// /// private bool IsMainDomValue(string val, IUmbracoDatabase db) => - db.ExecuteScalar("SELECT COUNT(*) FROM umbracoKeyValue WHERE [key] = @key AND [value] = @val", - new {key = MainDomKey, val}) == 1; + db.ExecuteScalar( + "SELECT COUNT(*) FROM umbracoKeyValue WHERE [key] = @key AND [value] = @val", + new { key = MainDomKey, val }) == 1; #region IDisposable Support @@ -423,13 +430,14 @@ public class SqlMainDomLock : IMainDomLock _logger.LogDebug("Releasing MainDom, updating row, new application is booting."); var count = db.Execute( $"UPDATE umbracoKeyValue SET [value] = [value] + '{UpdatedSuffix}' WHERE [key] = @key", - new {key = MainDomKey}); + new { key = MainDomKey }); } else { _logger.LogDebug("Releasing MainDom, deleting row, application is shutting down."); - var count = db.Execute("DELETE FROM umbracoKeyValue WHERE [key] = @key", - new {key = MainDomKey}); + var count = db.Execute( + "DELETE FROM umbracoKeyValue WHERE [key] = @key", + new { key = MainDomKey }); } } catch (Exception ex) diff --git a/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs b/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs index 97d01a56a1..1abdaa28af 100644 --- a/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs +++ b/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs @@ -159,11 +159,8 @@ namespace Umbraco.Cms.Infrastructure.Scoping /// public IScope DetachScope() { - Scope? ambientScope = AmbientScope; - if (ambientScope == null) - { - throw new InvalidOperationException("There is no ambient scope."); - } + Scope? ambientScope = AmbientScope + ?? throw new InvalidOperationException("There is no ambient scope."); if (ambientScope.Detachable == false) { @@ -389,7 +386,7 @@ namespace Umbraco.Cms.Infrastructure.Scoping bool? scopeFileSystems = null, bool callContext = false, bool autoComplete = false) => - (Cms.Core.Scoping.IScope) CreateScope( + (Cms.Core.Scoping.IScope)CreateScope( isolationLevel, repositoryCacheMode, eventDispatcher, @@ -399,9 +396,12 @@ namespace Umbraco.Cms.Infrastructure.Scoping autoComplete); /// - Core.Scoping.IScope Core.Scoping.IScopeProvider.CreateDetachedScope(IsolationLevel isolationLevel, - RepositoryCacheMode repositoryCacheMode, IEventDispatcher? eventDispatcher, - IScopedNotificationPublisher? scopedNotificationPublisher, bool? scopeFileSystems) => + Core.Scoping.IScope Core.Scoping.IScopeProvider.CreateDetachedScope( + IsolationLevel isolationLevel, + RepositoryCacheMode repositoryCacheMode, + IEventDispatcher? eventDispatcher, + IScopedNotificationPublisher? scopedNotificationPublisher, + bool? scopeFileSystems) => (Core.Scoping.IScope)CreateDetachedScope( isolationLevel, repositoryCacheMode, diff --git a/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs b/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs index 32a554aff0..04210ece14 100644 --- a/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs +++ b/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs @@ -21,8 +21,7 @@ public class BackOfficeClaimsPrincipalFactory : UserClaimsPrincipalFactory userManager, IOptions optionsAccessor, - IOptions backOfficeAuthenticationTypeSettings - ) + IOptions backOfficeAuthenticationTypeSettings) : base(userManager, optionsAccessor) { _backOfficeAuthenticationTypeSettings = backOfficeAuthenticationTypeSettings; diff --git a/src/Umbraco.Infrastructure/Security/MemberUserStore.cs b/src/Umbraco.Infrastructure/Security/MemberUserStore.cs index 708538f49d..51b236fa76 100644 --- a/src/Umbraco.Infrastructure/Security/MemberUserStore.cs +++ b/src/Umbraco.Infrastructure/Security/MemberUserStore.cs @@ -133,7 +133,8 @@ public class MemberUserStore : UmbracoUserStore : UserManager public virtual async Task ChangePasswordWithResetAsync(string userId, string token, string newPassword) { - TUser? user = await FindByIdAsync(userId); - if (user is null) - { - throw new InvalidOperationException("Could not find user"); - } + TUser? user = await FindByIdAsync(userId) + ?? throw new InvalidOperationException("Could not find user"); IdentityResult result = await ResetPasswordAsync(user, token, newPassword); return result; @@ -265,7 +262,7 @@ public abstract class UmbracoUserManager : UserManager)); } - var result = await VerifyPasswordAsync(userPasswordStore, user, password); + PasswordVerificationResult result = await VerifyPasswordAsync(userPasswordStore, user, password); return result == PasswordVerificationResult.Success || result == PasswordVerificationResult.SuccessRehashNeeded; } diff --git a/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj b/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj index cca5a43954..7a95a12304 100644 --- a/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj +++ b/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj @@ -6,8 +6,17 @@ Umbraco.Cms.Infrastructure - - false + + + CS0618,CA1416,SA1117,SA1401,SA1134,CA2017,CS0108,SYSLIB0051,SA1649,CS1998,CS0169,CS0114,IDE0060, + SA1130,IDE1006,CS1066,CS0612,CS1574 + $(DefineConstants);TRACE_SCOPES diff --git a/src/Umbraco.PublishedCache.NuCache/ContentCache.cs b/src/Umbraco.PublishedCache.NuCache/ContentCache.cs index b50a0a71ce..b9390f05d9 100644 --- a/src/Umbraco.PublishedCache.NuCache/ContentCache.cs +++ b/src/Umbraco.PublishedCache.NuCache/ContentCache.cs @@ -72,20 +72,20 @@ public class ContentCache : PublishedCacheBase, IPublishedContentCache, INavigab private IPublishedContent? GetByRouteInternal(bool preview, string route, bool? hideTopLevelNode, string? culture) { - hideTopLevelNode = hideTopLevelNode ?? HideTopLevelNodeFromPath; // default = settings + hideTopLevelNode ??= HideTopLevelNodeFromPath; // default = settings // the route always needs to be lower case because we only store the urlName attribute in lower case route = route.ToLowerInvariant(); var pos = route.IndexOf('/'); - var path = pos == 0 ? route : route.Substring(pos); - var startNodeId = pos == 0 ? 0 : int.Parse(route.Substring(0, pos), CultureInfo.InvariantCulture); + var path = pos == 0 ? route : route[pos..]; + var startNodeId = pos == 0 ? 0 : int.Parse(route[..pos], CultureInfo.InvariantCulture); var parts = path.Split(Constants.CharArrays.ForwardSlash, StringSplitOptions.RemoveEmptyEntries); IPublishedContent? content; - if ((!_globalSettings.ForceCombineUrlPathLeftToRight - && CultureInfo.GetCultureInfo(culture ?? _globalSettings.DefaultUILanguage).TextInfo.IsRightToLeft)) + if (!_globalSettings.ForceCombineUrlPathLeftToRight + && CultureInfo.GetCultureInfo(culture ?? _globalSettings.DefaultUILanguage).TextInfo.IsRightToLeft) { parts = parts.Reverse().ToArray(); } @@ -151,7 +151,7 @@ public class ContentCache : PublishedCacheBase, IPublishedContentCache, INavigab return null; } - hideTopLevelNode = hideTopLevelNode ?? HideTopLevelNodeFromPath; // default = settings + hideTopLevelNode ??= HideTopLevelNodeFromPath; // default = settings // walk up from that node until we hit a node with a domain, // or we reach the content root, collecting URLs in the way @@ -194,8 +194,8 @@ public class ContentCache : PublishedCacheBase, IPublishedContentCache, INavigab } // assemble the route- We only have to reverse for left to right languages - if ((_globalSettings.ForceCombineUrlPathLeftToRight - || !CultureInfo.GetCultureInfo(culture ?? _globalSettings.DefaultUILanguage).TextInfo.IsRightToLeft)) + if (_globalSettings.ForceCombineUrlPathLeftToRight + || !CultureInfo.GetCultureInfo(culture ?? _globalSettings.DefaultUILanguage).TextInfo.IsRightToLeft) { pathParts.Reverse(); } @@ -237,11 +237,9 @@ public class ContentCache : PublishedCacheBase, IPublishedContentCache, INavigab // that's the way it works pre-4.10 and we try to be backward compat for the time being if (content.Parent == null) { - IPublishedContent? rootNode = GetByRoute(preview, "/", true); - if (rootNode == null) - { - throw new Exception("Failed to get node at /. This might be because you're trying to publish a variant, with no domains setup"); - } + IPublishedContent? rootNode = GetByRoute(preview, "/", true) + ?? throw new Exception("Failed to get node at /. This might be because you're " + + "trying to publish a variant, with no domains setup"); // remove only if we're the default node if (rootNode.Id == content.Id) @@ -269,11 +267,10 @@ public class ContentCache : PublishedCacheBase, IPublishedContentCache, INavigab public override IPublishedContent? GetById(bool preview, Udi contentId) { - var guidUdi = contentId as GuidUdi; - if (guidUdi == null) - { - throw new ArgumentException($"Udi must be of type {typeof(GuidUdi).Name}.", nameof(contentId)); - } + GuidUdi guidUdi = contentId as GuidUdi + ?? throw new ArgumentException( + $"Udi must be of type {typeof(GuidUdi).Name}.", + nameof(contentId)); if (guidUdi.EntityType != Constants.UdiEntityType.Document) { @@ -299,10 +296,7 @@ public class ContentCache : PublishedCacheBase, IPublishedContentCache, INavigab public override IEnumerable GetAtRoot(bool preview, string? culture = null) { // handle context culture for variant - if (culture == null) - { - culture = _variationContextAccessor?.VariationContext?.Culture ?? string.Empty; - } + culture ??= _variationContextAccessor?.VariationContext?.Culture ?? string.Empty; // _snapshot.GetAtRoot() returns all ContentNode at root // both .Draft and .Published cannot be null at the same time diff --git a/src/Umbraco.PublishedCache.NuCache/ContentStore.cs b/src/Umbraco.PublishedCache.NuCache/ContentStore.cs index 0230032dc2..e0ec321385 100644 --- a/src/Umbraco.PublishedCache.NuCache/ContentStore.cs +++ b/src/Umbraco.PublishedCache.NuCache/ContentStore.cs @@ -495,11 +495,7 @@ public class ContentStore private void RegisterChange(int id, ContentNodeKit kit) { - if (_wchanges == null) - { - _wchanges = new List>(); - } - + _wchanges ??= new List>(); _wchanges.Add(new KeyValuePair(id, kit)); } @@ -630,7 +626,7 @@ public class ContentStore IReadOnlyCollection refreshedTypesA = refreshedTypes ?? Array.Empty(); var refreshedIdsA = refreshedTypesA.Select(x => x.Id).ToList(); - kits = kits ?? Array.Empty(); + kits ??= Array.Empty(); if (kits.Count == 0 && refreshedIdsA.Count == 0 && removedIdsA.Count == 0) { @@ -1519,18 +1515,15 @@ public class ContentStore /// private void AddTreeNodeLocked(ContentNode content, LinkedNode? parentLink = null) { - parentLink = parentLink ?? GetRequiredParentLink(content, null); + parentLink ??= GetRequiredParentLink(content, null); - ContentNode? parent = parentLink.Value; - - // We are doing a null check here but this should no longer be possible because we have a null check in BuildKit - // for the parent.Value property and we'll output a warning. However I'll leave this additional null check in place. - // see https://github.com/umbraco/Umbraco-CMS/issues/7868 - if (parent == null) - { - throw new PanicException( - $"A null Value was returned on the {nameof(parentLink)} LinkedNode with id={content.ParentContentId}, potentially your database paths are corrupted."); - } + ContentNode? parent = parentLink.Value + // We are doing a null check here but this should no longer be possible because we have a null check in BuildKit + // for the parent.Value property and we'll output a warning. However I'll leave this additional null check in place. + // see https://github.com/umbraco/Umbraco-CMS/issues/7868 + ?? throw new PanicException( + $"A null Value was returned on the {nameof(parentLink)} LinkedNode with " + + $"id={content.ParentContentId}, potentially your database paths are corrupted."); // if parent has no children, clone parent + add as first child if (parent.FirstChildContentId < 0) @@ -2071,7 +2064,7 @@ public class ContentStore } } - internal TestHelper Test => _unitTesting ?? (_unitTesting = new TestHelper(this)); + internal TestHelper Test => _unitTesting ??= new TestHelper(this); #endregion } diff --git a/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.ContentDataSerializer.cs b/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.ContentDataSerializer.cs index f81ff21a07..60440f0d91 100644 --- a/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.ContentDataSerializer.cs +++ b/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.ContentDataSerializer.cs @@ -7,17 +7,14 @@ namespace Umbraco.Cms.Infrastructure.PublishedCache.DataSource; ///
public class ContentDataSerializer : ISerializer { - private static readonly DictionaryOfPropertyDataSerializer S_defaultPropertiesSerializer = new(); - private static readonly DictionaryOfCultureVariationSerializer S_defaultCultureVariationsSerializer = new(); + private static readonly DictionaryOfPropertyDataSerializer _defaultPropertiesSerializer = new(); + private static readonly DictionaryOfCultureVariationSerializer _defaultCultureVariationsSerializer = new(); private readonly IDictionaryOfPropertyDataSerializer? _dictionaryOfPropertyDataSerializer; public ContentDataSerializer(IDictionaryOfPropertyDataSerializer? dictionaryOfPropertyDataSerializer = null) { _dictionaryOfPropertyDataSerializer = dictionaryOfPropertyDataSerializer; - if (_dictionaryOfPropertyDataSerializer == null) - { - _dictionaryOfPropertyDataSerializer = S_defaultPropertiesSerializer; - } + _dictionaryOfPropertyDataSerializer ??= _defaultPropertiesSerializer; } public ContentData ReadFrom(Stream stream) @@ -33,7 +30,7 @@ public class ContentDataSerializer : ISerializer properties = _dictionaryOfPropertyDataSerializer?.ReadFrom(stream); // TODO: We don't want to allocate empty arrays IReadOnlyDictionary cultureInfos = - S_defaultCultureVariationsSerializer.ReadFrom(stream); // TODO: We don't want to allocate empty arrays + _defaultCultureVariationsSerializer.ReadFrom(stream); // TODO: We don't want to allocate empty arrays var cachedTemplateId = templateId == 0 ? (int?)null : templateId; return new ContentData(name, urlSegment, versionId, versionDate, writerId, cachedTemplateId, published, properties, cultureInfos); } @@ -48,6 +45,6 @@ public class ContentDataSerializer : ISerializer PrimitiveSerializer.Int32.WriteTo(value.WriterId, stream); PrimitiveSerializer.Int32.WriteTo(value.TemplateId ?? 0, stream); _dictionaryOfPropertyDataSerializer?.WriteTo(value.Properties, stream); - S_defaultCultureVariationsSerializer.WriteTo(value.CultureInfos, stream); + _defaultCultureVariationsSerializer.WriteTo(value.CultureInfos, stream); } } diff --git a/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.ContentNodeKitSerializer.cs b/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.ContentNodeKitSerializer.cs index fbba6a2b17..d4782b1c4a 100644 --- a/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.ContentNodeKitSerializer.cs +++ b/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.ContentNodeKitSerializer.cs @@ -4,16 +4,13 @@ namespace Umbraco.Cms.Infrastructure.PublishedCache.DataSource; internal class ContentNodeKitSerializer : ISerializer { - private static readonly ContentDataSerializer S_defaultDataSerializer = new(); + private static readonly ContentDataSerializer _defaultDataSerializer = new(); private readonly ContentDataSerializer? _contentDataSerializer; public ContentNodeKitSerializer(ContentDataSerializer? contentDataSerializer = null) { _contentDataSerializer = contentDataSerializer; - if (_contentDataSerializer == null) - { - _contentDataSerializer = S_defaultDataSerializer; - } + _contentDataSerializer ??= _defaultDataSerializer; } // static readonly ListOfIntSerializer ChildContentIdsSerializer = new ListOfIntSerializer(); diff --git a/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.DictionaryOfPropertyDataSerializer.cs b/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.DictionaryOfPropertyDataSerializer.cs index d820a3f4a2..e484635cdf 100644 --- a/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.DictionaryOfPropertyDataSerializer.cs +++ b/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.DictionaryOfPropertyDataSerializer.cs @@ -8,7 +8,7 @@ namespace Umbraco.Cms.Infrastructure.PublishedCache.DataSource; internal class DictionaryOfPropertyDataSerializer : SerializerBase, ISerializer>, IDictionaryOfPropertyDataSerializer { - private static readonly PropertyData[] Empty = Array.Empty(); + private static readonly PropertyData[] _empty = Array.Empty(); public IDictionary ReadFrom(Stream stream) { @@ -26,7 +26,7 @@ internal class DictionaryOfPropertyDataSerializer : SerializerBase, ISerializer< var vcount = PrimitiveSerializer.Int32.ReadFrom(stream); if (vcount == 0) { - dict[key] = Empty; + dict[key] = _empty; continue; } diff --git a/src/Umbraco.PublishedCache.NuCache/Umbraco.PublishedCache.NuCache.csproj b/src/Umbraco.PublishedCache.NuCache/Umbraco.PublishedCache.NuCache.csproj index 04986712c8..81bfc45cef 100644 --- a/src/Umbraco.PublishedCache.NuCache/Umbraco.PublishedCache.NuCache.csproj +++ b/src/Umbraco.PublishedCache.NuCache/Umbraco.PublishedCache.NuCache.csproj @@ -6,8 +6,10 @@ Umbraco.Cms.Infrastructure.PublishedCache - - false + + SA1117,SA1401,SA1134,SA1649,CS0618,SA1111 diff --git a/src/Umbraco.Web.Common/Logging/RegisteredReloadableLogger.cs b/src/Umbraco.Web.Common/Logging/RegisteredReloadableLogger.cs index 63a34ca73f..5d9b398678 100644 --- a/src/Umbraco.Web.Common/Logging/RegisteredReloadableLogger.cs +++ b/src/Umbraco.Web.Common/Logging/RegisteredReloadableLogger.cs @@ -11,8 +11,8 @@ namespace Umbraco.Cms.Web.Common.Logging; /// internal class RegisteredReloadableLogger { - private static readonly object FrozenLock = new(); - private static bool frozen; + private static readonly object _frozenLock = new(); + private static bool _frozen; private readonly ReloadableLogger _logger; public RegisteredReloadableLogger(ReloadableLogger? logger) => @@ -22,9 +22,9 @@ internal class RegisteredReloadableLogger public void Reload(Func cfg) { - lock (FrozenLock) + lock (_frozenLock) { - if (frozen) + if (_frozen) { Logger.Debug("ReloadableLogger has already been frozen, unable to reload, NOOP."); return; @@ -33,7 +33,7 @@ internal class RegisteredReloadableLogger _logger.Reload(cfg); _logger.Freeze(); - frozen = true; + _frozen = true; } } } diff --git a/src/Umbraco.Web.Common/Middleware/UmbracoRequestMiddleware.cs b/src/Umbraco.Web.Common/Middleware/UmbracoRequestMiddleware.cs index a796e26ec2..38d6fae93a 100644 --- a/src/Umbraco.Web.Common/Middleware/UmbracoRequestMiddleware.cs +++ b/src/Umbraco.Web.Common/Middleware/UmbracoRequestMiddleware.cs @@ -188,7 +188,11 @@ internal class UmbracoRequestMiddleware : IMiddleware } #pragma warning disable IDE0044 // Add readonly modifier +#pragma warning disable IDE1006 // Naming Styles +#pragma warning disable CS0169 // Unused fields private static bool s_firstBackOfficeRequest; private static bool s_firstBackOfficeReqestFlag; +#pragma warning restore IDE1006 // Naming Styles #pragma warning restore IDE0044 // Add readonly modifier +#pragma warning restore CS0169 // Unused fields } diff --git a/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/ChecksumValidator.cs b/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/ChecksumValidator.cs index 654766d9b1..da210ee255 100644 --- a/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/ChecksumValidator.cs +++ b/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/ChecksumValidator.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; @@ -25,7 +25,7 @@ internal static class ChecksumValidator // // Other files (view imports) may or may not have existed at the time of compilation, // so we may not have checksums for them. - var checksums = item.GetChecksumMetadata(); + IReadOnlyList checksums = item.GetChecksumMetadata(); return checksums.Any(c => string.Equals(item.Identifier, c.Identifier, StringComparison.OrdinalIgnoreCase)); } @@ -43,7 +43,7 @@ internal static class ChecksumValidator throw new ArgumentNullException(nameof(item)); } - var checksums = item.GetChecksumMetadata(); + IReadOnlyList checksums = item.GetChecksumMetadata(); // The checksum that matches 'Item.Identity' in this list is significant. That represents the main file. // @@ -53,7 +53,7 @@ internal static class ChecksumValidator // // The presence of the main file with the same content is a very strong signal that you're in a // development scenario. - var primaryChecksum = checksums + IRazorSourceChecksumMetadata? primaryChecksum = checksums .FirstOrDefault(c => string.Equals(item.Identifier, c.Identifier, StringComparison.OrdinalIgnoreCase)); if (primaryChecksum == null) { @@ -61,7 +61,7 @@ internal static class ChecksumValidator return true; } - var projectItem = fileSystem.GetItem(primaryChecksum.Identifier, fileKind: null); + RazorProjectItem projectItem = fileSystem.GetItem(primaryChecksum.Identifier, fileKind: null); if (!projectItem.Exists) { // Main file doesn't exist - assume valid. @@ -78,14 +78,14 @@ internal static class ChecksumValidator for (var i = 0; i < checksums.Count; i++) { - var checksum = checksums[i]; + IRazorSourceChecksumMetadata checksum = checksums[i]; if (string.Equals(item.Identifier, checksum.Identifier, StringComparison.OrdinalIgnoreCase)) { // Ignore primary checksum on this pass. continue; } - var importItem = fileSystem.GetItem(checksum.Identifier, fileKind: null); + RazorProjectItem importItem = fileSystem.GetItem(checksum.Identifier, fileKind: null); if (!importItem.Exists) { // Import file doesn't exist - assume invalid. @@ -114,7 +114,7 @@ internal static class ChecksumValidator for (var i = 0; i < bytes.Length; i++) { var text = bytes[i].ToString("x2", CultureInfo.InvariantCulture); - if (checksum[i * 2] != text[0] || checksum[i * 2 + 1] != text[1]) + if (checksum[i * 2] != text[0] || checksum[(i * 2) + 1] != text[1]) { return false; } diff --git a/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/CollectibleRuntimeViewCompiler.cs b/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/CollectibleRuntimeViewCompiler.cs index 3c934231f3..4cb77897b6 100644 --- a/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/CollectibleRuntimeViewCompiler.cs +++ b/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/CollectibleRuntimeViewCompiler.cs @@ -1,4 +1,4 @@ -using System.Collections.Concurrent; +using System.Collections.Concurrent; using System.Diagnostics; using System.Reflection; using System.Text; @@ -40,29 +40,14 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler CompilationOptionsProvider compilationOptionsProvider, InMemoryAssemblyLoadContextManager loadContextManager) { - if (fileProvider == null) - { - throw new ArgumentNullException(nameof(fileProvider)); - } - - if (projectEngine == null) - { - throw new ArgumentNullException(nameof(projectEngine)); - } - if (precompiledViews == null) { throw new ArgumentNullException(nameof(precompiledViews)); } - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - _fileProvider = fileProvider; - _projectEngine = projectEngine; - _logger = logger; + _fileProvider = fileProvider ?? throw new ArgumentNullException(nameof(fileProvider)); + _projectEngine = projectEngine ?? throw new ArgumentNullException(nameof(projectEngine)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _referenceManager = referenceManager; _compilationOptionsProvider = compilationOptionsProvider; _loadContextManager = loadContextManager; @@ -81,7 +66,7 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler precompiledViews.Count, StringComparer.OrdinalIgnoreCase); - foreach (var precompiledView in precompiledViews) + foreach (CompiledViewDescriptor precompiledView in precompiledViews) { _logger.LogDebug("Initializing Razor view compiler with compiled view: '{ViewName}'", precompiledView.RelativePath); if (!_precompiledViews.ContainsKey(precompiledView.RelativePath)) @@ -117,7 +102,7 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler // Attempt to lookup the cache entry using the passed in path. This will succeed if the path is already // normalized and a cache entry exists. - if (_cache.TryGetValue>(relativePath, out var cachedResult) && cachedResult is not null) + if (_cache.TryGetValue>(relativePath, out Task? cachedResult) && cachedResult is not null) { return cachedResult; } @@ -145,12 +130,12 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler lock (_cacheLock) { // Double-checked locking to handle a possible race. - if (_cache.TryGetValue>(normalizedPath, out var result) && result is not null) + if (_cache.TryGetValue>(normalizedPath, out Task? result) && result is not null) { return result; } - if (_precompiledViews.TryGetValue(normalizedPath, out var precompiledView)) + if (_precompiledViews.TryGetValue(normalizedPath, out CompiledViewDescriptor? precompiledView)) { _logger.LogTrace("Located compiled view for view at path '{Path}'", normalizedPath); item = CreatePrecompiledWorkItem(normalizedPath, precompiledView); @@ -191,7 +176,7 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler Debug.Assert(taskSource != null); if (item.Descriptor?.Item != null && - ChecksumValidator.IsItemValid(_projectEngine.FileSystem, item.Descriptor.Item) ) + ChecksumValidator.IsItemValid(_projectEngine.FileSystem, item.Descriptor.Item)) { // If the item has checksums to validate, we should also have a precompiled view. Debug.Assert(item.Descriptor != null); @@ -203,7 +188,7 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler _logger.LogTrace("Invalidating compiled view at path '{Path}' with a file since the checksum did not match", item.NormalizedPath); try { - var descriptor = CompileAndEmit(normalizedPath); + CompiledViewDescriptor descriptor = CompileAndEmit(normalizedPath); descriptor.ExpirationTokens = cacheEntryOptions.ExpirationTokens; taskSource.SetResult(descriptor); } @@ -269,7 +254,7 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler _fileProvider.Watch(normalizedPath), }; - var projectItem = _projectEngine.FileSystem.GetItem(normalizedPath, fileKind: null); + RazorProjectItem projectItem = _projectEngine.FileSystem.GetItem(normalizedPath, fileKind: null); if (!projectItem.Exists) { _logger.LogTrace("Could not find a file for view at path '{Path}'", normalizedPath); @@ -307,7 +292,7 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler private IList GetExpirationTokens(CompiledViewDescriptor precompiledView) { - var checksums = precompiledView.Item.GetChecksumMetadata(); + IReadOnlyList checksums = precompiledView.Item.GetChecksumMetadata(); var expirationTokens = new List(checksums.Count); for (var i = 0; i < checksums.Count; i++) @@ -324,10 +309,10 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler { // OK this means we can do compilation. For now let's just identify the other files we need to watch // so we can create the cache entry. Compilation will happen after we release the lock. - var importFeature = _projectEngine.ProjectFeatures.OfType().ToArray(); - foreach (var feature in importFeature) + IImportProjectFeature[] importFeature = _projectEngine.ProjectFeatures.OfType().ToArray(); + foreach (IImportProjectFeature feature in importFeature) { - foreach (var file in feature.GetImports(projectItem)) + foreach (RazorProjectItem? file in feature.GetImports(projectItem)) { if (file.FilePath != null) { @@ -339,9 +324,9 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler protected virtual CompiledViewDescriptor CompileAndEmit(string relativePath) { - var projectItem = _projectEngine.FileSystem.GetItem(relativePath, fileKind: null); - var codeDocument = _projectEngine.Process(projectItem); - var cSharpDocument = codeDocument.GetCSharpDocument(); + RazorProjectItem projectItem = _projectEngine.FileSystem.GetItem(relativePath, fileKind: null); + RazorCodeDocument codeDocument = _projectEngine.Process(projectItem); + RazorCSharpDocument cSharpDocument = codeDocument.GetCSharpDocument(); if (cSharpDocument.Diagnostics.Count > 0) { @@ -350,11 +335,11 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler cSharpDocument.Diagnostics); } - var assembly = CompileAndEmit(codeDocument, cSharpDocument.GeneratedCode); + Assembly assembly = CompileAndEmit(codeDocument, cSharpDocument.GeneratedCode); // Anything we compile from source will use Razor 2.1 and so should have the new metadata. var loader = new RazorCompiledItemLoader(); - var item = loader.LoadItems(assembly).Single(); + RazorCompiledItem item = loader.LoadItems(assembly).Single(); return new CompiledViewDescriptor(item); } @@ -372,7 +357,7 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler using (var assemblyStream = new MemoryStream()) using (MemoryStream? pdbStream = emitPdbFile ? new MemoryStream() : null) { - var result = compilation.Emit( + EmitResult result = compilation.Emit( assemblyStream, pdbStream, options: _compilationOptionsProvider.EmitOptions); @@ -480,7 +465,7 @@ internal class CollectibleRuntimeViewCompiler : IViewCompiler return string.Create(length, (path, addLeadingSlash), (span, tuple) => { - var (pathValue, addLeadingSlashValue) = tuple; + (string pathValue, bool addLeadingSlashValue) = tuple; var spanIndex = 0; if (addLeadingSlashValue) diff --git a/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/UmbracoViewCompilerProvider.cs b/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/UmbracoViewCompilerProvider.cs index f981402456..2c4bfe0a33 100644 --- a/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/UmbracoViewCompilerProvider.cs +++ b/src/Umbraco.Web.Common/ModelsBuilder/InMemoryAuto/UmbracoViewCompilerProvider.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore.Mvc.ApplicationParts; +using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Razor.Compilation; using Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation; using Microsoft.AspNetCore.Razor.Language; @@ -73,7 +73,7 @@ internal class UmbracoViewCompilerProvider : IViewCompilerProvider private static IFileProvider GetCompositeFileProvider(MvcRazorRuntimeCompilationOptions options) { - var fileProviders = options.FileProviders; + IList fileProviders = options.FileProviders; if (fileProviders.Count == 0) { throw new PanicException(); diff --git a/src/Umbraco.Web.Common/Profiler/WebProfiler.cs b/src/Umbraco.Web.Common/Profiler/WebProfiler.cs index bb4066acab..407001b837 100644 --- a/src/Umbraco.Web.Common/Profiler/WebProfiler.cs +++ b/src/Umbraco.Web.Common/Profiler/WebProfiler.cs @@ -125,7 +125,7 @@ public class WebProfiler : IProfiler return false; } - var miniprofilerOptions = _httpContextAccessor.HttpContext?.RequestServices?.GetService>(); + IOptions? miniprofilerOptions = _httpContextAccessor.HttpContext?.RequestServices?.GetService>(); if (miniprofilerOptions is not null && miniprofilerOptions.Value.IgnoredPaths.Contains(request.Path)) { return false; diff --git a/src/Umbraco.Web.Common/Security/MemberManager.cs b/src/Umbraco.Web.Common/Security/MemberManager.cs index 46d07deb88..fce0ce74f1 100644 --- a/src/Umbraco.Web.Common/Security/MemberManager.cs +++ b/src/Umbraco.Web.Common/Security/MemberManager.cs @@ -55,20 +55,9 @@ public class MemberManager : UmbracoUserManager? allowGroups = null, IEnumerable? allowMembers = null) { - if (allowTypes == null) - { - allowTypes = Enumerable.Empty(); - } - - if (allowGroups == null) - { - allowGroups = Enumerable.Empty(); - } - - if (allowMembers == null) - { - allowMembers = Enumerable.Empty(); - } + allowTypes ??= Enumerable.Empty(); + allowGroups ??= Enumerable.Empty(); + allowMembers ??= Enumerable.Empty(); // Allow by default var allowAction = true; diff --git a/src/Umbraco.Web.Common/Umbraco.Web.Common.csproj b/src/Umbraco.Web.Common/Umbraco.Web.Common.csproj index 6de2cd1278..7258f44208 100644 --- a/src/Umbraco.Web.Common/Umbraco.Web.Common.csproj +++ b/src/Umbraco.Web.Common/Umbraco.Web.Common.csproj @@ -6,8 +6,14 @@ Umbraco.Cms.Web.Common - - false + + + SA1117,SA1401,SA1134,ASP0019,CS0618,IDE0040,SA1400,SA1405,SYSLIB0051,CS0419,CS1574,SA1649 + diff --git a/src/Umbraco.Web.Website/Umbraco.Web.Website.csproj b/src/Umbraco.Web.Website/Umbraco.Web.Website.csproj index 0e8d475725..ec92aa675d 100644 --- a/src/Umbraco.Web.Website/Umbraco.Web.Website.csproj +++ b/src/Umbraco.Web.Website/Umbraco.Web.Website.csproj @@ -7,9 +7,9 @@ + [CS0618] handle member obsolete appropriately, [SA1401] make fields private, + [SA1649] update file name, and remove this override, [IDE1006] fix naming rule violation, + and remove these overrides --> ASP0019,CS0618,SA1401,SA1649,IDE0270,IDE1006 diff --git a/tests/Umbraco.Tests.Benchmarks/LoggerAllocationBenchmark.cs b/tests/Umbraco.Tests.Benchmarks/LoggerAllocationBenchmark.cs index 7a69af3385..8ccc68f692 100644 --- a/tests/Umbraco.Tests.Benchmarks/LoggerAllocationBenchmark.cs +++ b/tests/Umbraco.Tests.Benchmarks/LoggerAllocationBenchmark.cs @@ -7,16 +7,19 @@ namespace Umbraco.Tests.Benchmarks; [QuickRunWithMemoryDiagnoserConfig] public class LoggerAllocationBenchmark { - private readonly string rawQuery = ""; - private readonly int totalItemCount; + private readonly string _rawQuery = string.Empty; + private readonly int _totalItemCount; [Benchmark(Baseline = true)] public void Baseline() { for (var i = 0; i < 1000; i++) { - OriginalDebugSignature(GetType(), "DeleteFromIndex with query: {Query} (found {TotalItems} results)", - rawQuery, totalItemCount); + OriginalDebugSignature( + GetType(), + "DeleteFromIndex with query: {Query} (found {TotalItems} results)", + _rawQuery, + _totalItemCount); } } @@ -25,8 +28,11 @@ public class LoggerAllocationBenchmark { for (var i = 0; i < 1000; i++) { - NewDebugSignature(GetType(), "DeleteFromIndex with query: {Query} (found {TotalItems} results)", rawQuery, - totalItemCount); + NewDebugSignature( + GetType(), + "DeleteFromIndex with query: {Query} (found {TotalItems} results)", + _rawQuery, + _totalItemCount); } } diff --git a/tests/Umbraco.Tests.Benchmarks/StringReplaceFirstBenchmarks.cs b/tests/Umbraco.Tests.Benchmarks/StringReplaceFirstBenchmarks.cs index e5c6c6b2b5..e0c6490d5b 100644 --- a/tests/Umbraco.Tests.Benchmarks/StringReplaceFirstBenchmarks.cs +++ b/tests/Umbraco.Tests.Benchmarks/StringReplaceFirstBenchmarks.cs @@ -12,7 +12,8 @@ namespace Umbraco.Tests.Benchmarks; [QuickRunWithMemoryDiagnoserConfig] public class StringReplaceFirstBenchmarks { - [Params("Test string", + [Params( + "Test string", "This is a test string that contains multiple test entries", "This is a string where the searched value is very far back. The system needs to go through all of this code before it reaches the test")] public string Text { get; set; } @@ -36,7 +37,7 @@ public class StringReplaceFirstBenchmarks return Text; } - return Text.Substring(0, pos) + Replace + Text.Substring(pos + Search.Length); + return Text[..pos] + Replace + Text[(pos + Search.Length)..]; } [Benchmark(Description = "Replace first w/ span")] diff --git a/tests/Umbraco.Tests.Benchmarks/Umbraco.Tests.Benchmarks.csproj b/tests/Umbraco.Tests.Benchmarks/Umbraco.Tests.Benchmarks.csproj index 5b8f2b3b56..1c3130e0f8 100644 --- a/tests/Umbraco.Tests.Benchmarks/Umbraco.Tests.Benchmarks.csproj +++ b/tests/Umbraco.Tests.Benchmarks/Umbraco.Tests.Benchmarks.csproj @@ -6,8 +6,9 @@ false - - false + + SYSLIB0021,IDE0060,CS0618,CS0649 diff --git a/tests/Umbraco.Tests.Common/TestHelperBase.cs b/tests/Umbraco.Tests.Common/TestHelperBase.cs index 072e20635a..67da964bca 100644 --- a/tests/Umbraco.Tests.Common/TestHelperBase.cs +++ b/tests/Umbraco.Tests.Common/TestHelperBase.cs @@ -183,10 +183,7 @@ public abstract class TestHelperBase { get { - if (_uriUtility == null) - { - _uriUtility = new UriUtility(GetHostingEnvironment()); - } + _uriUtility ??= new UriUtility(GetHostingEnvironment()); return _uriUtility; } diff --git a/tests/Umbraco.Tests.Common/Umbraco.Tests.Common.csproj b/tests/Umbraco.Tests.Common/Umbraco.Tests.Common.csproj index 24e0dce808..d89fa7bb10 100644 --- a/tests/Umbraco.Tests.Common/Umbraco.Tests.Common.csproj +++ b/tests/Umbraco.Tests.Common/Umbraco.Tests.Common.csproj @@ -8,8 +8,9 @@ $(BaseEnablePackageValidation) - - false + + CS1998,CS0618,SYSLIB0012 diff --git a/tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs b/tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs index bc83d90a46..043ed9a13a 100644 --- a/tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs +++ b/tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs @@ -67,7 +67,8 @@ public abstract class ManagementApiTest : UmbracoTestServerTestBase } else { - user = (await userService.CreateAsync(Constants.Security.SuperUserKey, + user = (await userService.CreateAsync( + Constants.Security.SuperUserKey, new UserCreateModel() { Email = username, diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/IO/ShadowFileSystemTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/IO/ShadowFileSystemTests.cs index a60a90cee2..73f83fe8fb 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/IO/ShadowFileSystemTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/IO/ShadowFileSystemTests.cs @@ -183,7 +183,7 @@ public class ShadowFileSystemTests : UmbracoIntegrationTest File.WriteAllText(path + "/ShadowTests/sub/f1.txt", "foo"); File.WriteAllText(path + "/ShadowTests/sub/f2.txt", "foo"); - var files = fs.GetFiles(""); + var files = fs.GetFiles(string.Empty); Assert.AreEqual(0, files.Count()); files = fs.GetFiles("sub"); @@ -407,7 +407,7 @@ public class ShadowFileSystemTests : UmbracoIntegrationTest { IsScoped = () => scopedFileSystems }; - var shadowPath = $"x/{Guid.NewGuid().ToString("N").Substring(0, 6)}"; + var shadowPath = $"x/{Guid.NewGuid().ToString("N")[..6]}"; var sw = (ShadowWrapper)fileSystems.CreateShadowWrapper(phy, shadowPath); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) @@ -523,7 +523,7 @@ public class ShadowFileSystemTests : UmbracoIntegrationTest { IsScoped = () => scopedFileSystems }; - var shadowPath = $"x/{Guid.NewGuid().ToString("N").Substring(0, 6)}"; + var shadowPath = $"x/{Guid.NewGuid().ToString("N")[..6]}"; var sw = fileSystems.CreateShadowWrapper(phy, shadowPath); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) @@ -592,7 +592,7 @@ public class ShadowFileSystemTests : UmbracoIntegrationTest { IsScoped = () => scopedFileSystems }; - var shadowPath = $"x/{Guid.NewGuid().ToString("N").Substring(0, 6)}"; + var shadowPath = $"x/{Guid.NewGuid().ToString("N")[..6]}"; var sw = fileSystems.CreateShadowWrapper(phy, shadowPath); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/RuntimeStateTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/RuntimeStateTests.cs index cd18e58563..208b7b11e4 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/RuntimeStateTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/RuntimeStateTests.cs @@ -88,7 +88,8 @@ public class RuntimeStateTests : UmbracoIntegrationTest MediaUrlGeneratorCollection mediaUrlGenerators, IShortStringHelper shortStringHelper, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, - IMigrationContext context, IOptions options) + IMigrationContext context, + IOptions options) : base(packagingService, mediaService, mediaFileManager, mediaUrlGenerators, shortStringHelper, contentTypeBaseServiceProvider, context, options) { } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentServiceTests.cs index 646fbbd51c..ae19e600d5 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentServiceTests.cs @@ -640,7 +640,8 @@ public class ContentServiceTests : UmbracoIntegrationTestWithContent // and proper values // first, the current (edited) version, with edited and published versions Assert.AreEqual("John Farr", versions[0].GetValue("author")); // current version has the edited value - Assert.AreEqual("Bob Hope", + Assert.AreEqual( + "Bob Hope", versions[0].GetValue("author", published: true)); // and the published published value // then, the current (published) version, with edited == published diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentTypeEditingServiceTests.Create.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentTypeEditingServiceTests.Create.cs index 077a8add22..da23e87857 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentTypeEditingServiceTests.Create.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentTypeEditingServiceTests.Create.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.ContentTypeEditing; @@ -252,8 +252,7 @@ public partial class ContentTypeEditingServiceTests CompositionType = CompositionType.Composition, Key = compositionType.Key, }, - } - ); + }); var result = await ContentTypeEditingService.CreateAsync(createModel, Constants.Security.SuperUserKey); Assert.IsTrue(result.Success); @@ -295,8 +294,7 @@ public partial class ContentTypeEditingServiceTests compositions: new[] { new Composition { CompositionType = CompositionType.Composition, Key = compositionType.Key, }, - } - ); + }); var tab = ContentTypePropertyContainerModel("Composition Tab", type: TabContainerType); var group = ContentTypePropertyContainerModel("Composition Group", type: GroupContainerType); @@ -866,8 +864,7 @@ public partial class ContentTypeEditingServiceTests compositions: new[] { new Composition { CompositionType = CompositionType.Composition, Key = compositionType.Key, }, - } - ); + }); // this is invalid; the model should not contain the composition container definitions (they will be resolved by ContentTypeEditingService) createModel.Containers = new[] { compositionContainer }; @@ -901,8 +898,7 @@ public partial class ContentTypeEditingServiceTests compositions: new[] { new Composition { CompositionType = CompositionType.Composition, Key = compositionType.Key, }, - } - ); + }); // this is invalid; cannot reuse the container key var container = ContentTypePropertyContainerModel("My Group", type: GroupContainerType, key: compositionContainer.Key); @@ -954,8 +950,7 @@ public partial class ContentTypeEditingServiceTests compositions: new[] { new Composition { CompositionType = CompositionType.Composition, Key = compositionType.Key, }, - } - ); + }); // this is invalid; cannot add properties to non-existing containers var property = ContentTypePropertyTypeModel("My Property", "myProperty", containerKey: Guid.NewGuid()); @@ -1008,8 +1003,7 @@ public partial class ContentTypeEditingServiceTests compositions: new[] { new Composition { CompositionType = CompositionType.Composition, Key = compositionType.Key, }, - } - ); + }); // this is invalid; cannot add a property on a container that belongs to the composition (the container must be duplicated to the content type itself) var property = ContentTypePropertyTypeModel("My Property", "myProperty", containerKey: compositionContainer.Key); @@ -1043,8 +1037,7 @@ public partial class ContentTypeEditingServiceTests compositions: new[] { new Composition { CompositionType = CompositionType.Composition, Key = compositionType.Key, }, - } - ); + }); // this is invalid; cannot create a new container within a parent container that belongs to the composition (the parent container must be duplicated to the content type itself) var container = ContentTypePropertyContainerModel("My Group", type: GroupContainerType); @@ -1079,8 +1072,7 @@ public partial class ContentTypeEditingServiceTests compositions: new[] { new Composition { CompositionType = CompositionType.Composition, Key = compositionType.Key, }, - } - ); + }); var result = await ContentTypeEditingService.CreateAsync(createModel, Constants.Security.SuperUserKey); Assert.IsFalse(result.Success); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ElementSwitchValidatorTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ElementSwitchValidatorTests.cs index 0b7ebd84c9..d72630a52b 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ElementSwitchValidatorTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ElementSwitchValidatorTests.cs @@ -37,13 +37,29 @@ public class ElementSwitchValidatorTests : UmbracoIntegrationTest [TestCase(new[] { false, false }, 0, true, true, TestName = "E InValid Child")] [TestCase(new[] { true, true }, 1, false, false, TestName = "D InValid Parent")] [TestCase(new[] { true, true }, 0, false, true, TestName = "D InValid Child")] - [TestCase(new[] { true, false, false, true, false }, 2, true, false, + [TestCase( + new[] { true, false, false, true, false }, + 2, + true, + false, TestName = "D=>E InValid Child, Invalid Parent")] - [TestCase(new[] { false, true, false, true, false }, 2, true, false, + [TestCase( + new[] { false, true, false, true, false }, + 2, + true, + false, TestName = "D=>E InValid Child, Invalid Ancestor")] - [TestCase(new[] { true, false, false, true, true }, 2, true, false, + [TestCase( + new[] { true, false, false, true, true }, + 2, + true, + false, TestName = "D=>E Valid Children, Invalid Parent")] - [TestCase(new[] { false, true, false, true, true }, 2, true, false, + [TestCase( + new[] { false, true, false, true, true }, + 2, + true, + false, TestName = "D=>E Valid Children, Invalid Ancestor")] [TestCase(new[] { false, false, false, false, false }, 2, true, false, TestName = "D=>E mismatch")] [TestCase(new[] { false, false, true, false, false }, 2, false, true, TestName = "D=>E correction")] @@ -98,13 +114,28 @@ public class ElementSwitchValidatorTests : UmbracoIntegrationTest [TestCase(new[] { false, false }, 0, true, false, TestName = "E InValid Child")] [TestCase(new[] { true, true }, 1, false, true, TestName = "D InValid Parent")] [TestCase(new[] { true, true }, 0, false, false, TestName = "D InValid Child")] - [TestCase(new[] { true, false, false, true, false }, 2, true, false, + [TestCase( + new[] { true, false, false, true, false }, + 2, + true, + false, TestName = "D=>E InValid Child, Invalid Parent")] - [TestCase(new[] { false, true, false, true, false }, 2, true, false, + [TestCase( + new[] { false, true, false, true, false }, + 2, + true, + false, TestName = "D=>E InValid Child, Invalid Ancestor")] - [TestCase(new[] { true, false, false, true, true }, 2, true, true, + [TestCase( + new[] { true, false, false, true, true }, + 2, + true, + true, TestName = "D=>E Valid Children, Invalid Parent")] - [TestCase(new[] { false, true, false, true, true }, 2, true, true, + [TestCase(new[] { false, true, false, true, true }, + 2, + true, + true, TestName = "D=>E Valid Children, Invalid Ancestor")] [TestCase(new[] { false, false, false, false, false }, 2, true, false, TestName = "D=>E mismatch")] [TestCase(new[] { false, false, true, false, false }, 2, false, true, TestName = "D=>E correction")] diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/LogViewerServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/LogViewerServiceTests.cs index 95604a3f49..cf1a0f7c95 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/LogViewerServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/LogViewerServiceTests.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Services.OperationStatus; using Umbraco.Cms.Tests.Common.Testing; @@ -14,10 +14,10 @@ public class LogViewerServiceTests : UmbracoIntegrationTest private const string LogfileName = "UmbracoTraceLog.INTEGRATIONTEST.20230707.json"; - private string _newLogfilePath; - private string _newLogfileDirPath; - private DateTime _startDate = new(2023, 7, 7); - private DateTime _endDate = new(2023, 7, 8); + private readonly string _newLogfilePath; + private readonly string _newLogfileDirPath; + private readonly DateTime _startDate = new(2023, 7, 7); + private readonly DateTime _endDate = new(2023, 7, 8); [OneTimeSetUp] public void Setup() @@ -83,7 +83,11 @@ public class LogViewerServiceTests : UmbracoIntegrationTest [Test] public async Task Can_Get_Logs_By_Filter_Expression() { - var attempt = await LogViewerService.GetPagedLogsAsync(_startDate, _endDate, 0, int.MaxValue, + var attempt = await LogViewerService.GetPagedLogsAsync( + _startDate, + _endDate, + 0, + int.MaxValue, filterExpression: "@Level='Error'"); Assert.Multiple(() => diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/MediaTypeEditingServiceTests.Create.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/MediaTypeEditingServiceTests.Create.cs index b9d0027f2b..7e520c3bce 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/MediaTypeEditingServiceTests.Create.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/MediaTypeEditingServiceTests.Create.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Models.ContentTypeEditing; using Umbraco.Cms.Core.Services.OperationStatus; @@ -137,8 +137,7 @@ public partial class MediaTypeEditingServiceTests compositions: new[] { new Composition { CompositionType = CompositionType.Composition, Key = compositionType.Key, }, - } - ); + }); var result = await MediaTypeEditingService.CreateAsync(createModel, Constants.Security.SuperUserKey); Assert.IsTrue(result.Success); @@ -176,8 +175,7 @@ public partial class MediaTypeEditingServiceTests compositions: new[] { new Composition { CompositionType = CompositionType.Composition, Key = compositionType.Key, }, - } - ); + }); var result = await MediaTypeEditingService.CreateAsync(createModel, Constants.Security.SuperUserKey); Assert.IsFalse(result.Success); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/SupressNotificationsTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/SuppressNotificationsTests.cs similarity index 96% rename from tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/SupressNotificationsTests.cs rename to tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/SuppressNotificationsTests.cs index ec573cbb2a..f85564bc46 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/SupressNotificationsTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/SuppressNotificationsTests.cs @@ -34,7 +34,7 @@ public class SuppressNotificationsTests : UmbracoIntegrationTest public void GivenScope_WhenNotificationsSuppressed_ThenNotificationsDoNotExecute() { using var scope = ScopeProvider.CreateScope(autoComplete: true); - using var _ = scope.Notifications.Suppress(); + using var suppressed = scope.Notifications.Suppress(); var contentType = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(contentType); @@ -47,7 +47,7 @@ public class SuppressNotificationsTests : UmbracoIntegrationTest { using (var parentScope = ScopeProvider.CreateScope(autoComplete: true)) { - using var _ = parentScope.Notifications.Suppress(); + using var suppressed = parentScope.Notifications.Suppress(); using (var childScope = ScopeProvider.CreateScope(autoComplete: true)) { diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Security/BackOfficeUserStoreTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Security/BackOfficeUserStoreTests.cs index cc28332ea6..d0ac96abd7 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Security/BackOfficeUserStoreTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Security/BackOfficeUserStoreTests.cs @@ -38,7 +38,7 @@ public class BackOfficeUserStoreTests : UmbracoIntegrationTest private IEventMessagesFactory EventMessagesFactory => GetRequiredService(); - private ILogger Logger = NullLogger.Instance; + private readonly ILogger _logger = NullLogger.Instance; private BackOfficeUserStore GetUserStore() @@ -55,7 +55,7 @@ public class BackOfficeUserStoreTests : UmbracoIntegrationTest UserRepository, RuntimeState, EventMessagesFactory, - Logger + _logger ); [Test] diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CacheInstructionServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CacheInstructionServiceTests.cs index dc7b78b6fd..78dffe5ecf 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CacheInstructionServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CacheInstructionServiceTests.cs @@ -221,8 +221,7 @@ public class CacheInstructionServiceTests : UmbracoIntegrationTest Assert.Multiple(() => { Assert.AreEqual(3, result.LastId); // 3 records found. - Assert.AreEqual(2, - result.NumberOfInstructionsProcessed); // 2 records processed (as one is for the same identity). + Assert.AreEqual(2, result.NumberOfInstructionsProcessed); // 2 records processed (as one is for the same identity). Assert.IsFalse(result.InstructionsWerePruned); }); @@ -231,11 +230,17 @@ public class CacheInstructionServiceTests : UmbracoIntegrationTest // The instructions has now been processed and shouldn't be processed on the next call... // Run again. - var secondResult = sut.ProcessInstructions(CacheRefreshers, ServerRoleAccessor.CurrentServerRole, - CancellationToken, LocalIdentity, DateTime.UtcNow.AddSeconds(-1), lastId); + var secondResult = sut.ProcessInstructions( + CacheRefreshers, + ServerRoleAccessor.CurrentServerRole, + CancellationToken, + LocalIdentity, + DateTime.UtcNow.AddSeconds(-1), + lastId); Assert.Multiple(() => { - Assert.AreEqual(0, + Assert.AreEqual( + 0, secondResult .LastId); // No instructions was processed so LastId is 0, this is consistent with behavior from V8 Assert.AreEqual(0, secondResult.NumberOfInstructionsProcessed); // Nothing was processed. diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs index 64064ce7b7..ff906251fa 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs @@ -328,8 +328,7 @@ public class ContentServicePublishBranchTests : UmbracoIntegrationTest Assert.IsTrue(vRoot.IsCulturePublished("es")); Assert.IsTrue(vRoot.IsCultureEdited("es")); // has draft - Assert.AreEqual("changed", - vRoot.GetValue("ip", published: true)); // publishing de implies publishing invariants + Assert.AreEqual("changed", vRoot.GetValue("ip", published: true)); // publishing de implies publishing invariants Assert.AreEqual("changed.de", vRoot.GetValue("vp", "de", published: true)); // validate - de and ru are published, es has not been published diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs index 56b5340c1a..bcab65dadf 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs @@ -934,7 +934,8 @@ public class ContentServiceTagsTests : UmbracoIntegrationTest Assert.AreEqual(2, savedTags.Length); } - private PropertyType CreateAndAddTagsPropertyType(ContentType contentType, + private PropertyType CreateAndAddTagsPropertyType( + ContentType contentType, ContentVariation variations = ContentVariation.Nothing) { var propertyType = new PropertyTypeBuilder() diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs index 8b01dcf8cf..a4246e7586 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs @@ -641,9 +641,11 @@ public class ContentTypeServiceTests : UmbracoIntegrationTest Assert.AreNotEqual(contentType.Key, category.Key); Assert.AreNotEqual(contentType.Path, category.Path); Assert.AreNotEqual(contentType.SortOrder, category.SortOrder); - Assert.AreNotEqual(contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, + Assert.AreNotEqual( + contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, category.PropertyTypes.First(x => x.Alias.Equals("title")).Id); - Assert.AreNotEqual(contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, + Assert.AreNotEqual( + contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, category.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs index e4381ff3d9..cce3797e7e 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs @@ -48,7 +48,7 @@ public class ContentTypeServiceVariantsTests : UmbracoIntegrationTest { var json = GetJson(id).Replace('"', '\''); var pos = json.IndexOf("'cd':", StringComparison.InvariantCultureIgnoreCase); - json = json.Substring(0, pos + "'cd':".Length); + json = json[..(pos + "'cd':".Length)]; Assert.AreEqual(expected, json); } @@ -82,8 +82,10 @@ public class ContentTypeServiceVariantsTests : UmbracoIntegrationTest [TestCase(ContentVariation.CultureAndSegment, ContentVariation.Segment, true)] [TestCase(ContentVariation.CultureAndSegment, ContentVariation.CultureAndSegment, false)] [LongRunning] - public void Change_Content_Type_Variation_Clears_Redirects(ContentVariation startingContentTypeVariation, - ContentVariation changedContentTypeVariation, bool shouldUrlRedirectsBeCleared) + public void Change_Content_Type_Variation_Clears_Redirects( + ContentVariation startingContentTypeVariation, + ContentVariation changedContentTypeVariation, + bool shouldUrlRedirectsBeCleared) { var contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = startingContentTypeVariation; diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DictionaryItemServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DictionaryItemServiceTests.cs index 57f542de79..0ee0f7ce6d 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DictionaryItemServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DictionaryItemServiceTests.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Models; @@ -238,7 +238,8 @@ public class DictionaryItemServiceTests : UmbracoIntegrationTest Assert.AreEqual("Testing12345", item.ItemKey); foreach (var language in allLangs) { - Assert.AreEqual($"Translation for: {language.IsoCode}", + Assert.AreEqual( + $"Translation for: {language.IsoCode}", item.Translations.Single(x => x.LanguageIsoCode == language.IsoCode).Value); } } @@ -627,8 +628,7 @@ public class DictionaryItemServiceTests : UmbracoIntegrationTest dictionaryResult = await DictionaryItemService.CreateAsync( new DictionaryItem( parentItem.Key, - "Child" - ) + "Child") { Translations = new List { diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs index 6643352faf..d18caf52b4 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs @@ -836,9 +836,11 @@ public class EntityServiceTests : UmbracoIntegrationTest [Test] public void EntityService_Cannot_Get_Id_For_Key_With_Incorrect_Object_Type() { - var result1 = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), + var result1 = EntityService.GetId( + Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); - var result2 = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), + var result2 = EntityService.GetId( + Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.MediaType); Assert.IsTrue(result1.Success); @@ -868,7 +870,7 @@ public class EntityServiceTests : UmbracoIntegrationTest Assert.IsFalse(EntityService.GetId(Guid.NewGuid(), UmbracoObjectTypes.DocumentType).Success); } - private static bool s_isSetup; + private static bool _isSetup; private int _folderId; private ContentType _contentType; @@ -885,9 +887,9 @@ public class EntityServiceTests : UmbracoIntegrationTest public void CreateTestData() { - if (s_isSetup == false) + if (_isSetup == false) { - s_isSetup = true; + _isSetup = true; var template = TemplateBuilder.CreateTextPageTemplate("defaultTemplate"); FileService.SaveTemplate(template); // else, FK violation on contentType! diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs index b370241965..8e68d4d3e2 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs @@ -120,7 +120,7 @@ public class EntityXmlSerializerTests : UmbracoIntegrationTest Assert.AreEqual(content.Name, (string)element.Attribute("nodeName")); Assert.AreEqual(urlName, (string)element.Attribute("urlName")); Assert.AreEqual(content.Path, (string)element.Attribute("path")); - Assert.AreEqual("", (string)element.Attribute("isDoc")); + Assert.AreEqual(string.Empty, (string)element.Attribute("isDoc")); Assert.AreEqual(content.ContentType.Id.ToString(), (string)element.Attribute("nodeType")); Assert.AreEqual(content.GetCreatorProfile(UserService).Name, (string)element.Attribute("creatorName")); Assert.AreEqual(content.GetWriterProfile(UserService).Name, (string)element.Attribute("writerName")); @@ -128,11 +128,14 @@ public class EntityXmlSerializerTests : UmbracoIntegrationTest Assert.AreEqual(content.TemplateId.ToString(), (string)element.Attribute("template")); Assert.AreEqual(content.Properties["title"].GetValue().ToString(), element.Elements("title").Single().Value); - Assert.AreEqual(content.Properties["bodyText"].GetValue().ToString(), + Assert.AreEqual( + content.Properties["bodyText"].GetValue().ToString(), element.Elements("bodyText").Single().Value); - Assert.AreEqual(content.Properties["keywords"].GetValue().ToString(), + Assert.AreEqual( + content.Properties["keywords"].GetValue().ToString(), element.Elements("keywords").Single().Value); - Assert.AreEqual(content.Properties["description"].GetValue().ToString(), + Assert.AreEqual( + content.Properties["description"].GetValue().ToString(), element.Elements("description").Single().Value); } @@ -193,7 +196,7 @@ public class EntityXmlSerializerTests : UmbracoIntegrationTest Assert.AreEqual(media.Name, (string)element.Attribute("nodeName")); Assert.AreEqual(urlName, (string)element.Attribute("urlName")); Assert.AreEqual(media.Path, (string)element.Attribute("path")); - Assert.AreEqual("", (string)element.Attribute("isDoc")); + Assert.AreEqual(string.Empty, (string)element.Attribute("isDoc")); Assert.AreEqual(media.ContentType.Id.ToString(), (string)element.Attribute("nodeType")); Assert.AreEqual(media.GetCreatorProfile(UserService).Name, (string)element.Attribute("writerName")); Assert.AreEqual(media.CreatorId.ToString(), (string)element.Attribute("writerID")); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs index 58138fd893..41fce99e95 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs @@ -275,7 +275,8 @@ public class LocalizationServiceTests : UmbracoIntegrationTest Assert.Greater(allLangs.Count(), 0); foreach (var language in allLangs) { - Assert.AreEqual("Hellooooo", + Assert.AreEqual( + "Hellooooo", item.Translations.Single(x => x.LanguageIsoCode == language.IsoCode).Value); } } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeContainerServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeContainerServiceTests.cs index 90034887f5..c2720019c8 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeContainerServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeContainerServiceTests.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Services; @@ -177,11 +177,11 @@ public class MediaTypeContainerServiceTests : UmbracoIntegrationTest { EntityContainer container = (await MediaTypeContainerService.CreateAsync(null,"Root Container", null, Constants.Security.SuperUserKey)).Result; - IMediaType MediaType = new MediaType(ShortStringHelper, container.Id) + IMediaType mediaType = new MediaType(ShortStringHelper, container.Id) { Alias = "test", Name = "Test" }; - MediaTypeService.Save(MediaType); + MediaTypeService.Save(mediaType); var result = await MediaTypeContainerService.DeleteAsync(container.Key, Constants.Security.SuperUserKey); Assert.IsFalse(result.Success); @@ -190,7 +190,7 @@ public class MediaTypeContainerServiceTests : UmbracoIntegrationTest var currentContainer = await MediaTypeContainerService.GetAsync(container.Key); Assert.IsNotNull(currentContainer); - var currentMediaType = MediaTypeService.Get(MediaType.Key); + var currentMediaType = MediaTypeService.Get(mediaType.Key); Assert.IsNotNull(currentMediaType); } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs index 8fa1a658c1..a35a7db908 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs @@ -170,9 +170,11 @@ public class MediaTypeServiceTests : UmbracoIntegrationTest Assert.AreNotEqual(mediaType.Key, sut.Key); Assert.AreNotEqual(mediaType.Path, sut.Path); Assert.AreNotEqual(mediaType.SortOrder, sut.SortOrder); - Assert.AreNotEqual(mediaType.PropertyTypes.First(x => x.Alias.Equals("umbracoFile")).Id, + Assert.AreNotEqual( + mediaType.PropertyTypes.First(x => x.Alias.Equals("umbracoFile")).Id, sut.PropertyTypes.First(x => x.Alias.Equals("umbracoFile")).Id); - Assert.AreNotEqual(mediaType.PropertyGroups.First(x => x.Name.Equals("Media")).Id, + Assert.AreNotEqual( + mediaType.PropertyGroups.First(x => x.Name.Equals("Media")).Id, sut.PropertyGroups.First(x => x.Name.Equals("Media")).Id); } @@ -214,9 +216,11 @@ public class MediaTypeServiceTests : UmbracoIntegrationTest Assert.AreNotEqual(clonedMediaType.Key, originalMediaType.Key); Assert.AreNotEqual(clonedMediaType.Path, originalMediaType.Path); - Assert.AreNotEqual(clonedMediaType.PropertyTypes.First(x => x.Alias.StartsWith("umbracoFile")).Id, + Assert.AreNotEqual( + clonedMediaType.PropertyTypes.First(x => x.Alias.StartsWith("umbracoFile")).Id, originalMediaType.PropertyTypes.First(x => x.Alias.StartsWith("umbracoFile")).Id); - Assert.AreNotEqual(clonedMediaType.PropertyGroups.First(x => x.Name.StartsWith("Media")).Id, + Assert.AreNotEqual( + clonedMediaType.PropertyGroups.First(x => x.Name.StartsWith("Media")).Id, originalMediaType.PropertyGroups.First(x => x.Name.StartsWith("Media")).Id); } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Persistence.EFCore/DbContext/CustomDbContextTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Persistence.EFCore/DbContext/CustomDbContextUmbracoProviderTests.cs similarity index 98% rename from tests/Umbraco.Tests.Integration/Umbraco.Persistence.EFCore/DbContext/CustomDbContextTests.cs rename to tests/Umbraco.Tests.Integration/Umbraco.Persistence.EFCore/DbContext/CustomDbContextUmbracoProviderTests.cs index bfa3adb92b..b2a71e0a9c 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Persistence.EFCore/DbContext/CustomDbContextTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Persistence.EFCore/DbContext/CustomDbContextUmbracoProviderTests.cs @@ -1,4 +1,4 @@ -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Tests.Integration.csproj b/tests/Umbraco.Tests.Integration/Umbraco.Tests.Integration.csproj index a04ee45648..a566324d10 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Tests.Integration.csproj +++ b/tests/Umbraco.Tests.Integration/Umbraco.Tests.Integration.csproj @@ -10,8 +10,14 @@ NU5100 - - false + + + SYSLIB0012,SA1117,SA1116,CS0162,CS0169,SA1134,SA1405,CS0108,CS0618,CS4014,CS1998,CS0649,CS0168 + diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Web.Website/Routing/FrontEndRouteTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Web.Website/Routing/SurfaceControllerTests.cs similarity index 99% rename from tests/Umbraco.Tests.Integration/Umbraco.Web.Website/Routing/FrontEndRouteTests.cs rename to tests/Umbraco.Tests.Integration/Umbraco.Web.Website/Routing/SurfaceControllerTests.cs index d8383bc601..c48741b36a 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Web.Website/Routing/FrontEndRouteTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Web.Website/Routing/SurfaceControllerTests.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Persistence.SqlServer/SqAzureDatabaseProviderMetadataTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Persistence.SqlServer/SqlAzureDatabaseProviderMetadataTests.cs similarity index 98% rename from tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Persistence.SqlServer/SqAzureDatabaseProviderMetadataTests.cs rename to tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Persistence.SqlServer/SqlAzureDatabaseProviderMetadataTests.cs index e945eeae07..26333ab621 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Persistence.SqlServer/SqAzureDatabaseProviderMetadataTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Persistence.SqlServer/SqlAzureDatabaseProviderMetadataTests.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using Umbraco.Cms.Core.Install.Models; using Umbraco.Cms.Persistence.SqlServer.Services; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/CacheTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/CacheTests.cs index 194abdc158..617600a6ed 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/CacheTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/CacheTests.cs @@ -28,8 +28,7 @@ public class CacheTests : DeliveryApiTests It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny()) - ).Returns(() => $"Delivery API value: {++invocationCount}"); + It.IsAny())).Returns(() => $"Delivery API value: {++invocationCount}"); propertyValueConverter.Setup(p => p.IsConverter(It.IsAny())).Returns(true); propertyValueConverter.Setup(p => p.GetPropertyCacheLevel(It.IsAny())).Returns(cacheLevel); propertyValueConverter.Setup(p => p.GetDeliveryApiPropertyCacheLevel(It.IsAny())).Returns(cacheLevel); @@ -41,11 +40,13 @@ public class CacheTests : DeliveryApiTests var prop1 = new PublishedElementPropertyBase(propertyType, element.Object, false, cacheLevel); - var results = new List(); - results.Add(prop1.GetDeliveryApiValue(expanding)!.ToString()); - results.Add(prop1.GetDeliveryApiValue(expanding)!.ToString()); - results.Add(prop1.GetDeliveryApiValue(expanding)!.ToString()); - results.Add(prop1.GetDeliveryApiValue(expanding)!.ToString()); + var results = new List + { + prop1.GetDeliveryApiValue(expanding)!.ToString(), + prop1.GetDeliveryApiValue(expanding)!.ToString(), + prop1.GetDeliveryApiValue(expanding)!.ToString(), + prop1.GetDeliveryApiValue(expanding)!.ToString() + }; Assert.AreEqual("Delivery API value: 1", results.First()); Assert.AreEqual(expectedConverterHits, results.Distinct().Count()); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/DeliveryApiTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/DeliveryApiTests.cs index 47a7c032c9..2d27d03969 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/DeliveryApiTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/DeliveryApiTests.cs @@ -30,15 +30,13 @@ public class DeliveryApiTests It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny()) - ).Returns("Delivery API value"); + It.IsAny())).Returns("Delivery API value"); deliveryApiPropertyValueConverter.Setup(p => p.ConvertIntermediateToObject( It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny()) - ).Returns("Default value"); + It.IsAny())).Returns("Default value"); deliveryApiPropertyValueConverter.Setup(p => p.IsConverter(It.IsAny())).Returns(true); deliveryApiPropertyValueConverter.Setup(p => p.IsValue(It.IsAny(), It.IsAny())).Returns(true); deliveryApiPropertyValueConverter.Setup(p => p.GetPropertyCacheLevel(It.IsAny())).Returns(PropertyCacheLevel.None); @@ -53,8 +51,7 @@ public class DeliveryApiTests It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny()) - ).Returns("Default value"); + It.IsAny())).Returns("Default value"); defaultPropertyValueConverter.Setup(p => p.IsConverter(It.IsAny())).Returns(true); defaultPropertyValueConverter.Setup(p => p.IsValue(It.IsAny(), It.IsAny())).Returns(true); defaultPropertyValueConverter.Setup(p => p.GetPropertyCacheLevel(It.IsAny())).Returns(PropertyCacheLevel.None); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/ImageCropperValueConverterTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/ImageCropperValueConverterTests.cs index fc70ae5f19..f27eff76d6 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/ImageCropperValueConverterTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/ImageCropperValueConverterTests.cs @@ -45,8 +45,7 @@ public class ImageCropperValueConverterTests : PropertyValueConverterTests } }, FocalPoint = new ImageCropperValue.ImageCropperFocalPoint { Left = .2m, Top = .4m } - } - ); + }); var inter = valueConverter.ConvertSourceToIntermediate(Mock.Of(), publishedPropertyType.Object, source, false); var result = valueConverter.ConvertIntermediateToDeliveryApiObject(Mock.Of(), publishedPropertyType.Object, PropertyCacheLevel.Element, inter, false, false) as ApiImageCropperValue; Assert.NotNull(result); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/MediaBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/MediaBuilderTests.cs index 399b164783..173a5bc565 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/MediaBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/MediaBuilderTests.cs @@ -1,4 +1,4 @@ -using Moq; +using Moq; using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.DeliveryApi; @@ -45,8 +45,7 @@ public class MediaBuilderTests : DeliveryApiTests Guid.NewGuid(), "The media", "media-url-segment", - new Dictionary() - ); + new Dictionary()); var builder = new ApiMediaBuilder(new ApiContentNameProvider(), SetupMediaUrlProvider(), Mock.Of(), CreateOutputExpansionStrategyAccessor()); var result = builder.Build(media); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/TypeExtensionsTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/TypeExtensionsTests.cs index cd2658f574..5453d3daed 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/TypeExtensionsTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/TypeExtensionsTests.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Extensions; @@ -6,9 +6,9 @@ namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Extensions; [TestFixture] public class TypeExtensionsTests { - private string[] PublicObjectMethodNames = { nameof(GetType), nameof(ToString), nameof(Equals), nameof(GetHashCode) }; + private readonly string[] _publicObjectMethodNames = { nameof(GetType), nameof(ToString), nameof(Equals), nameof(GetHashCode) }; - private string[] NonPublicObjectMethodNames = { nameof(MemberwiseClone), "Finalize" }; + private readonly string[] _nonPublicObjectMethodNames = { nameof(MemberwiseClone), "Finalize" }; [Test] public void Can_Get_Public_Properties_Of_Interface() @@ -95,20 +95,20 @@ public class TypeExtensionsTests public void Can_Get_Public_Methods_Of_Class() { var methods = typeof(TheBaseThing).GetPublicMethods(); - Assert.AreEqual(3 + PublicObjectMethodNames.Length, methods.Length); + Assert.AreEqual(3 + _publicObjectMethodNames.Length, methods.Length); var methodNames = methods.Select(p => p.Name).ToArray(); Assert.Contains( $"get_{nameof(TheBaseThing.TheBaseThingProperty)}", methodNames); Assert.Contains( nameof(TheBaseThing.TheBaseThingMethod), methodNames); Assert.Contains( nameof(TheBaseThing.TheExtraMethod), methodNames); - Assert.IsTrue(methodNames.ContainsAll(PublicObjectMethodNames)); + Assert.IsTrue(methodNames.ContainsAll(_publicObjectMethodNames)); } [Test] public void Get_Public_Methods_Of_Class_Contains_Inherited_Methods() { var methods = typeof(TheThing).GetPublicMethods(); - Assert.AreEqual(7 + PublicObjectMethodNames.Length, methods.Length); + Assert.AreEqual(7 + _publicObjectMethodNames.Length, methods.Length); var methodNames = methods.Select(p => p.Name).ToArray(); Assert.Contains( $"get_{nameof(TheBaseThing.TheBaseThingProperty)}", methodNames); @@ -118,29 +118,29 @@ public class TypeExtensionsTests Assert.Contains( $"set_{nameof(TheThing.TheThingProperty)}", methodNames); Assert.Contains( $"get_{nameof(TheThing.TheExtraProperty)}", methodNames); Assert.Contains( nameof(TheThing.TheThingMethod), methodNames); - Assert.IsTrue(methodNames.ContainsAll(PublicObjectMethodNames)); + Assert.IsTrue(methodNames.ContainsAll(_publicObjectMethodNames)); } [Test] public void Can_Get_All_Methods_Of_Class() { var methods = typeof(TheBaseThing).GetAllMethods(); - Assert.AreEqual(4 + PublicObjectMethodNames.Length + NonPublicObjectMethodNames.Length, methods.Length); + Assert.AreEqual(4 + _publicObjectMethodNames.Length + _nonPublicObjectMethodNames.Length, methods.Length); var methodNames = methods.Select(p => p.Name).ToArray(); Assert.Contains( $"get_{nameof(TheBaseThing.TheBaseThingProperty)}", methodNames); Assert.Contains( nameof(TheBaseThing.TheBaseThingMethod), methodNames); Assert.Contains( nameof(TheBaseThing.TheExtraMethod), methodNames); Assert.Contains( nameof(TheBaseThing.TheInternalMethod), methodNames); - Assert.IsTrue(methodNames.ContainsAll(PublicObjectMethodNames)); - Assert.IsTrue(methodNames.ContainsAll(NonPublicObjectMethodNames)); + Assert.IsTrue(methodNames.ContainsAll(_publicObjectMethodNames)); + Assert.IsTrue(methodNames.ContainsAll(_nonPublicObjectMethodNames)); } [Test] public void Get_All_Methods_Of_Class_Contains_Inherited_Methods() { var methods = typeof(TheThing).GetAllMethods(); - Assert.AreEqual(9 + PublicObjectMethodNames.Length + NonPublicObjectMethodNames.Length, methods.Length); + Assert.AreEqual(9 + _publicObjectMethodNames.Length + _nonPublicObjectMethodNames.Length, methods.Length); var methodNames = methods.Select(p => p.Name).ToArray(); Assert.Contains( $"get_{nameof(TheBaseThing.TheBaseThingProperty)}", methodNames); @@ -152,8 +152,8 @@ public class TypeExtensionsTests Assert.Contains( $"get_{nameof(TheThing.TheExtraProperty)}", methodNames); Assert.Contains( $"get_{nameof(TheThing.TheInternalProperty)}", methodNames); Assert.Contains( nameof(TheThing.TheThingMethod), methodNames); - Assert.IsTrue(methodNames.ContainsAll(PublicObjectMethodNames)); - Assert.IsTrue(methodNames.ContainsAll(NonPublicObjectMethodNames)); + Assert.IsTrue(methodNames.ContainsAll(_publicObjectMethodNames)); + Assert.IsTrue(methodNames.ContainsAll(_nonPublicObjectMethodNames)); } [Test] diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs index 15a74df3bf..443dea94d5 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs @@ -232,7 +232,7 @@ public abstract class Item : IEntity, ICanBeDirty return true; } - if (ReferenceEquals(obj, null)) + if (obj is null) { return false; } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/CultureImpactTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/CultureImpactTests.cs index 0ce0f73271..e91d37e25d 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/CultureImpactTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/CultureImpactTests.cs @@ -13,7 +13,7 @@ namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Models; [TestFixture] public class CultureImpactTests { - private CultureImpactFactory BasicImpactFactory => createCultureImpactService(); + private CultureImpactFactory BasicImpactFactory => CreateCultureImpactService(); [Test] public void Get_Culture_For_Invariant_Errors() @@ -28,8 +28,8 @@ public class CultureImpactTests Mock.Of(x => x.Published == false), new[] { "fr-FR" }, "en-US"); - Assert.AreEqual("fr-FR", - result); // default culture not being saved with not published version, use the first culture being saved + Assert.AreEqual("fr-FR", result); // default culture not being saved with not published version, + // use the first culture being saved result = BasicImpactFactory.GetCultureForInvariantErrors( Mock.Of(x => x.Published == true), @@ -179,7 +179,7 @@ public class CultureImpactTests [TestCase(false)] public void Edit_Invariant_From_Non_Default_Impacts_Invariant_Properties(bool allowEditInvariantFromNonDefault) { - var sut = createCultureImpactService(new ContentSettings + var sut = CreateCultureImpactService(new ContentSettings { AllowEditInvariantFromNonDefault = allowEditInvariantFromNonDefault }); @@ -188,7 +188,7 @@ public class CultureImpactTests Assert.AreEqual(allowEditInvariantFromNonDefault, impact.ImpactsAlsoInvariantProperties); } - private CultureImpactFactory createCultureImpactService(ContentSettings contentSettings = null) + private CultureImpactFactory CreateCultureImpactService(ContentSettings contentSettings = null) { contentSettings ??= new ContentSettings { AllowEditInvariantFromNonDefault = false, }; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionUtilitiesTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionUtilitiesTests.cs index 7a2efdedac..4f993436ee 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionUtilitiesTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionUtilitiesTests.cs @@ -660,7 +660,9 @@ public class ReflectionUtilitiesTests public readonly int Field3 = 22; public int Field1 = 33; +#pragma warning disable SA1306 // Field names should begin with lower-case letter private readonly int Field2 = 66; +#pragma warning restore SA1306 // Field names should begin with lower-case letter public Class1() { diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringExtensionsTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringExtensionsTests.cs index 6e959e45f4..58e06ba17b 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringExtensionsTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringExtensionsTests.cs @@ -360,7 +360,7 @@ public class StringExtensionsTests TryIsFullPath(@"\dir", false); // An "absolute", but not "full" path // Invalid on both Windows and Linux - TryIsFullPath("", false, false); + TryIsFullPath(string.Empty, false, false); TryIsFullPath(" ", false, false); // technically, a valid filename on Linux } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs index 026402b9f9..ecafb561dd 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs @@ -57,14 +57,12 @@ public class BackOfficeClaimsPrincipalFactoryTests => Assert.Throws(() => new BackOfficeClaimsPrincipalFactory( null, new OptionsWrapper(new BackOfficeIdentityOptions()), - new OptionsWrapper(new BackOfficeAuthenticationTypeSettings()) - )); + new OptionsWrapper(new BackOfficeAuthenticationTypeSettings()))); [Test] public void Ctor_When_Options_Are_Null_Expect_ArgumentNullException() => Assert.Throws(() => - new BackOfficeClaimsPrincipalFactory(GetMockedUserManager().Object, null, new OptionsWrapper(new BackOfficeAuthenticationTypeSettings())) - ); + new BackOfficeClaimsPrincipalFactory(GetMockedUserManager().Object, null, new OptionsWrapper(new BackOfficeAuthenticationTypeSettings()))); [Test] public void Ctor_When_Options_Value_Is_Null_Expect_ArgumentException() diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentCacheTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishContentCacheTests.cs similarity index 98% rename from tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentCacheTests.cs rename to tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishContentCacheTests.cs index c06aed8415..831333fcbb 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentCacheTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishContentCacheTests.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Umbraco.Cms.Core.Models; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.UnitTests.csproj b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.UnitTests.csproj index 6986e03494..02a84f6d74 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.UnitTests.csproj +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.UnitTests.csproj @@ -6,8 +6,17 @@ false - - false + + + SYSLIB0013,CS0618,CS1998,SA1117,CS0067,CA1822,CA1416,IDE0028,SA1401,SA1405 + IDE0060,SA1405,ASP0019,CS0114,CS0661,CS0659,CS0414,CS0252,IDE0060,IDE1006 + diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Routing/UmbracoRouteValueTransformerTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Routing/UmbracoRouteValueTransformerTests.cs index 30b40607f4..338e3c5568 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Routing/UmbracoRouteValueTransformerTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Routing/UmbracoRouteValueTransformerTests.cs @@ -67,8 +67,7 @@ public class UmbracoRouteValueTransformerTests Mock.Of(), publicAccessRequestHandler.Object, Mock.Of(), - Mock.Of>() - ); + Mock.Of>()); return transformer; } diff --git a/tools/Umbraco.JsonSchema/Program.cs b/tools/Umbraco.JsonSchema/Program.cs index 4711f0278b..24dd482931 100644 --- a/tools/Umbraco.JsonSchema/Program.cs +++ b/tools/Umbraco.JsonSchema/Program.cs @@ -4,7 +4,7 @@ await Parser.Default.ParseArguments(args).WithParsedAsync(async options { // Generate CMS schema var jsonSchemaGenerator = new UmbracoJsonSchemaGenerator(); - var jsonSchema = jsonSchemaGenerator.Generate(typeof(UmbracoCmsSchema)); + NJsonSchema.JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(UmbracoCmsSchema)); await File.WriteAllTextAsync(options.OutputFile, jsonSchema.ToJson()); }); diff --git a/tools/Umbraco.JsonSchema/Umbraco.JsonSchema.csproj b/tools/Umbraco.JsonSchema/Umbraco.JsonSchema.csproj index 471ebff802..3f3b81165e 100644 --- a/tools/Umbraco.JsonSchema/Umbraco.JsonSchema.csproj +++ b/tools/Umbraco.JsonSchema/Umbraco.JsonSchema.csproj @@ -5,8 +5,9 @@ false - - false + + SA1117,SA1401,SA1134,CS9042