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