Skip to content

Commit 78ab4bd

Browse files
authored
Soft enable CA1810 (#33659)
A lot of the warnings for this rule appear from logging. Given this is going to be replaced by a source generator, this change soft enables the rule while fixing warnings that appear in non-logging code Contributes to #24055
1 parent bb4cf1a commit 78ab4bd

File tree

63 files changed

+213
-253
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+213
-253
lines changed

.editorconfig

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -91,13 +91,19 @@ dotnet_diagnostic.CA1802.severity = warning
9191
# CA1805: Do not initialize unnecessarily
9292
dotnet_diagnostic.CA1805.severity = warning
9393

94-
# CA1823: Remove empty Finalizers
94+
# CA1810: Do not initialize unnecessarily
95+
dotnet_diagnostic.CA1810.severity = suggestion
96+
97+
# CA1821: Remove empty Finalizers
9598
dotnet_diagnostic.CA1821.severity = warning
9699

100+
# CA1822: Make member static
101+
dotnet_diagnostic.CA1822.severity = suggestion
102+
97103
# CA1823: Avoid unused private fields
98104
dotnet_diagnostic.CA1823.severity = warning
99105

100-
# CA1823: Avoid zero-length array allocations
106+
# CA1825: Avoid zero-length array allocations
101107
dotnet_diagnostic.CA1825.severity = warning
102108

103109
# CA1826: Do not use Enumerable methods on indexable collections. Instead use the collection directly
@@ -185,9 +191,21 @@ dotnet_diagnostic.CA2200.severity = warning
185191
# CA2208: Instantiate argument exceptions correctly
186192
dotnet_diagnostic.CA2208.severity = warning
187193

188-
[**/HostFactoryResolver.cs]
189-
# CA1823: Use literals where appropriate
190-
dotnet_diagnostic.CA1802.severity = suggestion
194+
# IDE0035: Remove unreachable code
195+
dotnet_diagnostic.IDE0035.severity = warning
196+
197+
# IDE0036: Order modifiers
198+
dotnet_diagnostic.IDE0036.severity = warning
199+
200+
# IDE0043: Format string contains invalid placeholder
201+
dotnet_diagnostic.IDE0043.severity = warning
202+
203+
# IDE0044: Make field readonly
204+
dotnet_diagnostic.IDE0044.severity = warning
205+
206+
# IDE0073: File header
207+
dotnet_diagnostic.IDE0073.severity = warning
208+
file_header_template = Copyright (c) .NET Foundation. All rights reserved.\nLicensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
191209

192210
[**/{test,samples,perf}/**.{cs,vb}]
193211
# CA1018: Mark attributes with AttributeUsageAttribute

src/Components/Web/src/Forms/InputNumber.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ namespace Microsoft.AspNetCore.Components.Forms
1414
/// </summary>
1515
public class InputNumber<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TValue> : InputBase<TValue>
1616
{
17-
private readonly static string _stepAttributeValue; // Null by default, so only allows whole numbers as per HTML spec
17+
private static readonly string _stepAttributeValue = GetStepAttributeValue();
1818

19-
static InputNumber()
19+
private static string GetStepAttributeValue()
2020
{
2121
// Unwrap Nullable<T>, because InputBase already deals with the Nullable aspect
2222
// of it for us. We will only get asked to parse the T for nonempty inputs.
@@ -28,7 +28,7 @@ static InputNumber()
2828
targetType == typeof(double) ||
2929
targetType == typeof(decimal))
3030
{
31-
_stepAttributeValue = "any";
31+
return "any";
3232
}
3333
else
3434
{

src/Components/WebAssembly/WebAssembly/src/Rendering/RendererRegistry.cs

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,8 @@ internal static class RendererRegistry
1313
// as well as rooting them for GC purposes, since nothing would otherwise be referencing
1414
// them even though we might still receive incoming events from JS.
1515

16+
private static readonly Dictionary<int, WebAssemblyRenderer>? _renderers = OperatingSystem.IsBrowser() ? new() : null;
1617
private static int _nextId;
17-
private static Dictionary<int, WebAssemblyRenderer>? _renderers;
18-
19-
static RendererRegistry()
20-
{
21-
if (OperatingSystem.IsBrowser())
22-
{
23-
_renderers = new Dictionary<int, WebAssemblyRenderer>();
24-
}
25-
}
2618

2719
internal static WebAssemblyRenderer Find(int rendererId)
2820
{

src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -163,21 +163,16 @@ protected override void HandleException(Exception exception)
163163

164164
private static class Log
165165
{
166-
private static readonly Action<ILogger, string, Exception> _unhandledExceptionRenderingComponent;
166+
private static readonly Action<ILogger, string, Exception> _unhandledExceptionRenderingComponent = LoggerMessage.Define<string>(
167+
LogLevel.Critical,
168+
EventIds.UnhandledExceptionRenderingComponent,
169+
"Unhandled exception rendering component: {Message}");
167170

168171
private static class EventIds
169172
{
170173
public static readonly EventId UnhandledExceptionRenderingComponent = new EventId(100, "ExceptionRenderingComponent");
171174
}
172175

173-
static Log()
174-
{
175-
_unhandledExceptionRenderingComponent = LoggerMessage.Define<string>(
176-
LogLevel.Critical,
177-
EventIds.UnhandledExceptionRenderingComponent,
178-
"Unhandled exception rendering component: {Message}");
179-
}
180-
181176
public static void UnhandledExceptionRenderingComponent(ILogger logger, Exception exception)
182177
{
183178
_unhandledExceptionRenderingComponent(

src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,13 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Services
1313
internal class WebAssemblyConsoleLogger<T> : ILogger<T>, ILogger
1414
{
1515
private const string _loglevelPadding = ": ";
16-
private static readonly string _messagePadding;
17-
private static readonly string _newLineWithMessagePadding;
16+
private static readonly string _messagePadding = new(' ', GetLogLevelString(LogLevel.Information).Length + _loglevelPadding.Length);
17+
private static readonly string _newLineWithMessagePadding = Environment.NewLine + _messagePadding;
1818
private static readonly StringBuilder _logBuilder = new StringBuilder();
1919

2020
private readonly string _name;
2121
private readonly WebAssemblyJSRuntime _jsRuntime;
2222

23-
static WebAssemblyConsoleLogger()
24-
{
25-
var logLevelString = GetLogLevelString(LogLevel.Information);
26-
_messagePadding = new string(' ', logLevelString.Length + _loglevelPadding.Length);
27-
_newLineWithMessagePadding = Environment.NewLine + _messagePadding;
28-
}
29-
3023
public WebAssemblyConsoleLogger(IJSRuntime jsRuntime)
3124
: this(string.Empty, (WebAssemblyJSRuntime)jsRuntime) // Cast for DI
3225
{

src/DataProtection/DataProtection/src/KeyManagement/DefaultKeyResolver.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ public DefaultKeyResolver(IOptions<KeyManagementOptions> keyManagementOptions)
4747

4848
public DefaultKeyResolver(IOptions<KeyManagementOptions> keyManagementOptions, ILoggerFactory loggerFactory)
4949
{
50-
_keyPropagationWindow = keyManagementOptions.Value.KeyPropagationWindow;
51-
_maxServerToServerClockSkew = keyManagementOptions.Value.MaxServerClockSkew;
50+
_keyPropagationWindow = KeyManagementOptions.KeyPropagationWindow;
51+
_maxServerToServerClockSkew = KeyManagementOptions.MaxServerClockSkew;
5252
_logger = loggerFactory.CreateLogger<DefaultKeyResolver>();
5353
}
5454

src/DataProtection/DataProtection/src/KeyManagement/KeyManagementOptions.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ internal KeyManagementOptions(KeyManagementOptions other)
7171
/// <remarks>
7272
/// This value is currently fixed at 48 hours.
7373
/// </remarks>
74-
internal TimeSpan KeyPropagationWindow
74+
internal static TimeSpan KeyPropagationWindow
7575
{
7676
get
7777
{
@@ -89,7 +89,7 @@ internal TimeSpan KeyPropagationWindow
8989
/// <remarks>
9090
/// This value is currently fixed at 24 hours.
9191
/// </remarks>
92-
internal TimeSpan KeyRingRefreshPeriod
92+
internal static TimeSpan KeyRingRefreshPeriod
9393
{
9494
get
9595
{
@@ -109,7 +109,7 @@ internal TimeSpan KeyRingRefreshPeriod
109109
/// <remarks>
110110
/// This value is currently fixed at 5 minutes.
111111
/// </remarks>
112-
internal TimeSpan MaxServerClockSkew
112+
internal static TimeSpan MaxServerClockSkew
113113
{
114114
get
115115
{

src/DataProtection/DataProtection/src/KeyManagement/KeyRingProvider.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ private CacheableKeyRing CreateCacheableKeyRingCoreStep2(DateTimeOffset now, Can
128128

129129
_logger.UsingKeyAsDefaultKey(defaultKey.KeyId);
130130

131-
var nextAutoRefreshTime = now + GetRefreshPeriodWithJitter(_keyManagementOptions.KeyRingRefreshPeriod);
131+
var nextAutoRefreshTime = now + GetRefreshPeriodWithJitter(KeyManagementOptions.KeyRingRefreshPeriod);
132132

133133
// The cached keyring should expire at the earliest of (default key expiration, next auto-refresh time).
134134
// Since the refresh period and safety window are not user-settable, we can guarantee that there's at

src/DataProtection/DataProtection/src/TypeForwardingActivator.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ internal object CreateInstance(Type expectedBaseType, string originalTypeName, o
6161
return base.CreateInstance(expectedBaseType, originalTypeName);
6262
}
6363

64-
protected string RemoveVersionFromAssemblyName(string forwardedTypeName)
64+
protected static string RemoveVersionFromAssemblyName(string forwardedTypeName)
6565
{
6666
// Type, Assembly, Version={Version}, Culture={Culture}, PublicKeyToken={Token}
6767

src/DataProtection/DataProtection/src/XmlEncryption/XmlKeyDecryptionOptions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,6 @@ public void AddKeyDecryptionCertificate(X509Certificate2 certificate)
3535
certificates.Add(certificate);
3636
}
3737

38-
private string GetKey(X509Certificate2 cert) => cert.Thumbprint;
38+
private static string GetKey(X509Certificate2 cert) => cert.Thumbprint;
3939
}
4040
}

src/Hosting/Hosting/src/GenericHost/GenericWebHostBuilder.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ public IWebHostBuilder Configure(Action<WebHostBuilderContext, IApplicationBuild
351351
return this;
352352
}
353353

354-
private WebHostBuilderContext GetWebHostBuilderContext(HostBuilderContext context)
354+
private static WebHostBuilderContext GetWebHostBuilderContext(HostBuilderContext context)
355355
{
356356
if (!context.Properties.TryGetValue(typeof(WebHostBuilderContext), out var contextVal))
357357
{

src/Hosting/Hosting/src/Internal/ApplicationLifetime.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ public void NotifyStopped()
101101
}
102102
}
103103

104-
private void ExecuteHandlers(CancellationTokenSource cancel)
104+
private static void ExecuteHandlers(CancellationTokenSource cancel)
105105
{
106106
// Noop if this is already cancelled
107107
if (cancel.IsCancellationRequested)

src/Hosting/Hosting/src/Internal/HostingApplication.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ public void DisposeContext(Context context, Exception? exception)
111111
_httpContextFactory!.Dispose(httpContext);
112112
}
113113

114-
_diagnostics.ContextDisposed(context);
114+
HostingApplicationDiagnostics.ContextDisposed(context);
115115

116116
// Reset the context as it may be pooled
117117
context.Reset();

src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ public void RequestEnd(HttpContext httpContext, Exception? exception, HostingApp
176176
}
177177

178178
[MethodImpl(MethodImplOptions.AggressiveInlining)]
179-
public void ContextDisposed(HostingApplication.Context context)
179+
public static void ContextDisposed(HostingApplication.Context context)
180180
{
181181
if (context.EventLogEnabled)
182182
{

src/Hosting/Hosting/src/Internal/WebHost.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ public async ValueTask DisposeAsync()
356356
await DisposeServiceProviderAsync(_hostingServiceProvider).ConfigureAwait(false);
357357
}
358358

359-
private async ValueTask DisposeServiceProviderAsync(IServiceProvider? serviceProvider)
359+
private static async ValueTask DisposeServiceProviderAsync(IServiceProvider? serviceProvider)
360360
{
361361
switch (serviceProvider)
362362
{

src/Hosting/Hosting/src/Internal/WebHostOptions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ public IEnumerable<string> GetFinalHostingStartupAssemblies()
6969
return HostingStartupAssemblies.Except(HostingStartupExcludeAssemblies, StringComparer.OrdinalIgnoreCase);
7070
}
7171

72-
private IReadOnlyList<string> Split(string value)
72+
private static IReadOnlyList<string> Split(string value)
7373
{
7474
return value?.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
7575
?? Array.Empty<string>();

src/Hosting/Hosting/src/WebHostBuilder.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ private IServiceCollection BuildCommonServices(out AggregateException? hostingSt
338338
return services;
339339
}
340340

341-
private void AddApplicationServices(IServiceCollection services, IServiceProvider hostingServiceProvider)
341+
private static void AddApplicationServices(IServiceCollection services, IServiceProvider hostingServiceProvider)
342342
{
343343
// We are forwarding services from hosting container so hosting container
344344
// can still manage their lifetime (disposal) shared instances with application services.
@@ -352,7 +352,7 @@ private void AddApplicationServices(IServiceCollection services, IServiceProvide
352352
services.Replace(ServiceDescriptor.Singleton(typeof(ActivitySource), activitySource!));
353353
}
354354

355-
private string ResolveContentRootPath(string contentRootPath, string basePath)
355+
private static string ResolveContentRootPath(string contentRootPath, string basePath)
356356
{
357357
if (string.IsNullOrEmpty(contentRootPath))
358358
{

src/Http/Headers/src/ContentDispositionHeaderValue.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,7 @@ private StringSegment Sanitize(StringSegment input)
518518
}
519519

520520
// Returns true if the value starts and ends with a quote
521-
private bool IsQuoted(StringSegment value)
521+
private static bool IsQuoted(StringSegment value)
522522
{
523523
Contract.Assert(value != null);
524524

@@ -527,7 +527,7 @@ private bool IsQuoted(StringSegment value)
527527
}
528528

529529
// tspecials are required to be in a quoted string. Only non-ascii needs to be encoded.
530-
private bool RequiresEncoding(StringSegment input)
530+
private static bool RequiresEncoding(StringSegment input)
531531
{
532532
Contract.Assert(input != null);
533533

@@ -607,7 +607,7 @@ private bool TryDecodeMime(StringSegment input, [NotNullWhen(true)] out string?
607607

608608
// Encode a string using RFC 5987 encoding
609609
// encoding'lang'PercentEncodedSpecials
610-
private string Encode5987(StringSegment input)
610+
private static string Encode5987(StringSegment input)
611611
{
612612
var builder = new StringBuilder("UTF-8\'\'");
613613
for (int i = 0; i < input.Length; i++)
@@ -649,7 +649,7 @@ private static void HexEscape(StringBuilder builder, char c)
649649

650650
// Attempt to decode using RFC 5987 encoding.
651651
// encoding'language'my%20string
652-
private bool TryDecode5987(StringSegment input, [NotNullWhen(true)] out string? output)
652+
private static bool TryDecode5987(StringSegment input, [NotNullWhen(true)] out string? output)
653653
{
654654
output = null;
655655

src/Http/Http/src/Features/FormFeature.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -305,26 +305,26 @@ private static Encoding FilterEncoding(Encoding? encoding)
305305
return encoding;
306306
}
307307

308-
private bool HasApplicationFormContentType([NotNullWhen(true)] MediaTypeHeaderValue? contentType)
308+
private static bool HasApplicationFormContentType([NotNullWhen(true)] MediaTypeHeaderValue? contentType)
309309
{
310310
// Content-Type: application/x-www-form-urlencoded; charset=utf-8
311311
return contentType != null && contentType.MediaType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase);
312312
}
313313

314-
private bool HasMultipartFormContentType([NotNullWhen(true)] MediaTypeHeaderValue? contentType)
314+
private static bool HasMultipartFormContentType([NotNullWhen(true)] MediaTypeHeaderValue? contentType)
315315
{
316316
// Content-Type: multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq
317317
return contentType != null && contentType.MediaType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase);
318318
}
319319

320-
private bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition)
320+
private static bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition)
321321
{
322322
// Content-Disposition: form-data; name="key";
323323
return contentDisposition != null && contentDisposition.DispositionType.Equals("form-data")
324324
&& StringSegment.IsNullOrEmpty(contentDisposition.FileName) && StringSegment.IsNullOrEmpty(contentDisposition.FileNameStar);
325325
}
326326

327-
private bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition)
327+
private static bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition)
328328
{
329329
// Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg"
330330
return contentDisposition != null && contentDisposition.DispositionType.Equals("form-data")

src/Http/Routing/src/DefaultParameterPolicyFactory.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ public override IParameterPolicy Create(RoutePatternParameterPart? parameter, st
6565
return parameterPolicy;
6666
}
6767

68-
private IParameterPolicy InitializeRouteConstraint(
68+
private static IParameterPolicy InitializeRouteConstraint(
6969
bool optional,
7070
IRouteConstraint routeConstraint)
7171
{

src/Http/Routing/src/Matching/DfaMatcher.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ public sealed override Task MatchAsync(HttpContext httpContext)
222222
return (states[destination].Candidates, states[destination].Policies);
223223
}
224224

225-
private void ProcessCaptures(
225+
private static void ProcessCaptures(
226226
KeyValuePair<string, object?>[] slots,
227227
(string parameterName, int segmentIndex, int slotIndex)[] captures,
228228
string path,
@@ -245,7 +245,7 @@ private void ProcessCaptures(
245245
}
246246
}
247247

248-
private void ProcessCatchAll(
248+
private static void ProcessCatchAll(
249249
KeyValuePair<string, object?>[] slots,
250250
in (string parameterName, int segmentIndex, int slotIndex) catchAll,
251251
string path,

src/Http/Routing/src/Matching/EndpointComparer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public int Compare(Endpoint? x, Endpoint? y)
5151
return compare == 0 ? ComparePattern(x, y) : compare;
5252
}
5353

54-
private int ComparePattern(Endpoint x, Endpoint y)
54+
private static int ComparePattern(Endpoint x, Endpoint y)
5555
{
5656
// A RouteEndpoint always comes before a non-RouteEndpoint, regardless of its RawText value
5757
var routeEndpointX = x as RouteEndpoint;

src/Http/Routing/src/Matching/HostMatcherPolicy.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ bool IEndpointSelectorPolicy.AppliesToEndpoints(IReadOnlyList<Endpoint> endpoint
4949
return applies;
5050
}
5151

52-
private bool AppliesToEndpointsCore(IReadOnlyList<Endpoint> endpoints)
52+
private static bool AppliesToEndpointsCore(IReadOnlyList<Endpoint> endpoints)
5353
{
5454
return endpoints.Any(e =>
5555
{
@@ -296,7 +296,7 @@ public PolicyJumpTable BuildJumpTable(int exitDestination, IReadOnlyList<PolicyJ
296296
return new HostPolicyJumpTable(exitDestination, ordered);
297297
}
298298

299-
private int GetScore(in EdgeKey key)
299+
private static int GetScore(in EdgeKey key)
300300
{
301301
// Higher score == lower priority.
302302
if (key.MatchesHost && !key.HasHostWildcard && key.MatchesPort)

0 commit comments

Comments
 (0)