diff --git a/.editorconfig b/.editorconfig index 44bc0ef547c5..fade2a27dcd9 100644 --- a/.editorconfig +++ b/.editorconfig @@ -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 diff --git a/src/Analyzers/Analyzers/src/WellKnownFeatures.cs b/src/Analyzers/Analyzers/src/WellKnownFeatures.cs index 7c6e82023294..1ad0d7b84260 100644 --- a/src/Analyzers/Analyzers/src/WellKnownFeatures.cs +++ b/src/Analyzers/Analyzers/src/WellKnownFeatures.cs @@ -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); } } diff --git a/src/Antiforgery/src/Internal/BinaryBlob.cs b/src/Antiforgery/src/Internal/BinaryBlob.cs index a33f727bd401..0cc2c4a38bef 100644 --- a/src/Antiforgery/src/Internal/BinaryBlob.cs +++ b/src/Antiforgery/src/Internal/BinaryBlob.cs @@ -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; diff --git a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs index fff8aa9175ce..474205b64df9 100644 --- a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs +++ b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs @@ -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; diff --git a/src/Components/Analyzers/src/ComponentsApi.cs b/src/Components/Analyzers/src/ComponentsApi.cs index 73ceff39fd40..425287d3daf7 100644 --- a/src/Components/Analyzers/src/ComponentsApi.cs +++ b/src/Components/Analyzers/src/ComponentsApi.cs @@ -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; } } } diff --git a/src/Components/Components/src/ComponentFactory.cs b/src/Components/Components/src/ComponentFactory.cs index c3235a2be405..ba8d5affb4be 100644 --- a/src/Components/Components/src/ComponentFactory.cs +++ b/src/Components/Components/src/ComponentFactory.cs @@ -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> _cachedInitializers = new(); diff --git a/src/Components/Samples/IgnitorSample/Program.cs b/src/Components/Samples/IgnitorSample/Program.cs index e272dc5b8787..9f1075e4a4b9 100644 --- a/src/Components/Samples/IgnitorSample/Program.cs +++ b/src/Components/Samples/IgnitorSample/Program.cs @@ -14,8 +14,7 @@ namespace IgnitorSample /// 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) { diff --git a/src/Components/Server/src/BlazorPack/BlazorPackHubProtocol.cs b/src/Components/Server/src/BlazorPack/BlazorPackHubProtocol.cs index 3fca949e0880..3477e3f0212d 100644 --- a/src/Components/Server/src/BlazorPack/BlazorPackHubProtocol.cs +++ b/src/Components/Server/src/BlazorPack/BlazorPackHubProtocol.cs @@ -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(); diff --git a/src/Components/Shared/src/BrowserNavigationManagerInterop.cs b/src/Components/Shared/src/BrowserNavigationManagerInterop.cs index ea3e4ec4318c..fc51b94e4701 100644 --- a/src/Components/Shared/src/BrowserNavigationManagerInterop.cs +++ b/src/Components/Shared/src/BrowserNavigationManagerInterop.cs @@ -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"; } } diff --git a/src/Components/WebAssembly/Samples/HostedBlazorWebassemblyApp/Server/Controllers/WeatherForecastController.cs b/src/Components/WebAssembly/Samples/HostedBlazorWebassemblyApp/Server/Controllers/WeatherForecastController.cs index 5b5cfdab88b4..f6e04258c104 100644 --- a/src/Components/WebAssembly/Samples/HostedBlazorWebassemblyApp/Server/Controllers/WeatherForecastController.cs +++ b/src/Components/WebAssembly/Samples/HostedBlazorWebassemblyApp/Server/Controllers/WeatherForecastController.cs @@ -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 _logger; diff --git a/src/Components/WebAssembly/WebAssembly/src/Hosting/RegisteredComponentsInterop.cs b/src/Components/WebAssembly/WebAssembly/src/Hosting/RegisteredComponentsInterop.cs index adb34bdb70f3..a978405d5b91 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Hosting/RegisteredComponentsInterop.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Hosting/RegisteredComponentsInterop.cs @@ -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"; } } diff --git a/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs b/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs index 9ed229ed3e60..2cddc2058fd9 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Services { internal class WebAssemblyConsoleLogger : ILogger, 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(); diff --git a/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs b/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs index 7fcb5367557b..5d5202d15e7e 100644 --- a/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs +++ b/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs @@ -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 + "."; diff --git a/src/FileProviders/Embedded/src/Manifest/ManifestParser.cs b/src/FileProviders/Embedded/src/Manifest/ManifestParser.cs index aea224c53384..34c0c25f0002 100644 --- a/src/FileProviders/Embedded/src/Manifest/ManifestParser.cs +++ b/src/FileProviders/Embedded/src/Manifest/ManifestParser.cs @@ -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) { diff --git a/src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs b/src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs index d21c2f74bb08..162a4a93e491 100644 --- a/src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs +++ b/src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs @@ -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"; } } } diff --git a/src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs b/src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs index 5ddf68dd1c9d..7805292486fb 100644 --- a/src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs +++ b/src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs @@ -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 _healthCheckEndHealthy = LoggerMessage.Define( LogLevel.Debug, @@ -226,11 +226,6 @@ private static class Log EventIds.HealthCheckEnd, HealthCheckEndText); - private static readonly Action _healthCheckEndFailed = LoggerMessage.Define( - LogLevel.Error, - EventIds.HealthCheckEnd, - HealthCheckEndText); - private static readonly Action _healthCheckError = LoggerMessage.Define( LogLevel.Error, EventIds.HealthCheckError, diff --git a/src/Hosting/Hosting/src/Internal/WebHost.cs b/src/Hosting/Hosting/src/Internal/WebHost.cs index 45ea00c96090..bc97a47ae649 100644 --- a/src/Hosting/Hosting/src/Internal/WebHost.cs +++ b/src/Hosting/Hosting/src/Internal/WebHost.cs @@ -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; diff --git a/src/Http/Headers/src/HeaderUtilities.cs b/src/Http/Headers/src/HeaderUtilities.cs index 9d5fe5179674..4bb4c1561247 100644 --- a/src/Http/Headers/src/HeaderUtilities.cs +++ b/src/Http/Headers/src/HeaderUtilities.cs @@ -16,7 +16,7 @@ namespace Microsoft.Net.Http.Headers /// 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"; diff --git a/src/Http/Http.Abstractions/test/MapPathMiddlewareTests.cs b/src/Http/Http.Abstractions/test/MapPathMiddlewareTests.cs index 6e907814d957..94b9a63c0ad3 100644 --- a/src/Http/Http.Abstractions/test/MapPathMiddlewareTests.cs +++ b/src/Http/Http.Abstractions/test/MapPathMiddlewareTests.cs @@ -11,8 +11,6 @@ namespace Microsoft.AspNetCore.Builder.Extensions { public class MapPathMiddlewareTests { - private static readonly Action ActionNotImplemented = new Action(_ => { throw new NotImplementedException(); }); - private static Task Success(HttpContext context) { context.Response.StatusCode = 200; diff --git a/src/Http/Http.Extensions/src/RequestDelegateFactory.cs b/src/Http/Http.Extensions/src/RequestDelegateFactory.cs index 795278d32479..7762e2e1467f 100644 --- a/src/Http/Http.Extensions/src/RequestDelegateFactory.cs +++ b/src/Http/Http.Extensions/src/RequestDelegateFactory.cs @@ -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>(() => Task.CompletedTask)); diff --git a/src/Http/Http/src/Features/ResponseCookiesFeature.cs b/src/Http/Http/src/Features/ResponseCookiesFeature.cs index b51b99831ff6..e8dade0a5cfa 100644 --- a/src/Http/Http/src/Features/ResponseCookiesFeature.cs +++ b/src/Http/Http/src/Features/ResponseCookiesFeature.cs @@ -12,9 +12,6 @@ namespace Microsoft.AspNetCore.Http.Features /// public class ResponseCookiesFeature : IResponseCookiesFeature { - // Lambda hoisted to static readonly field to improve inlining https://github.com/dotnet/roslyn/issues/13624 - private readonly static Func _nullResponseFeature = f => null; - private readonly IFeatureCollection _features; private IResponseCookies? _cookiesCollection; diff --git a/src/Http/Http/src/QueryCollection.cs b/src/Http/Http/src/QueryCollection.cs index 3753fd870bc7..70dba259d34c 100644 --- a/src/Http/Http/src/QueryCollection.cs +++ b/src/Http/Http/src/QueryCollection.cs @@ -18,7 +18,6 @@ public class QueryCollection : IQueryCollection /// public static readonly QueryCollection Empty = new QueryCollection(); private static readonly string[] EmptyKeys = Array.Empty(); - private static readonly StringValues[] EmptyValues = Array.Empty(); private static readonly Enumerator EmptyEnumerator = new Enumerator(); // Pre-box private static readonly IEnumerator> EmptyIEnumeratorType = EmptyEnumerator; diff --git a/src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs b/src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs index 8624af97a7ab..4b42405cc87a 100644 --- a/src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs +++ b/src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs @@ -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 diff --git a/src/Http/Routing/src/Matching/ILEmitTrieJumpTable.cs b/src/Http/Routing/src/Matching/ILEmitTrieJumpTable.cs index 18bdd2bc356e..d9fb170001b8 100644 --- a/src/Http/Routing/src/Matching/ILEmitTrieJumpTable.cs +++ b/src/Http/Routing/src/Matching/ILEmitTrieJumpTable.cs @@ -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; @@ -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) diff --git a/src/Http/Routing/src/Matching/JumpTableBuilder.cs b/src/Http/Routing/src/Matching/JumpTableBuilder.cs index 877c2a550bf3..889b373336ff 100644 --- a/src/Http/Routing/src/Matching/JumpTableBuilder.cs +++ b/src/Http/Routing/src/Matching/JumpTableBuilder.cs @@ -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) { diff --git a/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs b/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs index f82d860e8373..b9db0e40fa78 100644 --- a/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs +++ b/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs @@ -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) @@ -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) @@ -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 @@ -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; } diff --git a/src/Http/Routing/src/Patterns/RoutePatternParser.cs b/src/Http/Routing/src/Patterns/RoutePatternParser.cs index d59f6779cfe6..2a52f2daf461 100644 --- a/src/Http/Routing/src/Patterns/RoutePatternParser.cs +++ b/src/Http/Routing/src/Patterns/RoutePatternParser.cs @@ -15,7 +15,6 @@ internal static class RoutePatternParser private const char Separator = '/'; private const char OpenBrace = '{'; private const char CloseBrace = '}'; - private const char EqualsSign = '='; private const char QuestionMark = '?'; private const char Asterisk = '*'; private const string PeriodString = "."; diff --git a/src/Http/Routing/src/Template/TemplateMatcher.cs b/src/Http/Routing/src/Template/TemplateMatcher.cs index e955ca91a8bf..1cffb0d42c47 100644 --- a/src/Http/Routing/src/Template/TemplateMatcher.cs +++ b/src/Http/Routing/src/Template/TemplateMatcher.cs @@ -14,14 +14,10 @@ namespace Microsoft.AspNetCore.Routing.Template /// public class TemplateMatcher { - 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 }; private RoutePatternMatcher _routePatternMatcher; /// diff --git a/src/Http/Routing/test/UnitTests/Matching/HttpMethodMatcherPolicyIntegrationTestBase.cs b/src/Http/Routing/test/UnitTests/Matching/HttpMethodMatcherPolicyIntegrationTestBase.cs index fbb8cecc69ca..f7e94315eff0 100644 --- a/src/Http/Routing/test/UnitTests/Matching/HttpMethodMatcherPolicyIntegrationTestBase.cs +++ b/src/Http/Routing/test/UnitTests/Matching/HttpMethodMatcherPolicyIntegrationTestBase.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Routing.Patterns; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Net.Http.Headers; using Xunit; using static Microsoft.AspNetCore.Routing.Matching.HttpMethodMatcherPolicy; @@ -352,8 +353,8 @@ internal static HttpContext CreateContext( if (corsPreflight) { - httpContext.Request.Headers[OriginHeader] = "example.com"; - httpContext.Request.Headers[AccessControlRequestMethod] = httpMethod; + httpContext.Request.Headers[HeaderNames.Origin] = "example.com"; + httpContext.Request.Headers[HeaderNames.AccessControlRequestMethod] = httpMethod; } return httpContext; diff --git a/src/Http/Routing/test/UnitTests/Template/TemplateBinderTests.cs b/src/Http/Routing/test/UnitTests/Template/TemplateBinderTests.cs index 1aa2c5ad8b5f..3d6cf5848e42 100644 --- a/src/Http/Routing/test/UnitTests/Template/TemplateBinderTests.cs +++ b/src/Http/Routing/test/UnitTests/Template/TemplateBinderTests.cs @@ -17,8 +17,6 @@ namespace Microsoft.AspNetCore.Routing.Template.Tests { public class TemplateBinderTests { - private readonly IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver(); - public static TheoryData EmptyAndNullDefaultValues => new TheoryData { @@ -1444,14 +1442,6 @@ public void BindValues_HasUnmatchingAmbientValues_Discard() Assert.Equal(expected, boundTemplate); } - private static IInlineConstraintResolver GetInlineConstraintResolver() - { - var services = new ServiceCollection().AddOptions(); - var serviceProvider = services.BuildServiceProvider(); - var accessor = serviceProvider.GetRequiredService>(); - return new DefaultInlineConstraintResolver(accessor, serviceProvider); - } - private class PathAndQuery { public PathAndQuery(string uri) diff --git a/src/Http/Routing/test/UnitTests/Template/TemplateMatcherTests.cs b/src/Http/Routing/test/UnitTests/Template/TemplateMatcherTests.cs index fc78ef4cdc5b..6dd6d564cf2f 100644 --- a/src/Http/Routing/test/UnitTests/Template/TemplateMatcherTests.cs +++ b/src/Http/Routing/test/UnitTests/Template/TemplateMatcherTests.cs @@ -11,8 +11,6 @@ namespace Microsoft.AspNetCore.Routing.Template.Tests { public class TemplateMatcherTests { - private static IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver(); - [Fact] public void TryMatch_Success() { @@ -1130,13 +1128,5 @@ private static void RunTest( } } } - - private static IInlineConstraintResolver GetInlineConstraintResolver() - { - var services = new ServiceCollection().AddOptions(); - var serviceProvider = services.BuildServiceProvider(); - var accessor = serviceProvider.GetRequiredService>(); - return new DefaultInlineConstraintResolver(accessor, serviceProvider); - } } } diff --git a/src/Http/Routing/test/UnitTests/Tree/TreeRouterTest.cs b/src/Http/Routing/test/UnitTests/Tree/TreeRouterTest.cs index 517abedaad93..af7b091f5abe 100644 --- a/src/Http/Routing/test/UnitTests/Tree/TreeRouterTest.cs +++ b/src/Http/Routing/test/UnitTests/Tree/TreeRouterTest.cs @@ -22,9 +22,6 @@ public class TreeRouterTest { private static readonly RequestDelegate NullHandler = (c) => Task.CompletedTask; - private static ObjectPool Pool = new DefaultObjectPoolProvider().Create( - new UriBuilderContextPooledObjectPolicy()); - [Theory] [InlineData("template/5", "template/{parameter:int}")] [InlineData("template/5", "template/{parameter}")] diff --git a/src/Http/Routing/test/testassets/RoutingSandbox/UseEndpointRoutingStartup.cs b/src/Http/Routing/test/testassets/RoutingSandbox/UseEndpointRoutingStartup.cs index 116f743ad41e..f196871bb0fd 100644 --- a/src/Http/Routing/test/testassets/RoutingSandbox/UseEndpointRoutingStartup.cs +++ b/src/Http/Routing/test/testassets/RoutingSandbox/UseEndpointRoutingStartup.cs @@ -18,7 +18,6 @@ namespace RoutingSandbox { public class UseEndpointRoutingStartup { - private static readonly byte[] _homePayload = Encoding.UTF8.GetBytes("Endpoint Routing sample endpoints:" + Environment.NewLine + "/plaintext"); private static readonly byte[] _plainTextPayload = Encoding.UTF8.GetBytes("Plain text!"); public void ConfigureServices(IServiceCollection services) diff --git a/src/Http/Routing/test/testassets/RoutingWebSite/UseEndpointRoutingStartup.cs b/src/Http/Routing/test/testassets/RoutingWebSite/UseEndpointRoutingStartup.cs index 31aeba31db43..e17b2d64beed 100644 --- a/src/Http/Routing/test/testassets/RoutingWebSite/UseEndpointRoutingStartup.cs +++ b/src/Http/Routing/test/testassets/RoutingWebSite/UseEndpointRoutingStartup.cs @@ -20,7 +20,6 @@ namespace RoutingWebSite { public class UseEndpointRoutingStartup { - private static readonly byte[] _homePayload = Encoding.UTF8.GetBytes("Endpoint Routing sample endpoints:" + Environment.NewLine + "/plaintext"); private static readonly byte[] _plainTextPayload = Encoding.UTF8.GetBytes("Plain text!"); public void ConfigureServices(IServiceCollection services) diff --git a/src/Http/WebUtilities/src/HttpRequestStreamReader.cs b/src/Http/WebUtilities/src/HttpRequestStreamReader.cs index 3136b5768166..7dbdd644b38e 100644 --- a/src/Http/WebUtilities/src/HttpRequestStreamReader.cs +++ b/src/Http/WebUtilities/src/HttpRequestStreamReader.cs @@ -18,8 +18,6 @@ namespace Microsoft.AspNetCore.WebUtilities public class HttpRequestStreamReader : TextReader { private const int DefaultBufferSize = 1024; - private const int MinBufferSize = 128; - private const int MaxSharedBuilderCapacity = 360; // also the max capacity used in StringBuilderCache private Stream _stream; private readonly Encoding _encoding; diff --git a/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs b/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs index 55cc5d3933d3..4a0bb20f14ef 100644 --- a/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs +++ b/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs @@ -19,7 +19,6 @@ namespace Microsoft.AspNetCore.WebUtilities /// public class HttpResponseStreamWriter : TextWriter { - private const int MinBufferSize = 128; internal const int DefaultBufferSize = 16 * 1024; private Stream _stream; diff --git a/src/HttpClientFactory/Polly/src/HttpRequestMessageExtensions.cs b/src/HttpClientFactory/Polly/src/HttpRequestMessageExtensions.cs index 12b8e58dd16b..1a2d56c1311a 100644 --- a/src/HttpClientFactory/Polly/src/HttpRequestMessageExtensions.cs +++ b/src/HttpClientFactory/Polly/src/HttpRequestMessageExtensions.cs @@ -13,8 +13,10 @@ namespace Polly /// public static class HttpRequestMessageExtensions { +#pragma warning disable CA1802 // Use literals where appropriate. Using a static field for reference equality internal static readonly string PolicyExecutionContextKey = "PolicyExecutionContext"; - +#pragma warning restore CA1802 + /// /// Gets the associated with the provided . /// diff --git a/src/Identity/Core/src/IdentityConstants.cs b/src/Identity/Core/src/IdentityConstants.cs index e01715dfbcfa..e5d6fcafe1fb 100644 --- a/src/Identity/Core/src/IdentityConstants.cs +++ b/src/Identity/Core/src/IdentityConstants.cs @@ -8,7 +8,8 @@ namespace Microsoft.AspNetCore.Identity /// public class IdentityConstants { - private static readonly string CookiePrefix = "Identity"; + private const string CookiePrefix = "Identity"; + /// /// The scheme used to identify application authentication cookies. /// diff --git a/src/Identity/EntityFrameworkCore/test/EF.Test/UserStoreEncryptPersonalDataTest.cs b/src/Identity/EntityFrameworkCore/test/EF.Test/UserStoreEncryptPersonalDataTest.cs index 6f9efbe48f60..b21b50f43aa0 100644 --- a/src/Identity/EntityFrameworkCore/test/EF.Test/UserStoreEncryptPersonalDataTest.cs +++ b/src/Identity/EntityFrameworkCore/test/EF.Test/UserStoreEncryptPersonalDataTest.cs @@ -15,8 +15,6 @@ namespace Microsoft.AspNetCore.Identity.EntityFrameworkCore.Test { public class ProtectedUserStoreTest : SqlStoreTestBase { - private DefaultKeyRing _keyRing = new DefaultKeyRing(); - public ProtectedUserStoreTest(ScratchDatabaseFixture fixture) : base(fixture) { } diff --git a/src/Identity/Extensions.Core/src/Base32.cs b/src/Identity/Extensions.Core/src/Base32.cs index 31ee4e95dfe9..b987f6d74f70 100644 --- a/src/Identity/Extensions.Core/src/Base32.cs +++ b/src/Identity/Extensions.Core/src/Base32.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Identity // See http://tools.ietf.org/html/rfc3548#section-5 internal static class Base32 { - private static readonly string _base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + private const string _base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; public static string ToBase32(byte[] input) { diff --git a/src/Identity/Extensions.Core/src/PersonalDataAttribute.cs b/src/Identity/Extensions.Core/src/PersonalDataAttribute.cs index 5ee23537fa48..09553351b8e0 100644 --- a/src/Identity/Extensions.Core/src/PersonalDataAttribute.cs +++ b/src/Identity/Extensions.Core/src/PersonalDataAttribute.cs @@ -8,6 +8,7 @@ namespace Microsoft.AspNetCore.Identity /// /// Used to indicate that a something is considered personal data. /// + [AttributeUsage(AttributeTargets.All)] public class PersonalDataAttribute : Attribute { } } \ No newline at end of file diff --git a/src/Identity/Extensions.Core/src/UserManager.cs b/src/Identity/Extensions.Core/src/UserManager.cs index b794811a9766..778a35900d07 100644 --- a/src/Identity/Extensions.Core/src/UserManager.cs +++ b/src/Identity/Extensions.Core/src/UserManager.cs @@ -41,7 +41,6 @@ public class UserManager : IDisposable where TUser : class private readonly Dictionary> _tokenProviders = new Dictionary>(); - private TimeSpan _defaultLockout = TimeSpan.Zero; private bool _disposed; #if NETSTANDARD2_0 || NET461 private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create(); diff --git a/src/Middleware/Localization/src/CookieRequestCultureProvider.cs b/src/Middleware/Localization/src/CookieRequestCultureProvider.cs index 1ece3dbb42c8..b9c19f18d200 100644 --- a/src/Middleware/Localization/src/CookieRequestCultureProvider.cs +++ b/src/Middleware/Localization/src/CookieRequestCultureProvider.cs @@ -1,5 +1,5 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; @@ -12,9 +12,9 @@ namespace Microsoft.AspNetCore.Localization /// public class CookieRequestCultureProvider : RequestCultureProvider { - private static readonly char _cookieSeparator = '|'; - private static readonly string _culturePrefix = "c="; - private static readonly string _uiCulturePrefix = "uic="; + private const char _cookieSeparator = '|'; + private const string _culturePrefix = "c="; + private const string _uiCulturePrefix = "uic="; /// /// Represent the default cookie name used to track the user's preferred culture information, which is ".AspNetCore.Culture". diff --git a/src/Middleware/Localization/src/RequestLocalizationMiddleware.cs b/src/Middleware/Localization/src/RequestLocalizationMiddleware.cs index 0afc657b9fca..e1e66f32459a 100644 --- a/src/Middleware/Localization/src/RequestLocalizationMiddleware.cs +++ b/src/Middleware/Localization/src/RequestLocalizationMiddleware.cs @@ -24,7 +24,7 @@ namespace Microsoft.AspNetCore.Localization /// public class RequestLocalizationMiddleware { - private static readonly int MaxCultureFallbackDepth = 5; + private const int MaxCultureFallbackDepth = 5; private readonly RequestDelegate _next; private readonly RequestLocalizationOptions _options; diff --git a/src/Middleware/ResponseCaching/src/ResponseCachingKeyProvider.cs b/src/Middleware/ResponseCaching/src/ResponseCachingKeyProvider.cs index 3040d43ca57f..d227c5a560e7 100644 --- a/src/Middleware/ResponseCaching/src/ResponseCachingKeyProvider.cs +++ b/src/Middleware/ResponseCaching/src/ResponseCachingKeyProvider.cs @@ -14,9 +14,9 @@ namespace Microsoft.AspNetCore.ResponseCaching internal class ResponseCachingKeyProvider : IResponseCachingKeyProvider { // Use the record separator for delimiting components of the cache key to avoid possible collisions - private static readonly char KeyDelimiter = '\x1e'; + private const char KeyDelimiter = '\x1e'; // Use the unit separator for delimiting subcomponents of the cache key to avoid possible collisions - private static readonly char KeySubDelimiter = '\x1f'; + private const char KeySubDelimiter = '\x1f'; private readonly ObjectPool _builderPool; private readonly ResponseCachingOptions _options; diff --git a/src/Middleware/WebSockets/src/Constants.cs b/src/Middleware/WebSockets/src/Constants.cs index 3757d3a344ab..ca07a77b386e 100644 --- a/src/Middleware/WebSockets/src/Constants.cs +++ b/src/Middleware/WebSockets/src/Constants.cs @@ -7,8 +7,8 @@ internal static class Constants { public static class Headers { - public readonly static string UpgradeWebSocket = "websocket"; - public readonly static string SupportedVersion = "13"; + public const string UpgradeWebSocket = "websocket"; + public const string SupportedVersion = "13"; } } } diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpRequestStreamReaderFactory.cs b/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpRequestStreamReaderFactory.cs index d9d3a4e0f740..a24e0b23a769 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpRequestStreamReaderFactory.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpRequestStreamReaderFactory.cs @@ -19,7 +19,7 @@ internal class MemoryPoolHttpRequestStreamReaderFactory : IHttpRequestStreamRead /// /// The default size of created char buffers. /// - public static readonly int DefaultBufferSize = 1024; // 1KB - results in a 4KB byte array for UTF8. + public const int DefaultBufferSize = 1024; // 1KB - results in a 4KB byte array for UTF8. private readonly ArrayPool _bytePool; private readonly ArrayPool _charPool; diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpResponseStreamWriterFactory.cs b/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpResponseStreamWriterFactory.cs index 71ddf556e476..f68e685a2402 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpResponseStreamWriterFactory.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpResponseStreamWriterFactory.cs @@ -27,7 +27,7 @@ internal class MemoryPoolHttpResponseStreamWriterFactory : IHttpResponseStreamWr /// maintains s /// for these arrays. /// - public static readonly int DefaultBufferSize = 16 * 1024; + public const int DefaultBufferSize = 16 * 1024; private readonly ArrayPool _bytePool; private readonly ArrayPool _charPool; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinderProvider.cs index d88a9efa8370..ac34a820b82e 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinderProvider.cs @@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders /// public class DateTimeModelBinderProvider : IModelBinderProvider { - internal static readonly DateTimeStyles SupportedStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces; + internal const DateTimeStyles SupportedStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces; /// public IModelBinder? GetBinder(ModelBinderProviderContext context) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatingPointTypeModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatingPointTypeModelBinderProvider.cs index a600e53e0653..9640c3d496aa 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatingPointTypeModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatingPointTypeModelBinderProvider.cs @@ -18,7 +18,7 @@ public class FloatingPointTypeModelBinderProvider : IModelBinderProvider { // SimpleTypeModelBinder uses DecimalConverter and similar. Those TypeConverters default to NumberStyles.Float. // Internal for testing. - internal static readonly NumberStyles SupportedStyles = NumberStyles.Float | NumberStyles.AllowThousands; + internal const NumberStyles SupportedStyles = NumberStyles.Float | NumberStyles.AllowThousands; /// public IModelBinder? GetBinder(ModelBinderProviderContext context) diff --git a/src/Mvc/Mvc.Core/src/Routing/ActionConstraintMatcherPolicy.cs b/src/Mvc/Mvc.Core/src/Routing/ActionConstraintMatcherPolicy.cs index 54603729433c..b2e5cc43247e 100644 --- a/src/Mvc/Mvc.Core/src/Routing/ActionConstraintMatcherPolicy.cs +++ b/src/Mvc/Mvc.Core/src/Routing/ActionConstraintMatcherPolicy.cs @@ -18,8 +18,6 @@ namespace Microsoft.AspNetCore.Mvc.Routing // used with Matcher. internal class ActionConstraintMatcherPolicy : MatcherPolicy, IEndpointSelectorPolicy { - private static readonly IReadOnlyList EmptyEndpoints = Array.Empty(); - // We need to be able to run IActionConstraints on Endpoints that aren't associated // with an action. This is a sentinel value we use when the endpoint isn't from MVC. internal static readonly ActionDescriptor NonAction = new ActionDescriptor(); diff --git a/src/Mvc/Mvc.Formatters.Xml/src/FormattingUtilities.cs b/src/Mvc/Mvc.Formatters.Xml/src/FormattingUtilities.cs index 70a9c9445371..6899cbe968f7 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/FormattingUtilities.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/FormattingUtilities.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml /// internal static class FormattingUtilities { - public static readonly int DefaultMaxDepth = 32; + public const int DefaultMaxDepth = 32; public static readonly XsdDataContractExporter XsdDataContractExporter = new XsdDataContractExporter(); /// diff --git a/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapper.cs b/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapper.cs index f8f4a1108e1c..c08bcfc8e4ad 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapper.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapper.cs @@ -16,7 +16,7 @@ public sealed class SerializableErrorWrapper : IXmlSerializable, IUnwrappable { // Element name used when ModelStateEntry's Key is empty. Dash in element name should avoid collisions with // other ModelState entries because the character is not legal in an expression name. - internal static readonly string EmptyKey = "MVC-Empty"; + internal const string EmptyKey = "MVC-Empty"; /// /// Initializes a new diff --git a/src/Mvc/Mvc.Formatters.Xml/src/ValidationProblemDetailsWrapper.cs b/src/Mvc/Mvc.Formatters.Xml/src/ValidationProblemDetailsWrapper.cs index a454fb5d0a1e..cccfd4692965 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/ValidationProblemDetailsWrapper.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/ValidationProblemDetailsWrapper.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml [XmlRoot("problem", Namespace = "urn:ietf:rfc:7807")] public class ValidationProblemDetailsWrapper : ProblemDetailsWrapper, IUnwrappable { - private static readonly string ErrorKey = "MVC-Errors"; + private const string ErrorKey = "MVC-Errors"; /// /// Initializes a new instance of . diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/CompiledPageRouteModelProvider.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/CompiledPageRouteModelProvider.cs index 855fcb6d1a5e..16c676bede1f 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/CompiledPageRouteModelProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/CompiledPageRouteModelProvider.cs @@ -16,8 +16,8 @@ namespace Microsoft.AspNetCore.Mvc.ApplicationModels { internal class CompiledPageRouteModelProvider : IPageRouteModelProvider { - private static readonly string RazorPageDocumentKind = "mvc.1.0.razor-page"; - private static readonly string RouteTemplateKey = "RouteTemplate"; + private const string RazorPageDocumentKind = "mvc.1.0.razor-page"; + private const string RouteTemplateKey = "RouteTemplate"; private readonly ApplicationPartManager _applicationManager; private readonly RazorPagesOptions _pagesOptions; private readonly PageRouteModelFactory _routeModelFactory; diff --git a/src/Mvc/Mvc.ViewFeatures/src/Buffers/MemoryPoolViewBufferScope.cs b/src/Mvc/Mvc.ViewFeatures/src/Buffers/MemoryPoolViewBufferScope.cs index be686e5fe08c..2ad3dda3585f 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Buffers/MemoryPoolViewBufferScope.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Buffers/MemoryPoolViewBufferScope.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers /// internal class MemoryPoolViewBufferScope : IViewBufferScope, IDisposable { - public static readonly int MinimumSize = 16; + public const int MinimumSize = 16; private readonly ArrayPool _viewBufferPool; private readonly ArrayPool _charPool; private List _available; diff --git a/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs b/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs index de5964e46b7c..ea6aa480f20b 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs @@ -18,10 +18,10 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers [DebuggerDisplay("{DebuggerToString()}")] internal class ViewBuffer : IHtmlContentBuilder { - public static readonly int PartialViewPageSize = 32; - public static readonly int TagHelperPageSize = 32; - public static readonly int ViewComponentPageSize = 32; - public static readonly int ViewPageSize = 256; + public const int PartialViewPageSize = 32; + public const int TagHelperPageSize = 32; + public const int ViewComponentPageSize = 32; + public const int ViewPageSize = 256; private readonly IViewBufferScope _bufferScope; private readonly string _name; diff --git a/src/Mvc/Mvc.ViewFeatures/src/CookieTempDataProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/CookieTempDataProvider.cs index ea4c9372f23e..e57424537ad5 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/CookieTempDataProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/CookieTempDataProvider.cs @@ -22,7 +22,7 @@ public class CookieTempDataProvider : ITempDataProvider /// The name of the cookie. /// public static readonly string CookieName = ".AspNetCore.Mvc.CookieTempDataProvider"; - private static readonly string Purpose = "Microsoft.AspNetCore.Mvc.CookieTempDataProviderToken.v1"; + private const string Purpose = "Microsoft.AspNetCore.Mvc.CookieTempDataProviderToken.v1"; private readonly IDataProtector _dataProtector; private readonly ILogger _logger; @@ -68,7 +68,7 @@ public IDictionary LoadTempData(HttpContext context) // // Since TempData is a best-effort system, we don't want to throw and get a 500 if the cookie is // bad, we will just clear it and ignore the exception. The common case that we've identified for - // this is misconfigured data protection settings, which can cause the key used to create the + // this is misconfigured data protection settings, which can cause the key used to create the // cookie to no longer be available. try { diff --git a/src/Mvc/Mvc.ViewFeatures/src/MvcViewFeaturesLoggerExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/MvcViewFeaturesLoggerExtensions.cs index a8529f818999..3787762f525b 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/MvcViewFeaturesLoggerExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/MvcViewFeaturesLoggerExtensions.cs @@ -14,8 +14,6 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures { internal static class MvcViewFeaturesLoggerExtensions { - private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency; - private static readonly Action _viewComponentExecuting; private static readonly Action _viewComponentExecuted; diff --git a/src/Mvc/test/Mvc.FunctionalTests/ComponentRenderingFunctionalTests.cs b/src/Mvc/test/Mvc.FunctionalTests/ComponentRenderingFunctionalTests.cs index 5cd5afd214fd..5b310a39de81 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/ComponentRenderingFunctionalTests.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/ComponentRenderingFunctionalTests.cs @@ -17,10 +17,6 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests { public class ComponentRenderingFunctionalTests : IClassFixture> { - private static readonly Regex ContentWrapperRegex = new Regex( - "(?.*)", - RegexOptions.Compiled | RegexOptions.Singleline, TimeSpan.FromSeconds(1)); // Treat the entire input string as a single line - public ComponentRenderingFunctionalTests(MvcTestFixture fixture) { Factory = fixture; diff --git a/src/Mvc/test/Mvc.FunctionalTests/RequestSizeLimitTest.cs b/src/Mvc/test/Mvc.FunctionalTests/RequestSizeLimitTest.cs index 8e5ce315d3b4..66b794d44c7d 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/RequestSizeLimitTest.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/RequestSizeLimitTest.cs @@ -17,12 +17,6 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests { public class RequestSizeLimitTest : IClassFixture> { - // Some tests require comparing the actual response body against an expected response baseline - // so they require a reference to the assembly on which the resources are located, in order to - // make the tests less verbose, we get a reference to the assembly with the resources and we - // use it on all the rest of the tests. - private static readonly Assembly _resourcesAssembly = typeof(BasicTests).GetTypeInfo().Assembly; - public RequestSizeLimitTest(MvcTestFixture fixture) { var factory = fixture.Factories.FirstOrDefault() ?? fixture.WithWebHostBuilder(ConfigureWebHostBuilder); diff --git a/src/Mvc/test/Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs b/src/Mvc/test/Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs index 2567b0a8d0d0..e4ae8a9ffafe 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs @@ -18,16 +18,6 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests { public class XmlDataContractSerializerInputFormatterTest : IClassFixture> { - private readonly string errorMessageFormat = string.Format( - CultureInfo.CurrentCulture, - "{{1}}:{0} does not recognize '{1}', so instead use '{2}' with '{3}' set to '{4}' for value " + - "type property '{{0}}' on type '{{1}}'.", - typeof(DataContractSerializer).FullName, - typeof(RequiredAttribute).FullName, - typeof(DataMemberAttribute).FullName, - nameof(DataMemberAttribute.IsRequired), - bool.TrueString); - public XmlDataContractSerializerInputFormatterTest(MvcTestFixture fixture) { Client = fixture.CreateDefaultClient(); diff --git a/src/Mvc/test/WebSites/BasicWebSite/RequestScopedActionConstraint.cs b/src/Mvc/test/WebSites/BasicWebSite/RequestScopedActionConstraint.cs index ed5a267e3b7e..e5ee7b03f0cc 100644 --- a/src/Mvc/test/WebSites/BasicWebSite/RequestScopedActionConstraint.cs +++ b/src/Mvc/test/WebSites/BasicWebSite/RequestScopedActionConstraint.cs @@ -12,10 +12,6 @@ namespace BasicWebSite public class RequestScopedConstraintAttribute : Attribute, IActionConstraintFactory { private readonly string _requestId; - private readonly Func CreateFactory = - (t, s) => ActivatorUtilities.CreateFactory(t, new[] { s.GetType() }); - private readonly ConcurrentDictionary _constraintCache = - new ConcurrentDictionary(); public bool IsReusable => false; diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/LegacySectionTargetExtension.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/LegacySectionTargetExtension.cs index 52698cdfe86f..629541143a30 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/LegacySectionTargetExtension.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/LegacySectionTargetExtension.cs @@ -7,9 +7,9 @@ namespace Microsoft.AspNetCore.Razor.Language.Extensions { internal class LegacySectionTargetExtension : ISectionTargetExtension { - private static readonly string DefaultWriterName = "__razor_section_writer"; + private const string DefaultWriterName = "__razor_section_writer"; - public static readonly string DefaultSectionMethodName = "DefineSection"; + public const string DefaultSectionMethodName = "DefineSection"; public string SectionMethodName { get; set; } = DefaultSectionMethodName; diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTypeVisitor.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTypeVisitor.cs index 452df2c9ac9e..d9ccda3c776e 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTypeVisitor.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTypeVisitor.cs @@ -10,8 +10,6 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X { internal class ViewComponentTypeVisitor : SymbolVisitor { - private static readonly Version SupportedVCTHMvcVersion = new Version(1, 1); - private readonly INamedTypeSymbol _viewComponentAttribute; private readonly INamedTypeSymbol _nonViewComponentAttribute; private readonly List _results; diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDesignTimeNodeWriter.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDesignTimeNodeWriter.cs index 874e64061184..b6c875544be7 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDesignTimeNodeWriter.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDesignTimeNodeWriter.cs @@ -15,7 +15,7 @@ internal class ComponentDesignTimeNodeWriter : ComponentNodeWriter { private readonly ScopeStack _scopeStack = new ScopeStack(); - private static readonly string DesignTimeVariable = "__o"; + private const string DesignTimeVariable = "__o"; public override void WriteMarkupBlock(CodeRenderingContext context, MarkupBlockIntermediateNode node) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDocumentClassifierPass.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDocumentClassifierPass.cs index 6f7ef8ab3694..19b5145a62bd 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDocumentClassifierPass.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDocumentClassifierPass.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Components { internal class ComponentDocumentClassifierPass : DocumentClassifierPassBase { - public static readonly string ComponentDocumentKind = "component.1.0"; + public const string ComponentDocumentKind = "component.1.0"; /// /// The fallback value of the root namespace. Only used if the fallback root namespace @@ -22,7 +22,7 @@ internal class ComponentDocumentClassifierPass : DocumentClassifierPassBase /// /// Gets or sets whether to mangle class names. - /// + /// /// Set to true in the IDE so we can generated mangled class names. This is needed /// to avoid conflicts between generated design-time code and the code in the editor. /// diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDuplicateAttributeDiagnosticPass.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDuplicateAttributeDiagnosticPass.cs index 83936bf28d59..36a0e0da916c 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDuplicateAttributeDiagnosticPass.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDuplicateAttributeDiagnosticPass.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Components { internal sealed class ComponentMarkupDiagnosticPass : ComponentIntermediateNodePassBase, IRazorOptimizationPass { - public static readonly int DefaultOrder = 10000; + public const int DefaultOrder = 10000; public override int Order => DefaultOrder; @@ -49,7 +49,7 @@ attribute.Annotations[ComponentMetadata.Common.OriginalAttributeName] as string } else { - // This is a conflict in the code the user wrote. + // This is a conflict in the code the user wrote. other.node.Diagnostics.Add(ComponentDiagnosticFactory.Create_DuplicateMarkupAttribute( other.name, other.node.Source ?? node.Source)); @@ -92,7 +92,7 @@ attribute.Annotations[ComponentMetadata.Common.OriginalAttributeName] as string } else { - // This is a conflict in the code the user wrote. + // This is a conflict in the code the user wrote. other.node.Diagnostics.Add(ComponentDiagnosticFactory.Create_DuplicateComponentParameter( other.name, other.node.Source ?? node.Source)); diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentImportProjectFeature.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentImportProjectFeature.cs index 2e689044de55..5f19a23bca78 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentImportProjectFeature.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentImportProjectFeature.cs @@ -11,10 +11,8 @@ namespace Microsoft.AspNetCore.Razor.Language.Components { internal class ComponentImportProjectFeature : IImportProjectFeature { - private static readonly char[] PathSeparators = new char[]{ '/', '\\' }; - // Using explicit newlines here to avoid fooling our baseline tests - private readonly static string DefaultUsingImportContent = + private const string DefaultUsingImportContent = "\r\n" + "@using System\r\n" + "@using System.Collections.Generic\r\n" + diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentMetadata.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentMetadata.cs index 4f25d2d86e56..c6b7d3a9971b 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentMetadata.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentMetadata.cs @@ -8,14 +8,14 @@ namespace Microsoft.AspNetCore.Razor.Language.Components // Metadata used for Components interactions with the tag helper system internal static class ComponentMetadata { - private static readonly string MangledClassNamePrefix = "__generated__"; + private const string MangledClassNamePrefix = "__generated__"; // There's a bug in the 15.7 preview 1 Razor that prevents 'Kind' from being serialized // this affects both tooling and build. For now our workaround is to ignore 'Kind' and // use our own metadata entry to denote non-Component tag helpers. - public static readonly string SpecialKindKey = "Components.IsSpecialKind"; + public const string SpecialKindKey = "Components.IsSpecialKind"; - public static readonly string ImportsFileName = "_Imports.razor"; + public const string ImportsFileName = "_Imports.razor"; public static string MangleClassName(string className) { @@ -39,108 +39,108 @@ public static bool IsMangledClass(string className) public static class Common { - public static readonly string OriginalAttributeName = "Common.OriginalAttributeName"; + public const string OriginalAttributeName = "Common.OriginalAttributeName"; - public static readonly string DirectiveAttribute = "Common.DirectiveAttribute"; + public const string DirectiveAttribute = "Common.DirectiveAttribute"; - public static readonly string AddAttributeMethodName = "Common.AddAttributeMethodName"; + public const string AddAttributeMethodName = "Common.AddAttributeMethodName"; } public static class Bind { - public static readonly string RuntimeName = "Components.None"; + public const string RuntimeName = "Components.None"; - public readonly static string TagHelperKind = "Components.Bind"; + public const string TagHelperKind = "Components.Bind"; - public readonly static string FallbackKey = "Components.Bind.Fallback"; + public const string FallbackKey = "Components.Bind.Fallback"; - public readonly static string TypeAttribute = "Components.Bind.TypeAttribute"; + public const string TypeAttribute = "Components.Bind.TypeAttribute"; - public readonly static string ValueAttribute = "Components.Bind.ValueAttribute"; + public const string ValueAttribute = "Components.Bind.ValueAttribute"; - public readonly static string ChangeAttribute = "Components.Bind.ChangeAttribute"; + public const string ChangeAttribute = "Components.Bind.ChangeAttribute"; - public readonly static string ExpressionAttribute = "Components.Bind.ExpressionAttribute"; + public const string ExpressionAttribute = "Components.Bind.ExpressionAttribute"; - public readonly static string IsInvariantCulture = "Components.Bind.IsInvariantCulture"; + public const string IsInvariantCulture = "Components.Bind.IsInvariantCulture"; - public readonly static string Format = "Components.Bind.Format"; + public const string Format = "Components.Bind.Format"; } public static class ChildContent { - public static readonly string RuntimeName = "Components.None"; + public const string RuntimeName = "Components.None"; - public static readonly string TagHelperKind = "Components.ChildContent"; + public const string TagHelperKind = "Components.ChildContent"; - public static readonly string ParameterNameBoundAttributeKind = "Components.ChildContentParameterName"; + public const string ParameterNameBoundAttributeKind = "Components.ChildContentParameterName"; /// /// The name of the synthesized attribute used to set a child content parameter. /// - public static readonly string ParameterAttributeName = "Context"; + public const string ParameterAttributeName = "Context"; /// /// The default name of the child content parameter (unless set by a Context attribute). /// - public static readonly string DefaultParameterName = "context"; + public const string DefaultParameterName = "context"; } public static class Component { - public static readonly string ChildContentKey = "Components.ChildContent"; + public const string ChildContentKey = "Components.ChildContent"; - public static readonly string ChildContentParameterNameKey = "Components.ChildContentParameterName"; + public const string ChildContentParameterNameKey = "Components.ChildContentParameterName"; - public static readonly string DelegateSignatureKey = "Components.DelegateSignature"; + public const string DelegateSignatureKey = "Components.DelegateSignature"; - public static readonly string EventCallbackKey = "Components.EventCallback"; + public const string EventCallbackKey = "Components.EventCallback"; - public static readonly string WeaklyTypedKey = "Components.IsWeaklyTyped"; + public const string WeaklyTypedKey = "Components.IsWeaklyTyped"; - public static readonly string RuntimeName = "Components.IComponent"; + public const string RuntimeName = "Components.IComponent"; - public readonly static string TagHelperKind = "Components.Component"; + public const string TagHelperKind = "Components.Component"; - public readonly static string GenericTypedKey = "Components.GenericTyped"; + public const string GenericTypedKey = "Components.GenericTyped"; - public readonly static string TypeParameterKey = "Components.TypeParameter"; + public const string TypeParameterKey = "Components.TypeParameter"; - public readonly static string TypeParameterIsCascadingKey = "Components.TypeParameterIsCascading"; + public const string TypeParameterIsCascadingKey = "Components.TypeParameterIsCascading"; - public readonly static string NameMatchKey = "Components.NameMatch"; + public const string NameMatchKey = "Components.NameMatch"; - public readonly static string FullyQualifiedNameMatch = "Components.FullyQualifiedNameMatch"; + public const string FullyQualifiedNameMatch = "Components.FullyQualifiedNameMatch"; } public static class EventHandler { - public static readonly string EventArgsType = "Components.EventHandler.EventArgs"; + public const string EventArgsType = "Components.EventHandler.EventArgs"; - public static readonly string RuntimeName = "Components.None"; + public const string RuntimeName = "Components.None"; - public readonly static string TagHelperKind = "Components.EventHandler"; + public const string TagHelperKind = "Components.EventHandler"; } public static class Key { - public readonly static string TagHelperKind = "Components.Key"; + public const string TagHelperKind = "Components.Key"; - public static readonly string RuntimeName = "Components.None"; + public const string RuntimeName = "Components.None"; } public static class Splat { - public readonly static string TagHelperKind = "Components.Splat"; + public const string TagHelperKind = "Components.Splat"; - public static readonly string RuntimeName = "Components.None"; + public const string RuntimeName = "Components.None"; } public static class Ref { - public readonly static string TagHelperKind = "Components.Ref"; + public const string TagHelperKind = "Components.Ref"; - public static readonly string RuntimeName = "Components.None"; + public const string RuntimeName = "Components.None"; } } } diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentsApi.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentsApi.cs index 6e43c70490d7..e9b37d2fe179 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentsApi.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentsApi.cs @@ -7,161 +7,161 @@ namespace Microsoft.AspNetCore.Razor.Language.Components // 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 readonly string AddMultipleAttributesTypeFullName = "global::System.Collections.Generic.IEnumerable>"; + public const string AddMultipleAttributesTypeFullName = "global::System.Collections.Generic.IEnumerable>"; public static class ComponentBase { - public static readonly string Namespace = "Microsoft.AspNetCore.Components"; - public static readonly string FullTypeName = Namespace + ".ComponentBase"; - public static readonly string MetadataName = FullTypeName; + public const string Namespace = "Microsoft.AspNetCore.Components"; + public const string FullTypeName = Namespace + ".ComponentBase"; + public const string MetadataName = FullTypeName; - public static readonly string BuildRenderTree = nameof(BuildRenderTree); + public const string BuildRenderTree = nameof(BuildRenderTree); } 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 class LayoutAttribute { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.LayoutAttribute"; + public const string FullTypeName = "Microsoft.AspNetCore.Components.LayoutAttribute"; } public static class InjectAttribute { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.InjectAttribute"; + public const string FullTypeName = "Microsoft.AspNetCore.Components.InjectAttribute"; } public static class IComponent { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.IComponent"; + public const string FullTypeName = "Microsoft.AspNetCore.Components.IComponent"; - public static readonly string MetadataName = FullTypeName; + public const string MetadataName = FullTypeName; } public static class IDictionary { - public static readonly string MetadataName = "System.Collection.IDictionary`2"; + public const string MetadataName = "System.Collection.IDictionary`2"; } public static class RenderFragment { - public static readonly string Namespace = "Microsoft.AspNetCore.Components"; - public static readonly string FullTypeName = Namespace + ".RenderFragment"; - public static readonly string MetadataName = FullTypeName; + public const string Namespace = "Microsoft.AspNetCore.Components"; + public const string FullTypeName = Namespace + ".RenderFragment"; + public const string MetadataName = FullTypeName; } public static class RenderFragmentOfT { - public static readonly string Namespace = "Microsoft.AspNetCore.Components"; - public static readonly string FullTypeName = Namespace + ".RenderFragment<>"; - public static readonly string MetadataName = Namespace + ".RenderFragment`1"; + public const string Namespace = "Microsoft.AspNetCore.Components"; + public const string FullTypeName = Namespace + ".RenderFragment<>"; + public const string MetadataName = Namespace + ".RenderFragment`1"; } public static class RenderTreeBuilder { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder"; + public const string FullTypeName = "Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder"; - public static readonly string BuilderParameter = "__builder"; + public const string BuilderParameter = "__builder"; - public static readonly string OpenElement = nameof(OpenElement); + public const string OpenElement = nameof(OpenElement); - public static readonly string CloseElement = nameof(CloseElement); + public const string CloseElement = nameof(CloseElement); - public static readonly string OpenComponent = nameof(OpenComponent); + public const string OpenComponent = nameof(OpenComponent); - public static readonly string CloseComponent = nameof(CloseComponent); + public const string CloseComponent = nameof(CloseComponent); - public static readonly string AddMarkupContent = nameof(AddMarkupContent); + public const string AddMarkupContent = nameof(AddMarkupContent); - public static readonly string AddContent = nameof(AddContent); + public const string AddContent = nameof(AddContent); - public static readonly string AddAttribute = nameof(AddAttribute); + public const string AddAttribute = nameof(AddAttribute); - public static readonly string AddMultipleAttributes = nameof(AddMultipleAttributes); + public const string AddMultipleAttributes = nameof(AddMultipleAttributes); - public static readonly string AddElementReferenceCapture = nameof(AddElementReferenceCapture); + public const string AddElementReferenceCapture = nameof(AddElementReferenceCapture); - public static readonly string AddComponentReferenceCapture = nameof(AddComponentReferenceCapture); + public const string AddComponentReferenceCapture = nameof(AddComponentReferenceCapture); - public static readonly string Clear = nameof(Clear); + public const string Clear = nameof(Clear); - public static readonly string GetFrames = nameof(GetFrames); + public const string GetFrames = nameof(GetFrames); - public static readonly string ChildContent = nameof(ChildContent); + public const string ChildContent = nameof(ChildContent); - public static readonly string SetKey = nameof(SetKey); + public const string SetKey = nameof(SetKey); - public static readonly string SetUpdatesAttributeName = nameof(SetUpdatesAttributeName); + public const string SetUpdatesAttributeName = nameof(SetUpdatesAttributeName); - public static readonly string AddEventPreventDefaultAttribute = nameof(AddEventPreventDefaultAttribute); + public const string AddEventPreventDefaultAttribute = nameof(AddEventPreventDefaultAttribute); - public static readonly string AddEventStopPropagationAttribute = nameof(AddEventStopPropagationAttribute); + public const string AddEventStopPropagationAttribute = nameof(AddEventStopPropagationAttribute); } public static class RuntimeHelpers { - public static readonly string TypeCheck = "Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck"; - public static readonly string CreateInferredEventCallback = "Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.CreateInferredEventCallback"; + public const string TypeCheck = "Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck"; + public const string CreateInferredEventCallback = "Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.CreateInferredEventCallback"; } public static class RouteAttribute { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.RouteAttribute"; + public const string FullTypeName = "Microsoft.AspNetCore.Components.RouteAttribute"; } public static class BindElementAttribute { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.BindElementAttribute"; + public const string FullTypeName = "Microsoft.AspNetCore.Components.BindElementAttribute"; } public static class BindInputElementAttribute { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.BindInputElementAttribute"; + public const string FullTypeName = "Microsoft.AspNetCore.Components.BindInputElementAttribute"; } public static class EventHandlerAttribute { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.EventHandlerAttribute"; + public const string FullTypeName = "Microsoft.AspNetCore.Components.EventHandlerAttribute"; } public static class ElementReference { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.ElementReference"; + public const string FullTypeName = "Microsoft.AspNetCore.Components.ElementReference"; } public static class EventCallback { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.EventCallback"; - public static readonly string MetadataName = FullTypeName; + public const string FullTypeName = "Microsoft.AspNetCore.Components.EventCallback"; + public const string MetadataName = FullTypeName; - public static readonly string FactoryAccessor = FullTypeName + ".Factory"; + public const string FactoryAccessor = FullTypeName + ".Factory"; } public static class EventCallbackOfT { - public static readonly string MetadataName = "Microsoft.AspNetCore.Components.EventCallback`1"; + public const string MetadataName = "Microsoft.AspNetCore.Components.EventCallback`1"; } public static class EventCallbackFactory { - public static readonly string CreateMethod = "Create"; - public static readonly string CreateBinderMethod = "CreateBinder"; + public const string CreateMethod = "Create"; + public const string CreateBinderMethod = "CreateBinder"; } public static class BindConverter { - public static readonly string FullTypeName = "Microsoft.AspNetCore.Components.BindConverter"; - public static readonly string FormatValue = "Microsoft.AspNetCore.Components.BindConverter.FormatValue"; + public const string FullTypeName = "Microsoft.AspNetCore.Components.BindConverter"; + public const string FormatValue = "Microsoft.AspNetCore.Components.BindConverter.FormatValue"; } public static class CascadingTypeParameterAttribute { - public static readonly string MetadataName = "Microsoft.AspNetCore.Components.CascadingTypeParameterAttribute"; + public const string MetadataName = "Microsoft.AspNetCore.Components.CascadingTypeParameterAttribute"; } } } diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/HtmlContentIntermediateNodeExtensions.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/HtmlContentIntermediateNodeExtensions.cs index 5ca25f851d07..5ea7d5283d69 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/HtmlContentIntermediateNodeExtensions.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/HtmlContentIntermediateNodeExtensions.cs @@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Intermediate { internal static class HtmlContentIntermediateNodeExtensions { - private static readonly string HasEncodedContent = "HasEncodedContent"; + private const string HasEncodedContent = "HasEncodedContent"; public static bool IsEncoded(this HtmlContentIntermediateNode node) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/HtmlTokenizer.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/HtmlTokenizer.cs index aab93bdef812..4c162717f3ea 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/HtmlTokenizer.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/HtmlTokenizer.cs @@ -10,8 +10,6 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy // Tokenizer _loosely_ based on http://dev.w3.org/html5/spec/Overview.html#tokenization internal class HtmlTokenizer : Tokenizer { - private const char TransitionChar = '@'; - public HtmlTokenizer(ITextDocument source) : base(source) { @@ -253,23 +251,23 @@ private SyntaxToken Newline() return EndToken(SyntaxKind.NewLine); } - private bool AtToken() + private bool AtToken() { switch (CurrentCharacter) - { - case '<': - case '!': - case '/': - case '?': - case '[': - case '>': - case ']': - case '=': - case '"': + { + case '<': + case '!': + case '/': + case '?': + case '[': + case '>': + case ']': + case '=': + case '"': case '\'': - case '@': - return true; - case '-': + case '@': + return true; + case '-': return Peek() == '-'; } diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/SyntaxConstants.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/SyntaxConstants.cs index a4314b285a9a..51408d779cfd 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/SyntaxConstants.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/SyntaxConstants.cs @@ -5,28 +5,28 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy { internal static class SyntaxConstants { - public static readonly string TextTagName = "text"; - public static readonly char TransitionCharacter = '@'; - public static readonly string TransitionString = "@"; - public static readonly string StartCommentSequence = "@*"; - public static readonly string EndCommentSequence = "*@"; - public static readonly string SpanContextKind = "SpanData"; + public const string TextTagName = "text"; + public const char TransitionCharacter = '@'; + public const string TransitionString = "@"; + public const string StartCommentSequence = "@*"; + public const string EndCommentSequence = "*@"; + public const string SpanContextKind = "SpanData"; public static class CSharp { - public static readonly int UsingKeywordLength = 5; - public static readonly string TagHelperPrefixKeyword = "tagHelperPrefix"; - public static readonly string AddTagHelperKeyword = "addTagHelper"; - public static readonly string RemoveTagHelperKeyword = "removeTagHelper"; - public static readonly string InheritsKeyword = "inherits"; - public static readonly string FunctionsKeyword = "functions"; - public static readonly string SectionKeyword = "section"; - public static readonly string ElseIfKeyword = "else if"; - public static readonly string NamespaceKeyword = "namespace"; - public static readonly string ClassKeyword = "class"; + public const int UsingKeywordLength = 5; + public const string TagHelperPrefixKeyword = "tagHelperPrefix"; + public const string AddTagHelperKeyword = "addTagHelper"; + public const string RemoveTagHelperKeyword = "removeTagHelper"; + public const string InheritsKeyword = "inherits"; + public const string FunctionsKeyword = "functions"; + public const string SectionKeyword = "section"; + public const string ElseIfKeyword = "else if"; + public const string NamespaceKeyword = "namespace"; + public const string ClassKeyword = "class"; // Not supported. Only used for error cases. - public static readonly string HelperKeyword = "helper"; + public const string HelperKeyword = "helper"; } } } diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/TagHelperParseTreeRewriter.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/TagHelperParseTreeRewriter.cs index 2c661f27b983..a56788382a35 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/TagHelperParseTreeRewriter.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/TagHelperParseTreeRewriter.cs @@ -49,7 +49,7 @@ internal class Rewriter : SyntaxRewriter { // Internal for testing. // Null characters are invalid markup for HTML attribute values. - internal static readonly string InvalidAttributeValueMarker = "\0"; + internal const string InvalidAttributeValueMarker = "\0"; private readonly RazorSourceDocument _source; private readonly string _tagHelperPrefix; diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/MarkupEndTagSyntax.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/MarkupEndTagSyntax.cs index 2f0277287ac3..c4d7bae935d1 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/MarkupEndTagSyntax.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/MarkupEndTagSyntax.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Syntax.InternalSyntax { internal sealed partial class MarkupEndTagSyntax { - private static readonly string MarkupTransitionKey = "MarkupTransition"; + private const string MarkupTransitionKey = "MarkupTransition"; public bool IsMarkupTransition { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/MarkupStartTagSyntax.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/MarkupStartTagSyntax.cs index 47565e6e9392..3ff4e34c0752 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/MarkupStartTagSyntax.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/MarkupStartTagSyntax.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Syntax.InternalSyntax { internal sealed partial class MarkupStartTagSyntax { - private static readonly string MarkupTransitionKey = "MarkupTransition"; + private const string MarkupTransitionKey = "MarkupTransition"; public bool IsMarkupTransition { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/DefaultTagHelperTargetExtensionTest.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/DefaultTagHelperTargetExtensionTest.cs index fba53cd721c4..2a8bc2b33524 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/DefaultTagHelperTargetExtensionTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/DefaultTagHelperTargetExtensionTest.cs @@ -38,19 +38,6 @@ public class DefaultTagHelperTargetExtensionTest : RazorProjectEngineTestBase .TypeName("System.Int32"), }); - private static readonly TagHelperDescriptor StringIndexerTagHelper = CreateTagHelperDescriptor( - tagName: "input", - typeName: "InputTagHelper", - assemblyName: "TestAssembly", - attributes: new Action[] - { - builder => builder - .Name("bound") - .PropertyName("StringIndexer") - .TypeName("System.Collections.Generic.Dictionary") - .AsDictionary("foo-", "System.String"), - }); - private static readonly TagHelperDescriptor IntIndexerTagHelper = CreateTagHelperDescriptor( tagName: "input", typeName: "InputTagHelper", @@ -1083,7 +1070,7 @@ public void WriteTagHelperRuntime_DesignTime_RendersPreRequisites() // Arrange var extension = new DefaultTagHelperTargetExtension(); var context = TestCodeRenderingContext.CreateDesignTime(); - + var node = new DefaultTagHelperRuntimeIntermediateNode(); // Act @@ -1108,7 +1095,7 @@ public void WriteTagHelperRuntime_Runtime_DeclaresRequiredFields() // Arrange var extension = new DefaultTagHelperTargetExtension(); var context = TestCodeRenderingContext.CreateRuntime(); - + var node = new DefaultTagHelperRuntimeIntermediateNode(); // Act diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentChildContentIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentChildContentIntegrationTest.cs index f241a665afd0..7e8d79e59292 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentChildContentIntegrationTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentChildContentIntegrationTest.cs @@ -48,38 +48,6 @@ protected override void BuildRenderTree(RenderTreeBuilder builder) public string Value { get; set; } } } -"); - - private readonly CSharpSyntaxTree RenderMultipleChildContent = Parse(@" -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Rendering -namespace Test -{ - public class RenderMultipleChildContent : ComponentBase - { - protected override void BuildRenderTree(RenderTreeBuilder builder) - { - builder.AddContent(0, Header, Name); - builder.AddContent(1, ChildContent, Value); - builder.AddContent(2, Footer); - } - - [Parameter] - public string Name { get; set; } - - [Parameter] - public RenderFragment Header { get; set; } - - [Parameter] - public RenderFragment ChildContent { get; set; } - - [Parameter] - public RenderFragment Footer { get; set; } - - [Parameter] - public string Value { get; set; } - } -} "); internal override string FileKind => FileKinds.Component; diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpVerbatimBlockTest.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpVerbatimBlockTest.cs index a2f4509a6d5a..1e8eb6d6a763 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpVerbatimBlockTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpVerbatimBlockTest.cs @@ -8,8 +8,6 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy { public class CSharpVerbatimBlockTest : ParserTestBase { - private const string TestExtraKeyword = "model"; - [Fact] public void VerbatimBlock() { diff --git a/src/Razor/Microsoft.CodeAnalysis.Razor/src/DefaultTagHelperDescriptorFactory.cs b/src/Razor/Microsoft.CodeAnalysis.Razor/src/DefaultTagHelperDescriptorFactory.cs index 4eb83b36b770..a89f32d85ed6 100644 --- a/src/Razor/Microsoft.CodeAnalysis.Razor/src/DefaultTagHelperDescriptorFactory.cs +++ b/src/Razor/Microsoft.CodeAnalysis.Razor/src/DefaultTagHelperDescriptorFactory.cs @@ -12,7 +12,6 @@ namespace Microsoft.CodeAnalysis.Razor { internal class DefaultTagHelperDescriptorFactory { - private const string DataDashPrefix = "data-"; private const string TagHelperNameEnding = "TagHelper"; private readonly INamedTypeSymbol _htmlAttributeNameAttributeSymbol; diff --git a/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectTests.cs b/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectTests.cs index 9800b43c05cd..eff8ae939dc0 100644 --- a/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectTests.cs +++ b/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectTests.cs @@ -23,9 +23,6 @@ public class OpenIdConnectTests static string noncePrefix = "OpenIdConnect." + "Nonce."; static string nonceDelimiter = "."; const string DefaultHost = @"https://example.com"; - const string Logout = "/logout"; - const string Signin = "/signin"; - const string Signout = "/signout"; /// /// Tests RedirectForSignOutContext replaces the OpenIdConnectMesssage correctly. @@ -387,7 +384,7 @@ public void MapInboundClaimsCanBeSetToFalse() Assert.NotNull(jwtHandler); Assert.False(jwtHandler.MapInboundClaims); } - + // Test Cases for calculating the expiration time of cookie from cookie name [Fact] public void NonceCookieExpirationTime() diff --git a/src/Security/samples/Identity.ExternalClaims/Pages/Account/Manage/TwoFactorAuthentication.cshtml.cs b/src/Security/samples/Identity.ExternalClaims/Pages/Account/Manage/TwoFactorAuthentication.cshtml.cs index 8e05e5b1f98e..671cd8e2afca 100644 --- a/src/Security/samples/Identity.ExternalClaims/Pages/Account/Manage/TwoFactorAuthentication.cshtml.cs +++ b/src/Security/samples/Identity.ExternalClaims/Pages/Account/Manage/TwoFactorAuthentication.cshtml.cs @@ -12,8 +12,6 @@ namespace Identity.ExternalClaims.Pages.Account.Manage { public class TwoFactorAuthenticationModel : PageModel { - private const string AuthenicatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}"; - private readonly UserManager _userManager; private readonly SignInManager _signInManager; private readonly ILogger _logger; diff --git a/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs b/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs index e48789d2e500..7b23136fdf20 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs @@ -100,15 +100,15 @@ private void ValidateReadBuffer(byte[] buffer, int offset, int size) { if (buffer == null) { - throw new ArgumentNullException("buffer"); + throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { - throw new ArgumentOutOfRangeException("offset", offset, string.Empty); + throw new ArgumentOutOfRangeException(nameof(offset), offset, string.Empty); } if (size <= 0 || size > buffer.Length - offset) { - throw new ArgumentOutOfRangeException("size", size, string.Empty); + throw new ArgumentOutOfRangeException(nameof(size), size, string.Empty); } } diff --git a/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs b/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs index 83d31dc943bc..ab734118334c 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs @@ -556,7 +556,7 @@ internal async Task SendFileAsync(string fileName, long offset, long? count, Can // TODO: Verbose log parameters if (string.IsNullOrWhiteSpace(fileName)) { - throw new ArgumentNullException("fileName"); + throw new ArgumentNullException(nameof(fileName)); } CheckDisposed(); @@ -670,7 +670,7 @@ internal unsafe Task SendFileAsyncCore(string fileName, long offset, long? count } else { - // Abort the request but do not close the stream, let future writes complete + // Abort the request but do not close the stream, let future writes complete Log.FileSendAsyncErrorIgnored(Logger, statusCode); asyncResult.FailSilently(); } diff --git a/src/Servers/HttpSys/src/TimeoutManager.cs b/src/Servers/HttpSys/src/TimeoutManager.cs index cb84b63ae594..1455de647dfd 100644 --- a/src/Servers/HttpSys/src/TimeoutManager.cs +++ b/src/Servers/HttpSys/src/TimeoutManager.cs @@ -26,8 +26,8 @@ public sealed class TimeoutManager internal TimeoutManager() { // We have to maintain local state since we allow applications to set individual timeouts. Native Http - // API for setting timeouts expects all timeout values in every call so we have remember timeout values - // to fill in the blanks. Except MinSendBytesPerSecond, local state for remaining five timeouts is + // API for setting timeouts expects all timeout values in every call so we have remember timeout values + // to fill in the blanks. Except MinSendBytesPerSecond, local state for remaining five timeouts is // maintained in timeouts array. // // No initialization is required because a value of zero indicates that system defaults should be used. @@ -38,9 +38,9 @@ internal TimeoutManager() /// /// The time, in seconds, allowed for the request entity body to arrive. The default timer is 2 minutes. - /// - /// The HTTP Server API turns on this timer when the request has an entity body. The timer expiration is - /// initially set to the configured value. When the HTTP Server API receives additional data indications on the + /// + /// The HTTP Server API turns on this timer when the request has an entity body. The timer expiration is + /// initially set to the configured value. When the HTTP Server API receives additional data indications on the /// request, it resets the timer to give the connection another interval. /// /// Use TimeSpan.Zero to indicate that system defaults should be used. @@ -58,12 +58,12 @@ public TimeSpan EntityBody } /// - /// The time, in seconds, allowed for the HTTP Server API to drain the entity body on a Keep-Alive connection. + /// The time, in seconds, allowed for the HTTP Server API to drain the entity body on a Keep-Alive connection. /// The default timer is 2 minutes. - /// - /// On a Keep-Alive connection, after the application has sent a response for a request and before the request - /// entity body has completely arrived, the HTTP Server API starts draining the remainder of the entity body to - /// reach another potentially pipelined request from the client. If the time to drain the remaining entity body + /// + /// On a Keep-Alive connection, after the application has sent a response for a request and before the request + /// entity body has completely arrived, the HTTP Server API starts draining the remainder of the entity body to + /// reach another potentially pipelined request from the client. If the time to drain the remaining entity body /// exceeds the allowed period the connection is timed out. /// /// Use TimeSpan.Zero to indicate that system defaults should be used. @@ -81,7 +81,7 @@ public TimeSpan DrainEntityBody } /// - /// The time, in seconds, allowed for the request to remain in the request queue before the application picks + /// The time, in seconds, allowed for the request to remain in the request queue before the application picks /// it up. The default timer is 2 minutes. /// /// Use TimeSpan.Zero to indicate that system defaults should be used. @@ -100,7 +100,7 @@ public TimeSpan RequestQueue /// /// The time, in seconds, allowed for an idle connection. The default timer is 2 minutes. - /// + /// /// This timeout is only enforced after the first request on the connection is routed to the application. /// /// Use TimeSpan.Zero to indicate that system defaults should be used. @@ -118,9 +118,9 @@ public TimeSpan IdleConnection } /// - /// The time, in seconds, allowed for the HTTP Server API to parse the request header. The default timer is + /// The time, in seconds, allowed for the HTTP Server API to parse the request header. The default timer is /// 2 minutes. - /// + /// /// This timeout is only enforced after the first request on the connection is routed to the application. /// /// Use TimeSpan.Zero to indicate that system defaults should be used. @@ -138,9 +138,9 @@ public TimeSpan HeaderWait } /// - /// The minimum send rate, in bytes-per-second, for the response. The default response send rate is 150 + /// The minimum send rate, in bytes-per-second, for the response. The default response send rate is 150 /// bytes-per-second. - /// + /// /// Use 0 to indicate that system defaults should be used. /// /// To disable this timer set it to UInt32.MaxValue @@ -157,7 +157,7 @@ public long MinSendBytesPerSecond // MinSendRate value is ULONG in native layer. if (value < 0 || value > uint.MaxValue) { - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException(nameof(value)); } SetUrlGroupTimeouts(_timeouts, (uint)value); @@ -184,10 +184,10 @@ private void SetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE type, TimeSpan va if (timeoutValue < 0 || timeoutValue > ushort.MaxValue) { - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException(nameof(value)); } - // Use local state to get values for other timeouts. Call into the native layer and if that + // Use local state to get values for other timeouts. Call into the native layer and if that // call succeeds, update local state. var newTimeouts = (int[])_timeouts.Clone(); newTimeouts[(int)type] = (int)timeoutValue; diff --git a/src/Servers/HttpSys/src/UrlPrefix.cs b/src/Servers/HttpSys/src/UrlPrefix.cs index 31a56b4d90be..4e629571d268 100644 --- a/src/Servers/HttpSys/src/UrlPrefix.cs +++ b/src/Servers/HttpSys/src/UrlPrefix.cs @@ -65,12 +65,12 @@ public static UrlPrefix Create(string scheme, string host, int? portValue, strin } else { - throw new ArgumentOutOfRangeException("scheme", scheme, Resources.Exception_UnsupportedScheme); + throw new ArgumentOutOfRangeException(nameof(scheme), scheme, Resources.Exception_UnsupportedScheme); } if (string.IsNullOrWhiteSpace(host)) { - throw new ArgumentNullException("host"); + throw new ArgumentNullException(nameof(host)); } string port; diff --git a/src/Servers/IIS/IISIntegration/src/WebHostBuilderIISExtensions.cs b/src/Servers/IIS/IISIntegration/src/WebHostBuilderIISExtensions.cs index acb9ea3536d1..de368871bfa7 100644 --- a/src/Servers/IIS/IISIntegration/src/WebHostBuilderIISExtensions.cs +++ b/src/Servers/IIS/IISIntegration/src/WebHostBuilderIISExtensions.cs @@ -17,11 +17,11 @@ namespace Microsoft.AspNetCore.Hosting public static class WebHostBuilderIISExtensions { // These are defined as ASPNETCORE_ environment variables by IIS's AspNetCoreModule. - private static readonly string ServerPort = "PORT"; - private static readonly string ServerPath = "APPL_PATH"; - private static readonly string PairingToken = "TOKEN"; - private static readonly string IISAuth = "IIS_HTTPAUTH"; - private static readonly string IISWebSockets = "IIS_WEBSOCKETS_SUPPORTED"; + private const string ServerPort = "PORT"; + private const string ServerPath = "APPL_PATH"; + private const string PairingToken = "TOKEN"; + private const string IISAuth = "IIS_HTTPAUTH"; + private const string IISWebSockets = "IIS_WEBSOCKETS_SUPPORTED"; /// /// Configures the port and base path the server should listen on when running behind AspNetCoreModule. diff --git a/src/Servers/IIS/IntegrationTesting.IIS/src/RetryHandler.cs b/src/Servers/IIS/IntegrationTesting.IIS/src/RetryHandler.cs index 4282c3afca1a..8baa9758157a 100644 --- a/src/Servers/IIS/IntegrationTesting.IIS/src/RetryHandler.cs +++ b/src/Servers/IIS/IntegrationTesting.IIS/src/RetryHandler.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting.IIS { public class RetryHandler : DelegatingHandler { - private static readonly int MaxRetries = 5; + private const int MaxRetries = 5; private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(1); private readonly ILogger _logger; diff --git a/src/Servers/Kestrel/Core/src/Internal/Http/HttpHeaders.cs b/src/Servers/Kestrel/Core/src/Internal/Http/HttpHeaders.cs index c823ff2ef829..7df31cac9eba 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http/HttpHeaders.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http/HttpHeaders.cs @@ -291,7 +291,9 @@ public static void ValidateHeaderNameCharacters(string headerCharacters) } } - private readonly static string KeepAlive = "keep-alive"; +#pragma warning disable CA1802 // Use literals where appropriate. Using a static field for reference equality + private static readonly string KeepAlive = "keep-alive"; +#pragma warning restore CA1802 private readonly static StringValues ConnectionValueKeepAlive = KeepAlive; private readonly static StringValues ConnectionValueClose = "close"; private readonly static StringValues ConnectionValueUpgrade = HeaderNames.Upgrade; diff --git a/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs b/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs index ce7ee215be8d..4e5bc2292f6f 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs @@ -30,7 +30,7 @@ internal partial class Http2Connection : IHttp2StreamLifetimeHandler, IHttpHeade { public static ReadOnlySpan ClientPreface => ClientPrefaceBytes; - private static readonly PseudoHeaderFields _mandatoryRequestPseudoHeaderFields = + private const PseudoHeaderFields _mandatoryRequestPseudoHeaderFields = PseudoHeaderFields.Method | PseudoHeaderFields.Path | PseudoHeaderFields.Scheme; private readonly HttpConnectionContext _context; @@ -721,7 +721,7 @@ private Task ProcessRstStreamFrameAsync() // If RST_STREAM has already been received then the stream is in a closed state. // Additional frames (other than PRIORITY) are a stream error. // The server will usually send a RST_STREAM for a stream error, but RST_STREAM - // shouldn't be sent in response to RST_STREAM to avoid a loop. + // shouldn't be sent in response to RST_STREAM to avoid a loop. // The best course of action here is to do nothing. return Task.CompletedTask; } diff --git a/src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs b/src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs index 08f6033f8bfe..3a356bb4a4a0 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs @@ -33,7 +33,7 @@ internal abstract partial class Http3Stream : HttpProtocol, IHttp3Stream, IHttpH private static ReadOnlySpan TrailersBytes => new byte[8] { (byte)'t', (byte)'r', (byte)'a', (byte)'i', (byte)'l', (byte)'e', (byte)'r', (byte)'s' }; private static ReadOnlySpan ConnectBytes => new byte[7] { (byte)'C', (byte)'O', (byte)'N', (byte)'N', (byte)'E', (byte)'C', (byte)'T' }; - private static readonly PseudoHeaderFields _mandatoryRequestPseudoHeaderFields = + private const PseudoHeaderFields _mandatoryRequestPseudoHeaderFields = PseudoHeaderFields.Method | PseudoHeaderFields.Path | PseudoHeaderFields.Scheme; private readonly Http3FrameWriter _frameWriter; diff --git a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/Constants.cs b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/Constants.cs index c485f0bfbdee..1f3d25b15396 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/Constants.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/Constants.cs @@ -12,12 +12,12 @@ internal static class Constants /// /// The endpoint Kestrel will bind to if nothing else is specified. /// - public static readonly string DefaultServerAddress = "http://localhost:5000"; + public const string DefaultServerAddress = "http://localhost:5000"; /// /// The endpoint Kestrel will bind to if nothing else is specified and a default certificate is available. /// - public static readonly string DefaultServerHttpsAddress = "https://localhost:5001"; + public const string DefaultServerHttpsAddress = "https://localhost:5001"; /// /// Prefix of host name used to specify Unix sockets in the configuration. diff --git a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/HttpCharacters.cs b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/HttpCharacters.cs index 8e4b5ce37670..d59ab76a2a41 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/HttpCharacters.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/HttpCharacters.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure { internal static class HttpCharacters { - private static readonly int _tableSize = 128; + private const int _tableSize = 128; private static readonly bool[] _alphaNumeric = InitializeAlphaNumeric(); private static readonly bool[] _authority = InitializeAuthority(); private static readonly bool[] _token = InitializeToken(); diff --git a/src/Servers/Kestrel/Core/src/ListenOptions.cs b/src/Servers/Kestrel/Core/src/ListenOptions.cs index 520bd77431fe..56707ff8e674 100644 --- a/src/Servers/Kestrel/Core/src/ListenOptions.cs +++ b/src/Servers/Kestrel/Core/src/ListenOptions.cs @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core /// public class ListenOptions : IConnectionBuilder, IMultiplexedConnectionBuilder { - internal static readonly HttpProtocols DefaultHttpProtocols = HttpProtocols.Http1AndHttp2; + internal const HttpProtocols DefaultHttpProtocols = HttpProtocols.Http1AndHttp2; internal readonly List> _middleware = new List>(); internal readonly List> _multiplexedMiddleware = new List>(); diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/ListenerPrimary.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/ListenerPrimary.cs index 9b7528935f5c..9fee8c9ba7b5 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/ListenerPrimary.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/ListenerPrimary.cs @@ -163,11 +163,13 @@ private void DetachFromIOCP(UvHandle handle) } } +#pragma warning disable CA1823 // Avoid unused private fields private struct IO_STATUS_BLOCK { uint status; ulong information; } +#pragma warning restore CA1823 private struct FILE_COMPLETION_INFORMATION { diff --git a/src/Servers/Kestrel/perf/Microbenchmarks/Http1ConnectionBenchmark.cs b/src/Servers/Kestrel/perf/Microbenchmarks/Http1ConnectionBenchmark.cs index 45ddff65c3a6..2ea8447b5574 100644 --- a/src/Servers/Kestrel/perf/Microbenchmarks/Http1ConnectionBenchmark.cs +++ b/src/Servers/Kestrel/perf/Microbenchmarks/Http1ConnectionBenchmark.cs @@ -18,8 +18,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Microbenchmarks { public class Http1ConnectionBenchmark { - private const int InnerLoopCount = 512; - private readonly HttpParser _parser = new HttpParser(); private ReadOnlySequence _buffer; diff --git a/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs b/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs index fb4294748fec..40fd454292bd 100644 --- a/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs +++ b/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs @@ -24,12 +24,10 @@ public static class H2SpecCommands // group permission const int S_IRGRP = 0x20; - const int S_IWGRP = 0x10; const int S_IXGRP = 0x8; // other permissions const int S_IROTH = 0x4; - const int S_IWOTH = 0x2; const int S_IXOTH = 0x1; const int _0755 = diff --git a/src/Shared/ActivatorUtilities/ActivatorUtilitiesConstructorAttribute.cs b/src/Shared/ActivatorUtilities/ActivatorUtilitiesConstructorAttribute.cs index 67ffa13f6fc0..83dfd5599b8a 100644 --- a/src/Shared/ActivatorUtilities/ActivatorUtilitiesConstructorAttribute.cs +++ b/src/Shared/ActivatorUtilities/ActivatorUtilitiesConstructorAttribute.cs @@ -3,24 +3,16 @@ using System; -#if ActivatorUtilities_In_DependencyInjection -namespace Microsoft.Extensions.DependencyInjection -#else namespace Microsoft.Extensions.Internal -#endif { /// /// Marks the constructor to be used when activating type using . /// -#if ActivatorUtilities_In_DependencyInjection - public -#else // Do not take a dependency on this class unless you are explicitly trying to avoid taking a // dependency on Microsoft.AspNetCore.DependencyInjection.Abstractions. - internal -#endif - class ActivatorUtilitiesConstructorAttribute: Attribute + [AttributeUsage(AttributeTargets.All)] + internal sealed class ActivatorUtilitiesConstructorAttribute: Attribute { } } diff --git a/src/Shared/BenchmarkRunner/AspNetCoreBenchmarkAttribute.cs b/src/Shared/BenchmarkRunner/AspNetCoreBenchmarkAttribute.cs index d16493a738e6..4048803f7089 100644 --- a/src/Shared/BenchmarkRunner/AspNetCoreBenchmarkAttribute.cs +++ b/src/Shared/BenchmarkRunner/AspNetCoreBenchmarkAttribute.cs @@ -52,7 +52,7 @@ public IConfig Config $"Known configurations: {string.Join(", ", ConfigTypes.Keys)}"; throw new InvalidOperationException(message); } - + return (IConfig)Activator.CreateInstance(configType, Array.Empty()); } } @@ -63,11 +63,11 @@ public IConfig Config public static class NamedConfiguration { - public static readonly string Default = "default"; - public static readonly string Validation = "validation"; - public static readonly string Profile = "profile"; - public static readonly string Debug = "debug"; - public static readonly string PerfLab = "perflab"; + public const string Default = "default"; + public const string Validation = "validation"; + public const string Profile = "profile"; + public const string Debug = "debug"; + public const string PerfLab = "perflab"; } } } diff --git a/src/Shared/CertificateGeneration/MacOSCertificateManager.cs b/src/Shared/CertificateGeneration/MacOSCertificateManager.cs index c2a8194b67f8..15e10b885d97 100644 --- a/src/Shared/CertificateGeneration/MacOSCertificateManager.cs +++ b/src/Shared/CertificateGeneration/MacOSCertificateManager.cs @@ -17,14 +17,14 @@ internal class MacOSCertificateManager : CertificateManager private static readonly string MacOSUserKeyChain = Environment.GetEnvironmentVariable("HOME") + "/Library/Keychains/login.keychain-db"; private const string MacOSSystemKeyChain = "/Library/Keychains/System.keychain"; private const string MacOSFindCertificateCommandLine = "security"; - private static readonly string MacOSFindCertificateCommandLineArgumentsFormat = "find-certificate -c {0} -a -Z -p " + MacOSSystemKeyChain; + private const string MacOSFindCertificateCommandLineArgumentsFormat = "find-certificate -c {0} -a -Z -p " + MacOSSystemKeyChain; private const string MacOSFindCertificateOutputRegex = "SHA-1 hash: ([0-9A-Z]+)"; private const string MacOSRemoveCertificateTrustCommandLine = "sudo"; private const string MacOSRemoveCertificateTrustCommandLineArgumentsFormat = "security remove-trusted-cert -d {0}"; private const string MacOSDeleteCertificateCommandLine = "sudo"; private const string MacOSDeleteCertificateCommandLineArgumentsFormat = "security delete-certificate -Z {0} {1}"; private const string MacOSTrustCertificateCommandLine = "sudo"; - private static readonly string MacOSTrustCertificateCommandLineArguments = "security add-trusted-cert -d -r trustRoot -k " + MacOSSystemKeyChain + " "; + private const string MacOSTrustCertificateCommandLineArguments = "security add-trusted-cert -d -r trustRoot -k " + MacOSSystemKeyChain + " "; private const string MacOSAddCertificateToKeyChainCommandLine = "security"; private static readonly string MacOSAddCertificateToKeyChainCommandLineArgumentsFormat = "import {0} -k " + MacOSUserKeyChain + " -t cert -f pkcs12 -P {1} -A"; diff --git a/src/Shared/HttpSys/NativeInterop/SocketAddress.cs b/src/Shared/HttpSys/NativeInterop/SocketAddress.cs index de0bbfeaf862..407dc50fdcab 100644 --- a/src/Shared/HttpSys/NativeInterop/SocketAddress.cs +++ b/src/Shared/HttpSys/NativeInterop/SocketAddress.cs @@ -50,7 +50,7 @@ public SocketAddress(AddressFamily family, int size) // it doesn't make sense to create a socket address with less tha // 2 bytes, that's where we store the address family. - throw new ArgumentOutOfRangeException("size"); + throw new ArgumentOutOfRangeException(nameof(size)); } _size = size; _buffer = new byte[((size / IntPtr.Size) + 2) * IntPtr.Size]; // sizeof DWORD @@ -111,7 +111,7 @@ private byte this[int offset] // access if (offset < 0 || offset >= Size) { - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException(nameof(offset)); } return _buffer[offset]; } diff --git a/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs b/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs index 14c55cefcbd5..6db9113a9732 100644 --- a/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs +++ b/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs @@ -10,10 +10,8 @@ namespace Microsoft.AspNetCore.HttpSys.Internal internal static unsafe class UnsafeNclNativeMethods { private const string sspicli_LIB = "sspicli.dll"; - private const string api_ms_win_core_processthreads_LIB = "api-ms-win-core-processthreads-l1-1-1.dll"; private const string api_ms_win_core_io_LIB = "api-ms-win-core-io-l1-1-0.dll"; private const string api_ms_win_core_handle_LIB = "api-ms-win-core-handle-l1-1-0.dll"; - private const string api_ms_win_core_libraryloader_LIB = "api-ms-win-core-libraryloader-l1-1-0.dll"; private const string api_ms_win_core_heap_LIB = "api-ms-win-core-heap-L1-2-0.dll"; private const string api_ms_win_core_heap_obsolete_LIB = "api-ms-win-core-heap-obsolete-L1-1-0.dll"; private const string api_ms_win_core_kernel32_legacy_LIB = "api-ms-win-core-kernel32-legacy-l1-1-0.dll"; @@ -146,7 +144,7 @@ internal unsafe struct TOKENBINDING_RESULT_LIST // DACL related stuff [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Instantiated natively")] - [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", + [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Does not own the resource.")] [StructLayout(LayoutKind.Sequential)] internal class SECURITY_ATTRIBUTES diff --git a/src/Shared/HttpSys/RequestProcessing/HeaderCollection.cs b/src/Shared/HttpSys/RequestProcessing/HeaderCollection.cs index c2b97368a8a1..4725fba81741 100644 --- a/src/Shared/HttpSys/RequestProcessing/HeaderCollection.cs +++ b/src/Shared/HttpSys/RequestProcessing/HeaderCollection.cs @@ -145,7 +145,7 @@ public long? ContentLength { if (value.Value < 0) { - throw new ArgumentOutOfRangeException("value", value.Value, "Cannot be negative."); + throw new ArgumentOutOfRangeException(nameof(value), value.Value, "Cannot be negative."); } _contentLengthText = HeaderUtilities.FormatNonNegativeInt64(value.Value); this[HeaderNames.ContentLength] = _contentLengthText; diff --git a/src/Shared/HttpSys/RequestProcessing/RequestHeaders.cs b/src/Shared/HttpSys/RequestProcessing/RequestHeaders.cs index 4540a2b62a7f..af850388c901 100644 --- a/src/Shared/HttpSys/RequestProcessing/RequestHeaders.cs +++ b/src/Shared/HttpSys/RequestProcessing/RequestHeaders.cs @@ -168,7 +168,7 @@ bool ICollection>.IsReadOnly { if (value.Value < 0) { - throw new ArgumentOutOfRangeException("value", value.Value, "Cannot be negative."); + throw new ArgumentOutOfRangeException(nameof(value), value.Value, "Cannot be negative."); } _contentLengthText = HeaderUtilities.FormatNonNegativeInt64(value.Value); this[HeaderNames.ContentLength] = _contentLengthText; diff --git a/src/Shared/OperatingSystem.cs b/src/Shared/OperatingSystem.cs index 7bba4fb18a44..0db964d67117 100644 --- a/src/Shared/OperatingSystem.cs +++ b/src/Shared/OperatingSystem.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore internal sealed class OperatingSystem { #if NET461 - private static readonly bool _isBrowser = false; + private const bool _isBrowser = false; #else private static readonly bool _isBrowser = RuntimeInformation.IsOSPlatform(OSPlatform.Create("browser")); #endif diff --git a/src/Shared/WebEncoders/Properties/EncoderResources.cs b/src/Shared/WebEncoders/Properties/EncoderResources.cs index 3474ae82c5b7..b9c62e73ddd0 100644 --- a/src/Shared/WebEncoders/Properties/EncoderResources.cs +++ b/src/Shared/WebEncoders/Properties/EncoderResources.cs @@ -12,12 +12,12 @@ internal static class EncoderResources /// /// Invalid {0}, {1} or {2} length. /// - internal static readonly string WebEncoders_InvalidCountOffsetOrLength = "Invalid {0}, {1} or {2} length."; + internal const string WebEncoders_InvalidCountOffsetOrLength = "Invalid {0}, {1} or {2} length."; /// /// Malformed input: {0} is an invalid input length. /// - internal static readonly string WebEncoders_MalformedInput = "Malformed input: {0} is an invalid input length."; + internal const string WebEncoders_MalformedInput = "Malformed input: {0} is an invalid input length."; /// /// Invalid {0}, {1} or {2} length. diff --git a/src/Shared/test/Shared.Tests/runtime/Http2/HPackDecoderTest.cs b/src/Shared/test/Shared.Tests/runtime/Http2/HPackDecoderTest.cs index 6c84993d3fae..f73d72d3dd32 100644 --- a/src/Shared/test/Shared.Tests/runtime/Http2/HPackDecoderTest.cs +++ b/src/Shared/test/Shared.Tests/runtime/Http2/HPackDecoderTest.cs @@ -44,8 +44,6 @@ public class HPackDecoderTests private const string _userAgentString = "user-agent"; - private static readonly byte[] _userAgentBytes = Encoding.ASCII.GetBytes(_userAgentString); - private const string _headerNameString = "new-header"; private static readonly byte[] _headerNameBytes = Encoding.ASCII.GetBytes(_headerNameString); diff --git a/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs b/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs index b391fe314a6a..6779b8098213 100644 --- a/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs +++ b/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs @@ -51,9 +51,6 @@ public partial class HubConnection : IAsyncDisposable /// public static readonly TimeSpan DefaultKeepAliveInterval = TimeSpan.FromSeconds(15); - // This lock protects the connection state. - private readonly SemaphoreSlim _connectionLock = new SemaphoreSlim(1, 1); - // The receive loop has a single reader and single writer at a time so optimize the channel for that private static readonly UnboundedChannelOptions _receiveLoopOptions = new UnboundedChannelOptions { diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs b/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs index bb0f786db1df..6517ce5daf39 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs @@ -26,8 +26,8 @@ public partial class HttpConnection : ConnectionContext, IConnectionInherentKeep { // Not configurable on purpose, high enough that if we reach here, it's likely // a buggy server - private static readonly int _maxRedirects = 100; - private static readonly int _protocolVersionNumber = 1; + private const int _maxRedirects = 100; + private const int _protocolVersionNumber = 1; private static readonly Task _noAccessToken = Task.FromResult(null); private static readonly TimeSpan HttpClientTimeout = TimeSpan.FromSeconds(120); diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/Constants.cs b/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/Constants.cs index ed6687834944..f6270c107d8e 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/Constants.cs +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/Constants.cs @@ -11,7 +11,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal { internal static class Constants { +#pragma warning disable CA1802 public static readonly string UserAgent = "User-Agent"; +#pragma warning restore CA1802 public static readonly string UserAgentHeader; static Constants() diff --git a/src/SignalR/common/Http.Connections/src/Internal/HttpConnectionDispatcher.cs b/src/SignalR/common/Http.Connections/src/Internal/HttpConnectionDispatcher.cs index 86f5028307f1..abf0f54aa28c 100644 --- a/src/SignalR/common/Http.Connections/src/Internal/HttpConnectionDispatcher.cs +++ b/src/SignalR/common/Http.Connections/src/Internal/HttpConnectionDispatcher.cs @@ -46,7 +46,7 @@ internal partial class HttpConnectionDispatcher private readonly HttpConnectionManager _manager; private readonly ILoggerFactory _loggerFactory; private readonly ILogger _logger; - private static readonly int _protocolVersion = 1; + private const int _protocolVersion = 1; public HttpConnectionDispatcher(HttpConnectionManager manager, ILoggerFactory loggerFactory) { diff --git a/src/SignalR/common/Protocols.Json/src/Protocol/JsonHubProtocol.cs b/src/SignalR/common/Protocols.Json/src/Protocol/JsonHubProtocol.cs index d17094f6ef74..388ba02aae74 100644 --- a/src/SignalR/common/Protocols.Json/src/Protocol/JsonHubProtocol.cs +++ b/src/SignalR/common/Protocols.Json/src/Protocol/JsonHubProtocol.cs @@ -43,8 +43,8 @@ public sealed class JsonHubProtocol : IHubProtocol private const string HeadersPropertyName = "headers"; private static JsonEncodedText HeadersPropertyNameBytes = JsonEncodedText.Encode(HeadersPropertyName); - private static readonly string ProtocolName = "json"; - private static readonly int ProtocolVersion = 1; + private const string ProtocolName = "json"; + private const int ProtocolVersion = 1; /// /// Gets the serializer used to serialize invocation arguments and return values. diff --git a/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs b/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs index 37c71dc5fa16..22c3e0c918f9 100644 --- a/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs +++ b/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs @@ -18,8 +18,8 @@ namespace Microsoft.AspNetCore.SignalR.Protocol /// public class MessagePackHubProtocol : IHubProtocol { - private static readonly string ProtocolName = "messagepack"; - private static readonly int ProtocolVersion = 1; + private const string ProtocolName = "messagepack"; + private const int ProtocolVersion = 1; private readonly DefaultMessagePackHubProtocolWorker _worker; /// diff --git a/src/SignalR/common/Protocols.NewtonsoftJson/src/Protocol/NewtonsoftJsonHubProtocol.cs b/src/SignalR/common/Protocols.NewtonsoftJson/src/Protocol/NewtonsoftJsonHubProtocol.cs index 6c10a86ef229..2d44c7b2af17 100644 --- a/src/SignalR/common/Protocols.NewtonsoftJson/src/Protocol/NewtonsoftJsonHubProtocol.cs +++ b/src/SignalR/common/Protocols.NewtonsoftJson/src/Protocol/NewtonsoftJsonHubProtocol.cs @@ -34,8 +34,8 @@ public class NewtonsoftJsonHubProtocol : IHubProtocol private const string HeadersPropertyName = "headers"; private const string AllowReconnectPropertyName = "allowReconnect"; - private static readonly string ProtocolName = "json"; - private static readonly int ProtocolVersion = 1; + private const string ProtocolName = "json"; + private const int ProtocolVersion = 1; /// /// Gets the serializer used to serialize invocation arguments and return values. diff --git a/src/SignalR/common/Shared/TextMessageFormatter.cs b/src/SignalR/common/Shared/TextMessageFormatter.cs index 32470f320be9..72c8488b9c74 100644 --- a/src/SignalR/common/Shared/TextMessageFormatter.cs +++ b/src/SignalR/common/Shared/TextMessageFormatter.cs @@ -10,7 +10,7 @@ internal static class TextMessageFormatter { // This record separator is supposed to be used only for JSON payloads where 0x1e character // will not occur (is not a valid character) and therefore it is safe to not escape it - public static readonly byte RecordSeparator = 0x1e; + public const byte RecordSeparator = 0x1e; public static void WriteRecordSeparator(IBufferWriter output) { diff --git a/src/SignalR/common/Shared/Utf8BufferTextWriter.cs b/src/SignalR/common/Shared/Utf8BufferTextWriter.cs index 608bd4d536e3..89444b1751bb 100644 --- a/src/SignalR/common/Shared/Utf8BufferTextWriter.cs +++ b/src/SignalR/common/Shared/Utf8BufferTextWriter.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Internal internal sealed class Utf8BufferTextWriter : TextWriter { private static readonly UTF8Encoding _utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); - private static readonly int MaximumBytesPerUtf8Char = 4; + private const int MaximumBytesPerUtf8Char = 4; [ThreadStatic] private static Utf8BufferTextWriter? _cachedInstance; diff --git a/src/Testing/src/AssemblyTestLog.cs b/src/Testing/src/AssemblyTestLog.cs index c5b49f907a16..64bb0a550357 100644 --- a/src/Testing/src/AssemblyTestLog.cs +++ b/src/Testing/src/AssemblyTestLog.cs @@ -25,8 +25,8 @@ namespace Microsoft.AspNetCore.Testing { public class AssemblyTestLog : IDisposable { - private static readonly string MaxPathLengthEnvironmentVariableName = "ASPNETCORE_TEST_LOG_MAXPATH"; - private static readonly string LogFileExtension = ".log"; + private const string MaxPathLengthEnvironmentVariableName = "ASPNETCORE_TEST_LOG_MAXPATH"; + private const string LogFileExtension = ".log"; private static readonly int MaxPathLength = GetMaxPathLength(); private static readonly object _lock = new object(); diff --git a/src/Testing/src/xunit/SkipOnAlpineAttribute.cs b/src/Testing/src/xunit/SkipOnAlpineAttribute.cs index 4204d2bdcfc8..5482c6b8beb1 100644 --- a/src/Testing/src/xunit/SkipOnAlpineAttribute.cs +++ b/src/Testing/src/xunit/SkipOnAlpineAttribute.cs @@ -11,6 +11,7 @@ namespace Microsoft.AspNetCore.Testing /// /// Skip test if running on Alpine Linux (which uses musl instead of glibc) /// + [AttributeUsage(AttributeTargets.Method)] public class SkipOnAlpineAttribute : Attribute, ITestCondition { public SkipOnAlpineAttribute(string issueUrl = "")