Skip to content

Commit af9bb41

Browse files
authored
Turn on some CodeAnalysis rules (#32837)
* Turn on some CodeAnalysis rules
1 parent 659e492 commit af9bb41

File tree

119 files changed

+331
-458
lines changed

Some content is hidden

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

119 files changed

+331
-458
lines changed

.editorconfig

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,40 @@ end_of_line = lf
7070
charset = utf-8-bom
7171

7272
[*.{cs,vb}]
73+
# CA1018: Mark attributes with AttributeUsageAttribute
74+
dotnet_diagnostic.CA1018.severity = warning
75+
76+
# CA1047: Do not declare protected member in sealed type
77+
dotnet_diagnostic.CA1047.severity = warning
78+
7379
# CA1305: Specify IFormatProvider
7480
dotnet_diagnostic.CA1305.severity = error
7581

76-
[*.{cs,vb}]
82+
# CA1507: Use nameof to express symbol names
83+
dotnet_diagnostic.CA1507.severity = warning
84+
85+
# CA1725: Parameter names should match base declaration
86+
dotnet_diagnostic.CA1725.severity = suggestion
87+
88+
# CA1823: Use literals where appropriate
89+
dotnet_diagnostic.CA1802.severity = warning
90+
91+
# CA1823: Avoid unused private fields
92+
dotnet_diagnostic.CA1823.severity = warning
93+
7794
# CA2012: Use ValueTask correctly
7895
dotnet_diagnostic.CA2012.severity = warning
96+
97+
[**/HostFactoryResolver.cs]
98+
# CA1823: Use literals where appropriate
99+
dotnet_diagnostic.CA1802.severity = suggestion
100+
79101
[**/{test,perf}/**.{cs,vb}]
102+
# CA1018: Mark attributes with AttributeUsageAttribute
103+
dotnet_diagnostic.CA1018.severity = suggestion
104+
# CA1507: Use nameof to express symbol names
105+
dotnet_diagnostic.CA1507.severity = suggestion
106+
# CA1823: Use literals where appropriate
107+
dotnet_diagnostic.CA1802.severity = suggestion
108+
# CA2012: Use ValueTask correctly
80109
dotnet_diagnostic.CA2012.severity = suggestion

src/Analyzers/Analyzers/src/WellKnownFeatures.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@ namespace Microsoft.AspNetCore.Analyzers
55
{
66
internal static class WellKnownFeatures
77
{
8-
public static readonly string SignalR = nameof(SignalR);
8+
public const string SignalR = nameof(SignalR);
99
}
1010
}

src/Antiforgery/src/Internal/BinaryBlob.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,11 @@ public BinaryBlob(int bitLength, byte[] data)
2828
{
2929
if (bitLength < 32 || bitLength % 8 != 0)
3030
{
31-
throw new ArgumentOutOfRangeException("bitLength");
31+
throw new ArgumentOutOfRangeException(nameof(bitLength));
3232
}
3333
if (data == null || data.Length != bitLength / 8)
3434
{
35-
throw new ArgumentOutOfRangeException("data");
35+
throw new ArgumentOutOfRangeException(nameof(data));
3636
}
3737

3838
_data = data;

src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Antiforgery
1111
{
1212
internal class DefaultAntiforgeryTokenSerializer : IAntiforgeryTokenSerializer
1313
{
14-
private static readonly string Purpose = "Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1";
14+
private const string Purpose = "Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1";
1515
private const byte TokenVersion = 0x01;
1616

1717
private readonly IDataProtector _cryptoSystem;

src/Components/Analyzers/src/ComponentsApi.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,26 @@ namespace Microsoft.AspNetCore.Components.Analyzers
77
// Keep these in sync with the actual definitions
88
internal static class ComponentsApi
99
{
10-
public static readonly string AssemblyName = "Microsoft.AspNetCore.Components";
10+
public const string AssemblyName = "Microsoft.AspNetCore.Components";
1111

1212
public static class ParameterAttribute
1313
{
14-
public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.ParameterAttribute";
15-
public static readonly string MetadataName = FullTypeName;
14+
public const string FullTypeName = "Microsoft.AspNetCore.Components.ParameterAttribute";
15+
public const string MetadataName = FullTypeName;
1616

17-
public static readonly string CaptureUnmatchedValues = "CaptureUnmatchedValues";
17+
public const string CaptureUnmatchedValues = "CaptureUnmatchedValues";
1818
}
1919

2020
public static class CascadingParameterAttribute
2121
{
22-
public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.CascadingParameterAttribute";
23-
public static readonly string MetadataName = FullTypeName;
22+
public const string FullTypeName = "Microsoft.AspNetCore.Components.CascadingParameterAttribute";
23+
public const string MetadataName = FullTypeName;
2424
}
2525

2626
public static class IComponent
2727
{
28-
public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.IComponent";
29-
public static readonly string MetadataName = FullTypeName;
28+
public const string FullTypeName = "Microsoft.AspNetCore.Components.IComponent";
29+
public const string MetadataName = FullTypeName;
3030
}
3131
}
3232
}

src/Components/Components/src/ComponentFactory.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Components
1313
{
1414
internal sealed class ComponentFactory
1515
{
16-
private static readonly BindingFlags _injectablePropertyBindingFlags
16+
private const BindingFlags _injectablePropertyBindingFlags
1717
= BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
1818

1919
private readonly ConcurrentDictionary<Type, Action<IServiceProvider, IComponent>> _cachedInitializers = new();

src/Components/Samples/IgnitorSample/Program.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@ namespace IgnitorSample
1414
/// </summary>
1515
class Program
1616
{
17-
private static readonly string ServerUrl = "https://localhost:5001";
18-
private static readonly JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
17+
private const string ServerUrl = "https://localhost:5001";
1918

2019
static async Task Main(string[] args)
2120
{

src/Components/Server/src/BlazorPack/BlazorPackHubProtocol.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Components.Server.BlazorPack
1717
internal sealed class BlazorPackHubProtocol : IHubProtocol
1818
{
1919
internal const string ProtocolName = "blazorpack";
20-
private static readonly int ProtocolVersion = 1;
20+
private const int ProtocolVersion = 1;
2121

2222
private readonly BlazorPackHubProtocolWorker _worker = new BlazorPackHubProtocolWorker();
2323

src/Components/Shared/src/BrowserNavigationManagerInterop.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@ namespace Microsoft.AspNetCore.Components.Web
66
// Shared interop constants
77
internal static class BrowserNavigationManagerInterop
88
{
9-
private static readonly string Prefix = "Blazor._internal.navigationManager.";
9+
private const string Prefix = "Blazor._internal.navigationManager.";
1010

11-
public static readonly string EnableNavigationInterception = Prefix + "enableNavigationInterception";
11+
public const string EnableNavigationInterception = Prefix + "enableNavigationInterception";
1212

13-
public static readonly string GetLocationHref = Prefix + "getUnmarshalledLocationHref";
13+
public const string GetLocationHref = Prefix + "getUnmarshalledLocationHref";
1414

15-
public static readonly string GetBaseUri = Prefix + "getUnmarshalledBaseURI";
15+
public const string GetBaseUri = Prefix + "getUnmarshalledBaseURI";
1616

17-
public static readonly string NavigateTo = Prefix + "navigateTo";
17+
public const string NavigateTo = Prefix + "navigateTo";
1818
}
1919
}

src/Components/WebAssembly/Samples/HostedBlazorWebassemblyApp/Server/Controllers/WeatherForecastController.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,6 @@ namespace HostedBlazorWebassemblyApp.Server.Controllers
1010
[Route("[controller]")]
1111
public class WeatherForecastController : ControllerBase
1212
{
13-
private static readonly string[] Summaries = new[]
14-
{
15-
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
16-
};
1713
private readonly IWeatherForecastService _forecastService;
1814
private readonly ILogger<WeatherForecastController> _logger;
1915

src/Components/WebAssembly/WebAssembly/src/Hosting/RegisteredComponentsInterop.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,18 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
55
{
66
internal class RegisteredComponentsInterop
77
{
8-
private static readonly string Prefix = "Blazor._internal.registeredComponents.";
8+
private const string Prefix = "Blazor._internal.registeredComponents.";
99

10-
public static readonly string GetRegisteredComponentsCount = Prefix + "getRegisteredComponentsCount";
10+
public const string GetRegisteredComponentsCount = Prefix + "getRegisteredComponentsCount";
1111

12-
public static readonly string GetId = Prefix + "getId";
12+
public const string GetId = Prefix + "getId";
1313

14-
public static readonly string GetAssembly = Prefix + "getAssembly";
14+
public const string GetAssembly = Prefix + "getAssembly";
1515

16-
public static readonly string GetTypeName = Prefix + "getTypeName";
16+
public const string GetTypeName = Prefix + "getTypeName";
1717

18-
public static readonly string GetParameterDefinitions = Prefix + "getParameterDefinitions";
18+
public const string GetParameterDefinitions = Prefix + "getParameterDefinitions";
1919

20-
public static readonly string GetParameterValues = Prefix + "getParameterValues";
20+
public const string GetParameterValues = Prefix + "getParameterValues";
2121
}
2222
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Services
1212
{
1313
internal class WebAssemblyConsoleLogger<T> : ILogger<T>, ILogger
1414
{
15-
private static readonly string _loglevelPadding = ": ";
15+
private const string _loglevelPadding = ": ";
1616
private static readonly string _messagePadding;
1717
private static readonly string _newLineWithMessagePadding;
1818
private static readonly StringBuilder _logBuilder = new StringBuilder();

src/FileProviders/Embedded/src/EmbeddedFileProvider.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public EmbeddedFileProvider(Assembly assembly, string? baseNamespace)
4545
{
4646
if (assembly == null)
4747
{
48-
throw new ArgumentNullException("assembly");
48+
throw new ArgumentNullException(nameof(assembly));
4949
}
5050

5151
_baseNamespace = string.IsNullOrEmpty(baseNamespace) ? string.Empty : baseNamespace + ".";

src/FileProviders/Embedded/src/Manifest/ManifestParser.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ namespace Microsoft.Extensions.FileProviders.Embedded.Manifest
1313
{
1414
internal static class ManifestParser
1515
{
16-
private static readonly string DefaultManifestName = "Microsoft.Extensions.FileProviders.Embedded.Manifest.xml";
16+
private const string DefaultManifestName = "Microsoft.Extensions.FileProviders.Embedded.Manifest.xml";
1717

1818
public static EmbeddedFilesManifest Parse(Assembly assembly)
1919
{

src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,13 @@ private XElement BuildNode(Entry entry)
7272

7373
private class ElementNames
7474
{
75-
public static readonly string Directory = "Directory";
76-
public static readonly string Name = "Name";
77-
public static readonly string FileSystem = "FileSystem";
78-
public static readonly string Root = "Manifest";
79-
public static readonly string File = "File";
80-
public static readonly string ResourcePath = "ResourcePath";
81-
public static readonly string ManifestVersion = "ManifestVersion";
75+
public const string Directory = "Directory";
76+
public const string Name = "Name";
77+
public const string FileSystem = "FileSystem";
78+
public const string Root = "Manifest";
79+
public const string File = "File";
80+
public const string ResourcePath = "ResourcePath";
81+
public const string ManifestVersion = "ManifestVersion";
8282
}
8383
}
8484
}

src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ private static class Log
209209
"Running health check {HealthCheckName}");
210210

211211
// These are separate so they can have different log levels
212-
private static readonly string HealthCheckEndText = "Health check {HealthCheckName} with status {HealthStatus} completed after {ElapsedMilliseconds}ms with message '{HealthCheckDescription}'";
212+
private const string HealthCheckEndText = "Health check {HealthCheckName} with status {HealthStatus} completed after {ElapsedMilliseconds}ms with message '{HealthCheckDescription}'";
213213

214214
private static readonly Action<ILogger, string, double, HealthStatus, string?, Exception?> _healthCheckEndHealthy = LoggerMessage.Define<string, double, HealthStatus, string?>(
215215
LogLevel.Debug,
@@ -226,11 +226,6 @@ private static class Log
226226
EventIds.HealthCheckEnd,
227227
HealthCheckEndText);
228228

229-
private static readonly Action<ILogger, string, double, HealthStatus, string?, Exception?> _healthCheckEndFailed = LoggerMessage.Define<string, double, HealthStatus, string?>(
230-
LogLevel.Error,
231-
EventIds.HealthCheckEnd,
232-
HealthCheckEndText);
233-
234229
private static readonly Action<ILogger, string, double, Exception?> _healthCheckError = LoggerMessage.Define<string, double>(
235230
LogLevel.Error,
236231
EventIds.HealthCheckError,

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Hosting
2525
{
2626
internal class WebHost : IWebHost, IAsyncDisposable
2727
{
28-
private static readonly string DeprecatedServerUrlsKey = "server.urls";
28+
private const string DeprecatedServerUrlsKey = "server.urls";
2929

3030
private readonly IServiceCollection _applicationServiceCollection;
3131
private IStartup? _startup;

src/Http/Headers/src/HeaderUtilities.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ namespace Microsoft.Net.Http.Headers
1616
/// </summary>
1717
public static class HeaderUtilities
1818
{
19-
private static readonly int _qualityValueMaxCharCount = 10; // Little bit more permissive than RFC7231 5.3.1
19+
private const int _qualityValueMaxCharCount = 10; // Little bit more permissive than RFC7231 5.3.1
2020
private const string QualityName = "q";
2121
internal const string BytesUnit = "bytes";
2222

src/Http/Http.Abstractions/test/MapPathMiddlewareTests.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@ namespace Microsoft.AspNetCore.Builder.Extensions
1111
{
1212
public class MapPathMiddlewareTests
1313
{
14-
private static readonly Action<IApplicationBuilder> ActionNotImplemented = new Action<IApplicationBuilder>(_ => { throw new NotImplementedException(); });
15-
1614
private static Task Success(HttpContext context)
1715
{
1816
context.Response.StatusCode = 200;

src/Http/Http.Extensions/src/RequestDelegateFactory.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ public static class RequestDelegateFactory
5050
private static readonly MemberExpression RouteValuesExpr = Expression.Property(HttpRequestExpr, nameof(HttpRequest.RouteValues));
5151
private static readonly MemberExpression QueryExpr = Expression.Property(HttpRequestExpr, nameof(HttpRequest.Query));
5252
private static readonly MemberExpression HeadersExpr = Expression.Property(HttpRequestExpr, nameof(HttpRequest.Headers));
53-
private static readonly MemberExpression FormExpr = Expression.Property(HttpRequestExpr, nameof(HttpRequest.Form));
5453
private static readonly MemberExpression StatusCodeExpr = Expression.Property(HttpResponseExpr, nameof(HttpResponse.StatusCode));
5554
private static readonly MemberExpression CompletedTaskExpr = Expression.Property(null, (PropertyInfo)GetMemberInfo<Func<Task>>(() => Task.CompletedTask));
5655

src/Http/Http/src/Features/ResponseCookiesFeature.cs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@ namespace Microsoft.AspNetCore.Http.Features
1212
/// </summary>
1313
public class ResponseCookiesFeature : IResponseCookiesFeature
1414
{
15-
// Lambda hoisted to static readonly field to improve inlining https://github.com/dotnet/roslyn/issues/13624
16-
private readonly static Func<IFeatureCollection, IHttpResponseFeature?> _nullResponseFeature = f => null;
17-
1815
private readonly IFeatureCollection _features;
1916
private IResponseCookies? _cookiesCollection;
2017

src/Http/Http/src/QueryCollection.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ public class QueryCollection : IQueryCollection
1818
/// </summary>
1919
public static readonly QueryCollection Empty = new QueryCollection();
2020
private static readonly string[] EmptyKeys = Array.Empty<string>();
21-
private static readonly StringValues[] EmptyValues = Array.Empty<StringValues>();
2221
private static readonly Enumerator EmptyEnumerator = new Enumerator();
2322
// Pre-box
2423
private static readonly IEnumerator<KeyValuePair<string, StringValues>> EmptyIEnumeratorType = EmptyEnumerator;

src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ namespace Microsoft.AspNetCore.Routing.Matching
2020
public sealed class HttpMethodMatcherPolicy : MatcherPolicy, IEndpointComparerPolicy, INodeBuilderPolicy, IEndpointSelectorPolicy
2121
{
2222
// Used in tests
23-
internal static readonly string OriginHeader = "Origin";
24-
internal static readonly string AccessControlRequestMethod = "Access-Control-Request-Method";
2523
internal static readonly string PreflightHttpMethod = HttpMethods.Options;
2624

2725
// Used in tests

src/Http/Routing/src/Matching/ILEmitTrieJumpTable.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@ namespace Microsoft.AspNetCore.Routing.Matching
1515
// 2. The generated IL only supports ASCII in the URL path
1616
internal class ILEmitTrieJumpTable : JumpTable
1717
{
18-
private const int NotAscii = int.MinValue;
19-
2018
private readonly int _defaultDestination;
2119
private readonly int _exitDestination;
2220
private readonly (string text, int destination)[] _entries;
@@ -54,7 +52,7 @@ public override int GetDestination(string path, PathSegment segment)
5452
{
5553
return _getDestination(path, segment);
5654
}
57-
55+
5856
// Used when we haven't yet initialized the IL trie. We defer compilation of the IL for startup
5957
// performance.
6058
private int FallbackGetDestination(string path, PathSegment segment)

src/Http/Routing/src/Matching/JumpTableBuilder.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
88
{
99
internal static class JumpTableBuilder
1010
{
11-
public static readonly int InvalidDestination = -1;
11+
public const int InvalidDestination = -1;
1212

1313
public static JumpTable Build(int defaultDestination, int exitDestination, (string text, int destination)[] pathEntries)
1414
{

src/Http/Routing/src/Patterns/RoutePatternMatcher.cs

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,10 @@ namespace Microsoft.AspNetCore.Routing
1313
{
1414
internal class RoutePatternMatcher
1515
{
16-
private const string SeparatorString = "/";
17-
private const char SeparatorChar = '/';
18-
1916
// Perf: This is a cache to avoid looking things up in 'Defaults' each request.
2017
private readonly bool[] _hasDefaultValue;
2118
private readonly object[] _defaultValues;
2219

23-
private static readonly char[] Delimiters = new char[] { SeparatorChar };
24-
2520
public RoutePatternMatcher(
2621
RoutePattern pattern,
2722
RouteValueDictionary defaults)
@@ -83,7 +78,7 @@ public bool TryMatch(PathString path, RouteValueDictionary values)
8378
// The most common case would be a literal segment that doesn't match.
8479
//
8580
// On the second pass, we're almost certainly going to match the URL, so go ahead and allocate the 'values'
86-
// and start capturing strings.
81+
// and start capturing strings.
8782
foreach (var stringSegment in pathTokenizer)
8883
{
8984
if (stringSegment.Length == 0)
@@ -299,7 +294,7 @@ internal static bool MatchComplexSegment(
299294
var indexOfLastSegment = routeSegment.Parts.Count - 1;
300295

301296
// We match the request to the template starting at the rightmost parameter
302-
// If the last segment of template is optional, then request can match the
297+
// If the last segment of template is optional, then request can match the
303298
// template with or without the last parameter. So we start with regular matching,
304299
// but if it doesn't match, we start with next to last parameter. Example:
305300
// Template: {p1}/{p2}.{p3?}. If the request is one/two.three it will match right away
@@ -470,7 +465,7 @@ private static bool MatchComplexSegmentCore(
470465
{
471466
// If we're here that means we have a segment that contains multiple sub-segments.
472467
// For these segments all parameters must have non-empty values. If the parameter
473-
// has an empty value it's not a match.
468+
// has an empty value it's not a match.
474469
return false;
475470

476471
}

0 commit comments

Comments
 (0)