Skip to content

Turn on some CodeAnalysis rules #32837

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

Merged
merged 3 commits into from
May 20, 2021
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
31 changes: 30 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,40 @@ end_of_line = lf
charset = utf-8-bom

[*.{cs,vb}]
# CA1018: Mark attributes with AttributeUsageAttribute
dotnet_diagnostic.CA1018.severity = warning

# CA1047: Do not declare protected member in sealed type
dotnet_diagnostic.CA1047.severity = warning

# CA1305: Specify IFormatProvider
dotnet_diagnostic.CA1305.severity = error

[*.{cs,vb}]
# CA1507: Use nameof to express symbol names
dotnet_diagnostic.CA1507.severity = warning

# CA1725: Parameter names should match base declaration
dotnet_diagnostic.CA1725.severity = suggestion

# CA1823: Use literals where appropriate
dotnet_diagnostic.CA1802.severity = warning

# CA1823: Avoid unused private fields
dotnet_diagnostic.CA1823.severity = warning

# CA2012: Use ValueTask correctly
dotnet_diagnostic.CA2012.severity = warning

[**/HostFactoryResolver.cs]
# CA1823: Use literals where appropriate
dotnet_diagnostic.CA1802.severity = suggestion

[**/{test,perf}/**.{cs,vb}]
# CA1018: Mark attributes with AttributeUsageAttribute
dotnet_diagnostic.CA1018.severity = suggestion
# CA1507: Use nameof to express symbol names
dotnet_diagnostic.CA1507.severity = suggestion
# CA1823: Use literals where appropriate
dotnet_diagnostic.CA1802.severity = suggestion
# CA2012: Use ValueTask correctly
dotnet_diagnostic.CA2012.severity = suggestion
2 changes: 1 addition & 1 deletion src/Analyzers/Analyzers/src/WellKnownFeatures.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ namespace Microsoft.AspNetCore.Analyzers
{
internal static class WellKnownFeatures
{
public static readonly string SignalR = nameof(SignalR);
public const string SignalR = nameof(SignalR);
}
}
4 changes: 2 additions & 2 deletions src/Antiforgery/src/Internal/BinaryBlob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ public BinaryBlob(int bitLength, byte[] data)
{
if (bitLength < 32 || bitLength % 8 != 0)
{
throw new ArgumentOutOfRangeException("bitLength");
throw new ArgumentOutOfRangeException(nameof(bitLength));
}
if (data == null || data.Length != bitLength / 8)
{
throw new ArgumentOutOfRangeException("data");
throw new ArgumentOutOfRangeException(nameof(data));
}

_data = data;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Antiforgery
{
internal class DefaultAntiforgeryTokenSerializer : IAntiforgeryTokenSerializer
{
private static readonly string Purpose = "Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1";
private const string Purpose = "Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1";
private const byte TokenVersion = 0x01;

private readonly IDataProtector _cryptoSystem;
Expand Down
16 changes: 8 additions & 8 deletions src/Components/Analyzers/src/ComponentsApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,26 @@ namespace Microsoft.AspNetCore.Components.Analyzers
// Keep these in sync with the actual definitions
internal static class ComponentsApi
{
public static readonly string AssemblyName = "Microsoft.AspNetCore.Components";
public const string AssemblyName = "Microsoft.AspNetCore.Components";

public static class ParameterAttribute
{
public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.ParameterAttribute";
public static readonly string MetadataName = FullTypeName;
public const string FullTypeName = "Microsoft.AspNetCore.Components.ParameterAttribute";
public const string MetadataName = FullTypeName;

public static readonly string CaptureUnmatchedValues = "CaptureUnmatchedValues";
public const string CaptureUnmatchedValues = "CaptureUnmatchedValues";
}

public static class CascadingParameterAttribute
{
public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.CascadingParameterAttribute";
public static readonly string MetadataName = FullTypeName;
public const string FullTypeName = "Microsoft.AspNetCore.Components.CascadingParameterAttribute";
public const string MetadataName = FullTypeName;
}

public static class IComponent
{
public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.IComponent";
public static readonly string MetadataName = FullTypeName;
public const string FullTypeName = "Microsoft.AspNetCore.Components.IComponent";
public const string MetadataName = FullTypeName;
}
}
}
2 changes: 1 addition & 1 deletion src/Components/Components/src/ComponentFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Components
{
internal sealed class ComponentFactory
{
private static readonly BindingFlags _injectablePropertyBindingFlags
private const BindingFlags _injectablePropertyBindingFlags
= BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

private readonly ConcurrentDictionary<Type, Action<IServiceProvider, IComponent>> _cachedInitializers = new();
Expand Down
3 changes: 1 addition & 2 deletions src/Components/Samples/IgnitorSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ namespace IgnitorSample
/// </summary>
class Program
{
private static readonly string ServerUrl = "https://localhost:5001";
private static readonly JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
private const string ServerUrl = "https://localhost:5001";

static async Task Main(string[] args)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Components.Server.BlazorPack
internal sealed class BlazorPackHubProtocol : IHubProtocol
{
internal const string ProtocolName = "blazorpack";
private static readonly int ProtocolVersion = 1;
private const int ProtocolVersion = 1;

private readonly BlazorPackHubProtocolWorker _worker = new BlazorPackHubProtocolWorker();

Expand Down
10 changes: 5 additions & 5 deletions src/Components/Shared/src/BrowserNavigationManagerInterop.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ namespace Microsoft.AspNetCore.Components.Web
// Shared interop constants
internal static class BrowserNavigationManagerInterop
{
private static readonly string Prefix = "Blazor._internal.navigationManager.";
private const string Prefix = "Blazor._internal.navigationManager.";

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

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

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

public static readonly string NavigateTo = Prefix + "navigateTo";
public const string NavigateTo = Prefix + "navigateTo";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@ namespace HostedBlazorWebassemblyApp.Server.Controllers
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly IWeatherForecastService _forecastService;
private readonly ILogger<WeatherForecastController> _logger;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
{
internal class RegisteredComponentsInterop
{
private static readonly string Prefix = "Blazor._internal.registeredComponents.";
private const string Prefix = "Blazor._internal.registeredComponents.";

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

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

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

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

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

public static readonly string GetParameterValues = Prefix + "getParameterValues";
public const string GetParameterValues = Prefix + "getParameterValues";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Services
{
internal class WebAssemblyConsoleLogger<T> : ILogger<T>, ILogger
{
private static readonly string _loglevelPadding = ": ";
private const string _loglevelPadding = ": ";
private static readonly string _messagePadding;
private static readonly string _newLineWithMessagePadding;
private static readonly StringBuilder _logBuilder = new StringBuilder();
Expand Down
2 changes: 1 addition & 1 deletion src/FileProviders/Embedded/src/EmbeddedFileProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public EmbeddedFileProvider(Assembly assembly, string? baseNamespace)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
throw new ArgumentNullException(nameof(assembly));
}

_baseNamespace = string.IsNullOrEmpty(baseNamespace) ? string.Empty : baseNamespace + ".";
Expand Down
2 changes: 1 addition & 1 deletion src/FileProviders/Embedded/src/Manifest/ManifestParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace Microsoft.Extensions.FileProviders.Embedded.Manifest
{
internal static class ManifestParser
{
private static readonly string DefaultManifestName = "Microsoft.Extensions.FileProviders.Embedded.Manifest.xml";
private const string DefaultManifestName = "Microsoft.Extensions.FileProviders.Embedded.Manifest.xml";

public static EmbeddedFilesManifest Parse(Assembly assembly)
{
Expand Down
14 changes: 7 additions & 7 deletions src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,13 @@ private XElement BuildNode(Entry entry)

private class ElementNames
{
public static readonly string Directory = "Directory";
public static readonly string Name = "Name";
public static readonly string FileSystem = "FileSystem";
public static readonly string Root = "Manifest";
public static readonly string File = "File";
public static readonly string ResourcePath = "ResourcePath";
public static readonly string ManifestVersion = "ManifestVersion";
public const string Directory = "Directory";
public const string Name = "Name";
public const string FileSystem = "FileSystem";
public const string Root = "Manifest";
public const string File = "File";
public const string ResourcePath = "ResourcePath";
public const string ManifestVersion = "ManifestVersion";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ private static class Log
"Running health check {HealthCheckName}");

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

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

private static readonly Action<ILogger, string, double, HealthStatus, string?, Exception?> _healthCheckEndFailed = LoggerMessage.Define<string, double, HealthStatus, string?>(
LogLevel.Error,
EventIds.HealthCheckEnd,
HealthCheckEndText);

private static readonly Action<ILogger, string, double, Exception?> _healthCheckError = LoggerMessage.Define<string, double>(
LogLevel.Error,
EventIds.HealthCheckError,
Expand Down
2 changes: 1 addition & 1 deletion src/Hosting/Hosting/src/Internal/WebHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Hosting
{
internal class WebHost : IWebHost, IAsyncDisposable
{
private static readonly string DeprecatedServerUrlsKey = "server.urls";
private const string DeprecatedServerUrlsKey = "server.urls";

private readonly IServiceCollection _applicationServiceCollection;
private IStartup? _startup;
Expand Down
2 changes: 1 addition & 1 deletion src/Http/Headers/src/HeaderUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ namespace Microsoft.Net.Http.Headers
/// </summary>
public static class HeaderUtilities
{
private static readonly int _qualityValueMaxCharCount = 10; // Little bit more permissive than RFC7231 5.3.1
private const int _qualityValueMaxCharCount = 10; // Little bit more permissive than RFC7231 5.3.1
private const string QualityName = "q";
internal const string BytesUnit = "bytes";

Expand Down
2 changes: 0 additions & 2 deletions src/Http/Http.Abstractions/test/MapPathMiddlewareTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ namespace Microsoft.AspNetCore.Builder.Extensions
{
public class MapPathMiddlewareTests
{
private static readonly Action<IApplicationBuilder> ActionNotImplemented = new Action<IApplicationBuilder>(_ => { throw new NotImplementedException(); });

private static Task Success(HttpContext context)
{
context.Response.StatusCode = 200;
Expand Down
1 change: 0 additions & 1 deletion src/Http/Http.Extensions/src/RequestDelegateFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ public static class RequestDelegateFactory
private static readonly MemberExpression RouteValuesExpr = Expression.Property(HttpRequestExpr, nameof(HttpRequest.RouteValues));
private static readonly MemberExpression QueryExpr = Expression.Property(HttpRequestExpr, nameof(HttpRequest.Query));
private static readonly MemberExpression HeadersExpr = Expression.Property(HttpRequestExpr, nameof(HttpRequest.Headers));
private static readonly MemberExpression FormExpr = Expression.Property(HttpRequestExpr, nameof(HttpRequest.Form));
private static readonly MemberExpression StatusCodeExpr = Expression.Property(HttpResponseExpr, nameof(HttpResponse.StatusCode));
private static readonly MemberExpression CompletedTaskExpr = Expression.Property(null, (PropertyInfo)GetMemberInfo<Func<Task>>(() => Task.CompletedTask));

Expand Down
3 changes: 0 additions & 3 deletions src/Http/Http/src/Features/ResponseCookiesFeature.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ namespace Microsoft.AspNetCore.Http.Features
/// </summary>
public class ResponseCookiesFeature : IResponseCookiesFeature
{
// Lambda hoisted to static readonly field to improve inlining https://github.com/dotnet/roslyn/issues/13624
private readonly static Func<IFeatureCollection, IHttpResponseFeature?> _nullResponseFeature = f => null;

private readonly IFeatureCollection _features;
private IResponseCookies? _cookiesCollection;

Expand Down
1 change: 0 additions & 1 deletion src/Http/Http/src/QueryCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ public class QueryCollection : IQueryCollection
/// </summary>
public static readonly QueryCollection Empty = new QueryCollection();
private static readonly string[] EmptyKeys = Array.Empty<string>();
private static readonly StringValues[] EmptyValues = Array.Empty<StringValues>();
private static readonly Enumerator EmptyEnumerator = new Enumerator();
// Pre-box
private static readonly IEnumerator<KeyValuePair<string, StringValues>> EmptyIEnumeratorType = EmptyEnumerator;
Expand Down
2 changes: 0 additions & 2 deletions src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ namespace Microsoft.AspNetCore.Routing.Matching
public sealed class HttpMethodMatcherPolicy : MatcherPolicy, IEndpointComparerPolicy, INodeBuilderPolicy, IEndpointSelectorPolicy
{
// Used in tests
internal static readonly string OriginHeader = "Origin";
internal static readonly string AccessControlRequestMethod = "Access-Control-Request-Method";
internal static readonly string PreflightHttpMethod = HttpMethods.Options;

// Used in tests
Expand Down
4 changes: 1 addition & 3 deletions src/Http/Routing/src/Matching/ILEmitTrieJumpTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ namespace Microsoft.AspNetCore.Routing.Matching
// 2. The generated IL only supports ASCII in the URL path
internal class ILEmitTrieJumpTable : JumpTable
{
private const int NotAscii = int.MinValue;

private readonly int _defaultDestination;
private readonly int _exitDestination;
private readonly (string text, int destination)[] _entries;
Expand Down Expand Up @@ -54,7 +52,7 @@ public override int GetDestination(string path, PathSegment segment)
{
return _getDestination(path, segment);
}

// Used when we haven't yet initialized the IL trie. We defer compilation of the IL for startup
// performance.
private int FallbackGetDestination(string path, PathSegment segment)
Expand Down
2 changes: 1 addition & 1 deletion src/Http/Routing/src/Matching/JumpTableBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
{
internal static class JumpTableBuilder
{
public static readonly int InvalidDestination = -1;
public const int InvalidDestination = -1;

public static JumpTable Build(int defaultDestination, int exitDestination, (string text, int destination)[] pathEntries)
{
Expand Down
11 changes: 3 additions & 8 deletions src/Http/Routing/src/Patterns/RoutePatternMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,10 @@ namespace Microsoft.AspNetCore.Routing
{
internal class RoutePatternMatcher
{
private const string SeparatorString = "/";
private const char SeparatorChar = '/';

// Perf: This is a cache to avoid looking things up in 'Defaults' each request.
private readonly bool[] _hasDefaultValue;
private readonly object[] _defaultValues;

private static readonly char[] Delimiters = new char[] { SeparatorChar };

public RoutePatternMatcher(
RoutePattern pattern,
RouteValueDictionary defaults)
Expand Down Expand Up @@ -83,7 +78,7 @@ public bool TryMatch(PathString path, RouteValueDictionary values)
// The most common case would be a literal segment that doesn't match.
//
// On the second pass, we're almost certainly going to match the URL, so go ahead and allocate the 'values'
// and start capturing strings.
// and start capturing strings.
foreach (var stringSegment in pathTokenizer)
{
if (stringSegment.Length == 0)
Expand Down Expand Up @@ -299,7 +294,7 @@ internal static bool MatchComplexSegment(
var indexOfLastSegment = routeSegment.Parts.Count - 1;

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

}
Expand Down
Loading