Skip to content

Commit

Permalink
Resolved more warnings, and marked more warning types as errors (#16991)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
emmagarland authored Sep 24, 2024
1 parent c8899af commit ac57566
Show file tree
Hide file tree
Showing 118 changed files with 991 additions and 800 deletions.
3 changes: 2 additions & 1 deletion src/Umbraco.Cms.Api.Delivery/Umbraco.Cms.Api.Delivery.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
<Description>Contains the presentation layer for the Umbraco CMS Delivery API.</Description>
</PropertyGroup>
<PropertyGroup>
<!-- TODO: [ASP0019] use IHeaderDictionary.Append or the indexer to append or set headers and remove this override -->
<!-- TODO: [ASP0019] use IHeaderDictionary.Append or the indexer to append or set headers,
and remove this override -->
<WarningsNotAsErrors>ASP0019</WarningsNotAsErrors>
</PropertyGroup>
<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,10 @@ public async Task<IActionResult> Signout(CancellationToken cancellationToken)

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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -21,7 +21,8 @@ status is UpgradeOperationStatus.Success
? 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.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,16 @@ void AddAllowedApplicationsPolicy(string policyName, params string[] allowedClai

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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ public static IUmbracoBuilder AddBackOfficeCore(this IUmbracoBuilder builder)
hostingEnvironment,
factory.GetRequiredService<ILogger<PhysicalFileSystem>>(),
hostingEnvironment.MapPathContentRoot(path),
hostingEnvironment.ToAbsolute(path)
);
hostingEnvironment.ToAbsolute(path));
});

