Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolved more warnings, and marked more warning types as errors #16991

Merged
merged 18 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@

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,

Check warning on line 69 in src/Umbraco.Cms.Api.Management/DependencyInjection/BackOfficeAuthPolicyBuilderExtensions.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (contrib)

❌ Getting worse: Large Method

CreatePolicies increases from 87 to 90 lines of code, threshold = 70. Large functions with many lines of code are generally harder to understand and lower the code health. Avoid adding more lines to this function.
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
@@ -1,4 +1,4 @@
using System.Text;

Check warning on line 1 in src/Umbraco.Core/IO/ViewHelper.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (contrib)

❌ New issue: String Heavy Function Arguments

In this module, 40.0% of all arguments to its 9 functions are strings. The threshold for string arguments is 39.0%. The functions in this file have a high ratio of strings as arguments. Avoid adding more.
using Microsoft.Extensions.DependencyInjection;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Models;
Expand All @@ -15,7 +15,9 @@
{
_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
Loading