return builder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ public static IUmbracoBuilder AddBackOfficeIdentity(this IUmbracoBuilder builder
factory.GetRequiredService<IUserRepository>(),
factory.GetRequiredService<IRuntimeState>(),
factory.GetRequiredService<IEventMessagesFactory>(),
factory.GetRequiredService<ILogger<BackOfficeUserStore>>()
))
factory.GetRequiredService<ILogger<BackOfficeUserStore>>()))
.AddUserManager<IBackOfficeUserManager, BackOfficeUserManager>()
.AddSignInManager<IBackOfficeSignInManager, BackOfficeSignInManager>()
.AddClaimsPrincipalFactory<BackOfficeClaimsPrincipalFactory>()
Expand Down Expand Up @@ -94,14 +93,16 @@ private static BackOfficeIdentityBuilder BuildUmbracoBackOfficeIdentity(this IUm
/// <summary>
/// Adds support for external login providers in Umbraco
/// </summary>
public static IUmbracoBuilder AddBackOfficeExternalLogins(this IUmbracoBuilder umbracoBuilder,
public static IUmbracoBuilder AddBackOfficeExternalLogins(
this IUmbracoBuilder umbracoBuilder,
Action<BackOfficeExternalLoginsBuilder> builder)
{
builder(new BackOfficeExternalLoginsBuilder(umbracoBuilder.Services));
return umbracoBuilder;
}

public static BackOfficeIdentityBuilder AddTwoFactorProvider<T>(this BackOfficeIdentityBuilder identityBuilder,
public static BackOfficeIdentityBuilder AddTwoFactorProvider<T>(
this BackOfficeIdentityBuilder identityBuilder,
string providerName) where T : class, ITwoFactorProvider
{
identityBuilder.Services.AddSingleton<ITwoFactorProvider, T>();
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -32,7 +32,12 @@ public void Apply(OpenApiOperation operation, OperationFilterContext context)
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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ public BackOfficeAuthenticationBuilder(
/// <param name="displayName"></param>
/// <param name="configureOptions"></param>
/// <returns></returns>
public override AuthenticationBuilder AddRemoteScheme<TOptions, THandler>(string authenticationScheme,
string? displayName, Action<TOptions>? configureOptions)
public override AuthenticationBuilder AddRemoteScheme<TOptions, THandler>(
string authenticationScheme,
string? displayName,
Action<TOptions>? configureOptions)
{
// Validate that the prefix is set
if (!authenticationScheme.StartsWith(Constants.Security.BackOfficeExternalAuthenticationTypePrefix))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ public interface IBackOfficeExternalLoginService

Task<Attempt<IEnumerable<IdentityError>, ExternalLoginOperationStatus>> HandleLoginCallbackAsync(HttpContext httpContext);

Task<Attempt<Guid?, ExternalLoginOperationStatus>> GenerateLoginProviderSecretAsync(ClaimsPrincipal claimsPrincipal,
Task<Attempt<Guid?, ExternalLoginOperationStatus>> GenerateLoginProviderSecretAsync(
ClaimsPrincipal claimsPrincipal,
string loginProvider);

Task<Attempt<ClaimsPrincipal?, ExternalLoginOperationStatus>> ClaimsPrincipleFromLoginProviderLinkKeyAsync(
Expand Down
11 changes: 9 additions & 2 deletions src/Umbraco.Cms.Api.Management/Umbraco.Cms.Api.Management.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,15 @@
<RootNamespace>Umbraco.Cms.Api.Management</RootNamespace>
</PropertyGroup>
<PropertyGroup>
<!-- TODO: Fix all warnings and remove this override -->
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<!-- TODO: Fix [SA1117] params all on same line, [SA1401] make fields private,
[SA1134] own line attributes, [CS0108] hidden inherited member, [CS0618]/[CS9042] update
obsolete references, [CS1998] remove async or make method synchronous, [CS8524] switch statement,
[IDE0060] removed unused parameter, [SA1649] file name match type, [CS0419] ambiguous reference,
[CS1573] param tag for all parameters, [CS1574] unresolveable cref, and remove overrides -->
<WarningsNotAsErrors>
SA1117,SA1401,SA1134,CS0108,CS0618,CS1998,CS8524,CS9042,IDE0060,SA1649,CS0419,
CS1573,CS1574
</WarningsNotAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="JsonPatch.Net" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
<Description>Adds support for Entity Framework Core to Umbraco CMS.</Description>
</PropertyGroup>
<PropertyGroup>
<!-- TODO: [IDE0270] Simplify null checks, [CS0108] resolve hiding inherited members, [CS1998] remove async or make method synchronous,
and remove this override -->
<!-- TODO: [IDE0270] Simplify null checks, [CS0108] resolve hiding inherited members, [CS1998]
remove async or make method synchronous, and remove these overrides -->
<WarningsNotAsErrors>IDE0270,CS0108,CS1998</WarningsNotAsErrors>
</PropertyGroup>
<ItemGroup>
<ItemGroup>
<!-- Take top-level depedendency on Azure.Identity, because Microsoft.EntityFrameworkCore.SqlServer depends on a vulnerable version -->
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@
<Description>Adds support for SQL Server to Umbraco CMS.</Description>
</PropertyGroup>
<PropertyGroup>
<!-- TODO: [SA1405] Simplify null checks, [SA1121] resolve hiding inherited members, [SA1117] remove async or make method synchronous,
[IDE1006] fix naming rule violation, [CS0618] handle member obsolete appropriately, [IDE0270] simplify null check, [IDE0057] simplify substring,
[IDE0054] use compound assignment, [CSO618] use NVARCARMAX, [IDE0048] add parenthesis for clarity, [CS1574] resolve ML comment cref attribute and remove this override -->
<WarningsNotAsErrors>SA1405,SA1121,SA1117,SA1116,IDE1006,CS0618,IDE0270,IDE0057,IDE0054,CSO618,IDE0048,CS1574</WarningsNotAsErrors>
<!-- TODO: [SA1405] Debug assret message text, [SA1121] resolve hiding inherited members, [SA1117] remove
async or make method synchronous, [IDE1006] fix naming rule violation, [CS0618] handle member
obsolete appropriately, [IDE0270] simplify null check, [IDE0057] simplify substring, [IDE0054]
use compound assignment, [CSO618] use NVARCARMAX, [IDE0048] add parenthesis for clarity,
[CS1574] resolve ML comment cref attribute, and remove these overrides -->
<WarningsNotAsErrors>
SA1405,SA1121,SA1117,SA1116,IDE1006,CS0618,IDE0270,IDE0057,IDE0054,CSO618,IDE0048,
CS1574
</WarningsNotAsErrors>
</PropertyGroup>
<ItemGroup>
<!-- Take top-level depedendency on Azure.Identity, because NPoco.SqlServer depends on a vulnerable version -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<PropertyGroup>
<!-- TODO: [NU5123] Rename files so path is shorter -->
<!-- TODO: [NU5123] Rename files so path is shorter and remove this override -->
<WarningsNotAsErrors>NU5123</WarningsNotAsErrors>
</PropertyGroup>

Expand Down
4 changes: 2 additions & 2 deletions src/Umbraco.Cms.Targets/Umbraco.Cms.Targets.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
<IncludeSymbols>false</IncludeSymbols>
</PropertyGroup>
<PropertyGroup>
<!-- TODO: [IDE0270] Simplify null checks, [CS0108] resolve hiding inherited members, [CS1998] remove async or make method synchronous,
and remove this override -->
<!-- TODO: [IDE0270] Simplify null checks, [CS0108] resolve hiding inherited members, [CS1998] remove
async or make method synchronous, and remove these overrides -->
<WarningsNotAsErrors>IDE0270,CS0108,CS1998</WarningsNotAsErrors>
</PropertyGroup>
<ItemGroup>
Expand Down
28 changes: 14 additions & 14 deletions src/Umbraco.Core/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ public static string StripFileExtension(this string fileName)
return fileName;
}

var spanFileName = fileName.AsSpan();
ReadOnlySpan<char> spanFileName = fileName.AsSpan();
var lastIndex = spanFileName.LastIndexOf('.');
if (lastIndex > 0)
{
var ext = spanFileName[lastIndex..];
ReadOnlySpan<char> ext = spanFileName[lastIndex..];

// file extensions cannot contain whitespace
if (ext.Contains(' '))
Expand Down Expand Up @@ -377,7 +377,7 @@ public static string TrimStart(this string value, string forRemoving)

while (value.StartsWith(forRemoving, StringComparison.InvariantCultureIgnoreCase))
{
value = value.Substring(forRemoving.Length);
value = value[forRemoving.Length..];
}

return value;
Expand Down Expand Up @@ -497,7 +497,7 @@ public static Guid EncodeAsGuid(this string input)

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;
}
Expand Down Expand Up @@ -528,8 +528,8 @@ public static string DecodeFromHex(this string hexValue)
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;
Expand Down Expand Up @@ -871,7 +871,7 @@ public static string Truncate(this string text, int maxLength, string suffix = "
return truncatedString;
}

truncatedString = text.Substring(0, strLength);
truncatedString = text[..strLength];
truncatedString = truncatedString.TrimEnd();
truncatedString += suffix;

Expand Down Expand Up @@ -914,7 +914,7 @@ public static string OrIfNullOrWhiteSpace(this string input, string alternative)
public static string ToFirstUpper(this string input) =>
string.IsNullOrWhiteSpace(input)
? input
: input.Substring(0, 1).ToUpper() + input.Substring(1);
: input[..1].ToUpper() + input[1..];

/// <summary>
/// Returns a copy of the string with the first character converted to lowercase.
Expand All @@ -924,7 +924,7 @@ public static string ToFirstUpper(this string input) =>
public static string ToFirstLower(this string input) =>
string.IsNullOrWhiteSpace(input)
? input
: input.Substring(0, 1).ToLower() + input.Substring(1);
: input[..1].ToLower() + input[1..];

/// <summary>
/// Returns a copy of the string with the first character converted to uppercase using the casing rules of the
Expand All @@ -936,7 +936,7 @@ public static string ToFirstLower(this string input) =>
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..];

/// <summary>
/// Returns a copy of the string with the first character converted to lowercase using the casing rules of the
Expand All @@ -948,7 +948,7 @@ public static string ToFirstUpper(this string input, CultureInfo culture) =>
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..];

/// <summary>
/// Returns a copy of the string with the first character converted to uppercase using the casing rules of the
Expand All @@ -959,7 +959,7 @@ public static string ToFirstLower(this string input, CultureInfo culture) =>
public static string ToFirstUpperInvariant(this string input) =>
string.IsNullOrWhiteSpace(input)
? input
: input.Substring(0, 1).ToUpperInvariant() + input.Substring(1);
: input[..1].ToUpperInvariant() + input[1..];

/// <summary>
/// Returns a copy of the string with the first character converted to lowercase using the casing rules of the
Expand All @@ -970,7 +970,7 @@ public static string ToFirstUpperInvariant(this string input) =>
public static string ToFirstLowerInvariant(this string input) =>
string.IsNullOrWhiteSpace(input)
? input
: input.Substring(0, 1).ToLowerInvariant() + input.Substring(1);
: input[..1].ToLowerInvariant() + input[1..];

/// <summary>
/// Returns a new string in which all occurrences of specified strings are replaced by other specified strings.
Expand Down Expand Up @@ -1355,7 +1355,7 @@ public static string ToSafeAlias(this string alias, IShortStringHelper shortStri
return a;
}

return char.ToLowerInvariant(a[0]) + a.Substring(1);
return char.ToLowerInvariant(a[0]) + a[1..];
}

/// <summary>
Expand Down
6 changes: 1 addition & 5 deletions src/Umbraco.Core/HashGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,7 @@ public string GenerateHash()
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)
{
Expand Down
4 changes: 3 additions & 1 deletion src/Umbraco.Core/IO/ViewHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ public ViewHelper(FileSystems fileSystems, IDefaultViewContentProvider defaultVi
{
_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 =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ public override object ToConfigurationObject(
}
}

protected TConfiguration? AsConfigurationObject(IDictionary<string, object> configuration,
protected TConfiguration? AsConfigurationObject(
IDictionary<string, object> configuration,
IConfigurationEditorJsonSerializer configurationEditorJsonSerializer) =>
ToConfigurationObject(configuration, configurationEditorJsonSerializer) is TConfiguration configurationObject
? configurationObject
Expand Down
Loading

0 comments on commit ac57566

Please sign in to comment.