diff --git a/.editorconfig b/.editorconfig index ade15f781f50..1af9937fd6fd 100644 --- a/.editorconfig +++ b/.editorconfig @@ -195,6 +195,7 @@ dotnet_diagnostic.CA2208.severity = warning dotnet_diagnostic.IDE0035.severity = warning # IDE0036: Order modifiers +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion dotnet_diagnostic.IDE0036.severity = warning # IDE0043: Format string contains invalid placeholder @@ -204,7 +205,7 @@ dotnet_diagnostic.IDE0043.severity = warning dotnet_diagnostic.IDE0044.severity = warning # IDE0073: File header -dotnet_diagnostic.IDE0073.severity = warning +dotnet_diagnostic.IDE0073.severity = suggestion file_header_template = Copyright (c) .NET Foundation. All rights reserved.\nLicensed under the Apache License, Version 2.0. See License.txt in the project root for license information. [**/{test,samples,perf}/**.{cs,vb}] diff --git a/eng/targets/CSharp.Common.targets b/eng/targets/CSharp.Common.targets index 4ed6574931c8..1599eea3a292 100644 --- a/eng/targets/CSharp.Common.targets +++ b/eng/targets/CSharp.Common.targets @@ -27,6 +27,9 @@ '$(ISBenchmarkProject)' == 'true' OR '$(IsSampleProject)' == 'true' OR '$(IsMicrobenchmarksProject)' == 'true'">$(NoWarn);CA1416 + + + true diff --git a/src/Analyzers/Analyzers/src/StartupAnalysis.cs b/src/Analyzers/Analyzers/src/StartupAnalysis.cs index 9ddc03e04e69..85e9ca0659c5 100644 --- a/src/Analyzers/Analyzers/src/StartupAnalysis.cs +++ b/src/Analyzers/Analyzers/src/StartupAnalysis.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Analyzers { internal class StartupAnalysis { - private ImmutableDictionary> _analysesByType; + private readonly ImmutableDictionary> _analysesByType; public StartupAnalysis( StartupSymbols startupSymbols, diff --git a/src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs b/src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs index cb2f50997ee1..59b1ec5b2ac8 100644 --- a/src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs +++ b/src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs @@ -27,7 +27,7 @@ static Diagnostics() }); } - internal readonly static DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor( + internal static readonly DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor( "ASP0000", "Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'", "Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.", @@ -36,7 +36,7 @@ static Diagnostics() isEnabledByDefault: true, helpLinkUri: "https://aka.ms/AA5k895"); - internal readonly static DiagnosticDescriptor UnsupportedUseMvcWithEndpointRouting = new DiagnosticDescriptor( + internal static readonly DiagnosticDescriptor UnsupportedUseMvcWithEndpointRouting = new DiagnosticDescriptor( "MVC1005", "Cannot use UseMvc with Endpoint Routing.", "Using '{0}' to configure MVC is not supported while using Endpoint Routing. To continue using '{0}', please set 'MvcOptions.EnableEndpointRouting = false' inside '{1}'.", @@ -45,7 +45,7 @@ static Diagnostics() isEnabledByDefault: true, helpLinkUri: "https://aka.ms/YJggeFn"); - internal readonly static DiagnosticDescriptor IncorrectlyConfiguredAuthorizationMiddleware = new DiagnosticDescriptor( + internal static readonly DiagnosticDescriptor IncorrectlyConfiguredAuthorizationMiddleware = new DiagnosticDescriptor( "ASP0001", "Authorization middleware is incorrectly configured.", "The call to UseAuthorization should appear between app.UseRouting() and app.UseEndpoints(..) for authorization to be correctly evaluated.", diff --git a/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs b/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs index 5c9a758db7c7..4726aace65dd 100644 --- a/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs +++ b/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Authentication.AzureADB2C.UI [Obsolete("This is obsolete and will be removed in a future version. Use Microsoft.Identity.Web instead. See https://aka.ms/ms-identity-web.")] internal class AzureADB2COpenIDConnectEventHandlers { - private IDictionary _policyToIssuerAddress = + private readonly IDictionary _policyToIssuerAddress = new Dictionary(StringComparer.OrdinalIgnoreCase); public AzureADB2COpenIDConnectEventHandlers(string schemeName, AzureADB2COptions options) diff --git a/src/Caching/SqlServer/src/PlatformHelper.cs b/src/Caching/SqlServer/src/PlatformHelper.cs index 380302431497..3bac348a2f42 100644 --- a/src/Caching/SqlServer/src/PlatformHelper.cs +++ b/src/Caching/SqlServer/src/PlatformHelper.cs @@ -7,7 +7,7 @@ namespace Microsoft.Extensions.Caching.SqlServer { internal static class PlatformHelper { - private static Lazy _isMono = new Lazy(() => Type.GetType("Mono.Runtime") != null); + private static readonly Lazy _isMono = new Lazy(() => Type.GetType("Mono.Runtime") != null); public static bool IsMono { @@ -17,4 +17,4 @@ public static bool IsMono } } } -} \ No newline at end of file +} diff --git a/src/Components/Analyzers/test/TestFiles/ComponentInternalUsageDiagnosticsAnalyzerTest/UsesRendererTypesInDeclarations.cs b/src/Components/Analyzers/test/TestFiles/ComponentInternalUsageDiagnosticsAnalyzerTest/UsesRendererTypesInDeclarations.cs index 0a0bd11b7bee..82dcfdc508a8 100644 --- a/src/Components/Analyzers/test/TestFiles/ComponentInternalUsageDiagnosticsAnalyzerTest/UsesRendererTypesInDeclarations.cs +++ b/src/Components/Analyzers/test/TestFiles/ComponentInternalUsageDiagnosticsAnalyzerTest/UsesRendererTypesInDeclarations.cs @@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.Components.Analyzers.Tests.TestFiles.ComponentInt { /*MMBaseClass*/class UsesRendererTypesInDeclarations : Renderer { - private Renderer /*MMField*/_field = null; + private readonly Renderer /*MMField*/_field = null; public UsesRendererTypesInDeclarations() /*MMInvocation*/: base(null, null) diff --git a/src/Components/Components/src/CascadingParameterState.cs b/src/Components/Components/src/CascadingParameterState.cs index c755bac06df6..712efc9e7976 100644 --- a/src/Components/Components/src/CascadingParameterState.cs +++ b/src/Components/Components/src/CascadingParameterState.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Components { internal readonly struct CascadingParameterState { - private readonly static ConcurrentDictionary _cachedInfos = new(); + private static readonly ConcurrentDictionary _cachedInfos = new(); public string LocalValueName { get; } public ICascadingValueComponent ValueSupplier { get; } diff --git a/src/Components/Components/src/DynamicComponent.cs b/src/Components/Components/src/DynamicComponent.cs index 43182500b0da..db83925d5dee 100644 --- a/src/Components/Components/src/DynamicComponent.cs +++ b/src/Components/Components/src/DynamicComponent.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Components public class DynamicComponent : IComponent { private RenderHandle _renderHandle; - private RenderFragment _cachedRenderFragment; + private readonly RenderFragment _cachedRenderFragment; /// /// Constructs an instance of . diff --git a/src/Components/Components/src/Lifetime/ComponentApplicationLifetime.cs b/src/Components/Components/src/Lifetime/ComponentApplicationLifetime.cs index 0aa85ceefbda..2d5464e3952f 100644 --- a/src/Components/Components/src/Lifetime/ComponentApplicationLifetime.cs +++ b/src/Components/Components/src/Lifetime/ComponentApplicationLifetime.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Components.Lifetime public class ComponentApplicationLifetime { private bool _stateIsPersisted; - private List _pauseCallbacks = new(); + private readonly List _pauseCallbacks = new(); private readonly Dictionary _currentState = new(); private readonly ILogger _logger; diff --git a/src/Components/Components/src/RenderTree/EventArgsTypeCache.cs b/src/Components/Components/src/RenderTree/EventArgsTypeCache.cs index 314545941589..ffb6379612c9 100644 --- a/src/Components/Components/src/RenderTree/EventArgsTypeCache.cs +++ b/src/Components/Components/src/RenderTree/EventArgsTypeCache.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Components.RenderTree { internal static class EventArgsTypeCache { - private static ConcurrentDictionary Cache = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary Cache = new ConcurrentDictionary(); public static Type GetEventArgsType(MethodInfo methodInfo) { diff --git a/src/Components/Components/src/Rendering/RenderTreeBuilder.cs b/src/Components/Components/src/Rendering/RenderTreeBuilder.cs index 65397a9a93f1..57441c85b696 100644 --- a/src/Components/Components/src/Rendering/RenderTreeBuilder.cs +++ b/src/Components/Components/src/Rendering/RenderTreeBuilder.cs @@ -20,9 +20,9 @@ namespace Microsoft.AspNetCore.Components.Rendering /// public sealed class RenderTreeBuilder : IDisposable { - private readonly static object BoxedTrue = true; - private readonly static object BoxedFalse = false; - private readonly static string ComponentReferenceCaptureInvalidParentMessage = $"Component reference captures may only be added as children of frames of type {RenderTreeFrameType.Component}"; + private static readonly object BoxedTrue = true; + private static readonly object BoxedFalse = false; + private static readonly string ComponentReferenceCaptureInvalidParentMessage = $"Component reference captures may only be added as children of frames of type {RenderTreeFrameType.Component}"; private readonly RenderTreeFrameArrayBuilder _entries = new RenderTreeFrameArrayBuilder(); private readonly Stack _openElementIndices = new Stack(); diff --git a/src/Components/Components/src/Rendering/SimplifiedStringHashComparer.cs b/src/Components/Components/src/Rendering/SimplifiedStringHashComparer.cs index ecdb7cc8dd2f..03af8db6e129 100644 --- a/src/Components/Components/src/Rendering/SimplifiedStringHashComparer.cs +++ b/src/Components/Components/src/Rendering/SimplifiedStringHashComparer.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Components.Rendering /// internal class SimplifiedStringHashComparer : IEqualityComparer { - public readonly static SimplifiedStringHashComparer Instance = new SimplifiedStringHashComparer(); + public static readonly SimplifiedStringHashComparer Instance = new SimplifiedStringHashComparer(); public bool Equals(string? x, string? y) { diff --git a/src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs b/src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs index 6ae7bbc8bccd..9781eb13144e 100644 --- a/src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs +++ b/src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs @@ -204,7 +204,7 @@ public TestRenderer() : base(new ServiceCollection().BuildServiceProvider(), Nul { } - private Dispatcher _dispatcher = Dispatcher.CreateDefault(); + private readonly Dispatcher _dispatcher = Dispatcher.CreateDefault(); public override Dispatcher Dispatcher => _dispatcher; diff --git a/src/Components/Components/test/RendererTest.cs b/src/Components/Components/test/RendererTest.cs index 85185a710e84..f4604a5eaec4 100644 --- a/src/Components/Components/test/RendererTest.cs +++ b/src/Components/Components/test/RendererTest.cs @@ -4443,7 +4443,7 @@ protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) private class TestComponent : IComponent, IDisposable { private RenderHandle _renderHandle; - private RenderFragment _renderFragment; + private readonly RenderFragment _renderFragment; public TestComponent(RenderFragment renderFragment) { @@ -5211,7 +5211,7 @@ public Task SetParametersAsync(ParameterView parameters) private class TestErrorBoundary : AutoRenderComponent, IErrorBoundary { - private TaskCompletionSource receivedErrorTaskCompletionSource = new(); + private readonly TaskCompletionSource receivedErrorTaskCompletionSource = new(); public Exception ReceivedException { get; private set; } public Task ReceivedErrorTask => receivedErrorTaskCompletionSource.Task; diff --git a/src/Components/Components/test/Routing/RouteTableFactoryTests.cs b/src/Components/Components/test/Routing/RouteTableFactoryTests.cs index 29b1fd1ddd8f..c5475b138499 100644 --- a/src/Components/Components/test/Routing/RouteTableFactoryTests.cs +++ b/src/Components/Components/test/Routing/RouteTableFactoryTests.cs @@ -1013,8 +1013,8 @@ public void SuppliesNullForUnusedHandlerParameters() private class TestRouteTableBuilder { - IList<(string Template, Type Handler)> _routeTemplates = new List<(string, Type)>(); - Type _handler = typeof(object); + readonly IList<(string Template, Type Handler)> _routeTemplates = new List<(string, Type)>(); + readonly Type _handler = typeof(object); public TestRouteTableBuilder AddRoute(string template, Type handler = null) { diff --git a/src/Components/Forms/src/ValidationStateChangedEventArgs.cs b/src/Components/Forms/src/ValidationStateChangedEventArgs.cs index fd8dbb8d69c8..51fe8a2aca92 100644 --- a/src/Components/Forms/src/ValidationStateChangedEventArgs.cs +++ b/src/Components/Forms/src/ValidationStateChangedEventArgs.cs @@ -13,7 +13,7 @@ public sealed class ValidationStateChangedEventArgs : EventArgs /// /// Gets a shared empty instance of . /// - public new static readonly ValidationStateChangedEventArgs Empty = new ValidationStateChangedEventArgs(); + public static new readonly ValidationStateChangedEventArgs Empty = new ValidationStateChangedEventArgs(); /// /// Creates a new instance of diff --git a/src/Components/Ignitor/src/NodeSerializer.cs b/src/Components/Ignitor/src/NodeSerializer.cs index c405bdd394fd..bc47d24f6b4e 100644 --- a/src/Components/Ignitor/src/NodeSerializer.cs +++ b/src/Components/Ignitor/src/NodeSerializer.cs @@ -37,7 +37,7 @@ private class Serializer private readonly TextWriter _writer; private int _depth; private bool _atStartOfLine; - private HashSet _visited = new HashSet(); + private readonly HashSet _visited = new HashSet(); public Serializer(TextWriter writer) { diff --git a/src/Components/Server/test/Circuits/RemoteRendererTest.cs b/src/Components/Server/test/Circuits/RemoteRendererTest.cs index 063685d80f17..f6e0d06da88f 100644 --- a/src/Components/Server/test/Circuits/RemoteRendererTest.cs +++ b/src/Components/Server/test/Circuits/RemoteRendererTest.cs @@ -452,7 +452,7 @@ public async Task RenderComponentAsync(ParameterView initialParamete private class TestComponent : IComponent, IHandleAfterRender { private RenderHandle _renderHandle; - private RenderFragment _renderFragment = (builder) => + private readonly RenderFragment _renderFragment = (builder) => { builder.OpenElement(0, "my element"); builder.AddContent(1, "some text"); diff --git a/src/Components/Server/test/Circuits/RenderBatchWriterTest.cs b/src/Components/Server/test/Circuits/RenderBatchWriterTest.cs index 7fdf9231676e..dff7ab271852 100644 --- a/src/Components/Server/test/Circuits/RenderBatchWriterTest.cs +++ b/src/Components/Server/test/Circuits/RenderBatchWriterTest.cs @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Components.Server { public class RenderBatchWriterTest { - static object NullStringMarker = new object(); + static readonly object NullStringMarker = new object(); [Fact] public void CanSerializeEmptyRenderBatch() diff --git a/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs b/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs index fb8bac72bbf2..34acb704e39b 100644 --- a/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs +++ b/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Components.Forms /// public static class EditContextFieldClassExtensions { - private readonly static object FieldCssClassProviderKey = new object(); + private static readonly object FieldCssClassProviderKey = new object(); /// /// Gets a string that indicates the status of the specified field as a CSS class. This will include diff --git a/src/Components/Web/src/Forms/FieldCssClassProvider.cs b/src/Components/Web/src/Forms/FieldCssClassProvider.cs index dd56db64aa9f..ea77dbb9ba03 100644 --- a/src/Components/Web/src/Forms/FieldCssClassProvider.cs +++ b/src/Components/Web/src/Forms/FieldCssClassProvider.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Components.Forms /// public class FieldCssClassProvider { - internal readonly static FieldCssClassProvider Instance = new FieldCssClassProvider(); + internal static readonly FieldCssClassProvider Instance = new FieldCssClassProvider(); /// /// Gets a string that indicates the status of the specified field as a CSS class. diff --git a/src/Components/WebAssembly/Server/src/TargetPickerUi.cs b/src/Components/WebAssembly/Server/src/TargetPickerUi.cs index 553b9905f869..de2c036b46fb 100644 --- a/src/Components/WebAssembly/Server/src/TargetPickerUi.cs +++ b/src/Components/WebAssembly/Server/src/TargetPickerUi.cs @@ -27,8 +27,8 @@ public class TargetPickerUi DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; - private string _browserHost; - private string _debugProxyUrl; + private readonly string _browserHost; + private readonly string _debugProxyUrl; /// /// Initialize a new instance of . diff --git a/src/Components/WebAssembly/WebAssembly.Authentication/test/RemoteAuthenticatorCoreTests.cs b/src/Components/WebAssembly/WebAssembly.Authentication/test/RemoteAuthenticatorCoreTests.cs index 43a16047122d..578f18b2e210 100644 --- a/src/Components/WebAssembly/WebAssembly.Authentication/test/RemoteAuthenticatorCoreTests.cs +++ b/src/Components/WebAssembly/WebAssembly.Authentication/test/RemoteAuthenticatorCoreTests.cs @@ -752,7 +752,7 @@ public TestRemoteAuthenticationService( public Func, Task>> CompleteSignOutCallback { get; set; } public Func> GetAuthenticatedUserCallback { get; set; } - public async override Task GetAuthenticationStateAsync() => new AuthenticationState(await GetAuthenticatedUserCallback()); + public override async Task GetAuthenticationStateAsync() => new AuthenticationState(await GetAuthenticatedUserCallback()); public override Task> CompleteSignInAsync(RemoteAuthenticationContext context) => CompleteSignInCallback(context); diff --git a/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs b/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs index 6fe29c04872a..2c2c0f527428 100644 --- a/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs +++ b/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.HotReload public static class WebAssemblyHotReload { private static HotReloadAgent? _hotReloadAgent; - private static UpdateDelta[] _updateDeltas = new[] + private static readonly UpdateDelta[] _updateDeltas = new[] { new UpdateDelta(), }; diff --git a/src/Components/WebAssembly/testassets/HostedInAspNet.Server/BootResourceRequestLog.cs b/src/Components/WebAssembly/testassets/HostedInAspNet.Server/BootResourceRequestLog.cs index fea623aa4224..b0c8181c4319 100644 --- a/src/Components/WebAssembly/testassets/HostedInAspNet.Server/BootResourceRequestLog.cs +++ b/src/Components/WebAssembly/testassets/HostedInAspNet.Server/BootResourceRequestLog.cs @@ -9,7 +9,7 @@ namespace HostedInAspNet.Server { public class BootResourceRequestLog { - private ConcurrentBag _requestPaths = new ConcurrentBag(); + private readonly ConcurrentBag _requestPaths = new ConcurrentBag(); public IReadOnlyCollection RequestPaths => _requestPaths; diff --git a/src/Components/WebAssembly/testassets/Wasm.Authentication.Client/PreferencesUserFactory.cs b/src/Components/WebAssembly/testassets/Wasm.Authentication.Client/PreferencesUserFactory.cs index f9971712fc2f..9fcf56a1ee8c 100644 --- a/src/Components/WebAssembly/testassets/Wasm.Authentication.Client/PreferencesUserFactory.cs +++ b/src/Components/WebAssembly/testassets/Wasm.Authentication.Client/PreferencesUserFactory.cs @@ -21,7 +21,7 @@ public PreferencesUserFactory(NavigationManager navigationManager, IAccessTokenP _httpClient = new HttpClient { BaseAddress = new Uri(navigationManager.BaseUri) }; } - public async override ValueTask CreateUserAsync( + public override async ValueTask CreateUserAsync( OidcAccount account, RemoteAuthenticationUserOptions options) { diff --git a/src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs b/src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs index 6a4bf4814d9a..81474838ae45 100644 --- a/src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs +++ b/src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs @@ -19,11 +19,11 @@ internal class PhotinoWebViewManager : WebViewManager // because webview2 won't let you do top-level navigation to such a URL. // On Linux/Mac, we must use a custom scheme, because their webviews // don't have a way to intercept http:// scheme requests. - internal readonly static string BlazorAppScheme = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + internal static readonly string BlazorAppScheme = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "http" : "app"; - internal readonly static string AppBaseUri + internal static readonly string AppBaseUri = $"{BlazorAppScheme}://0.0.0.0/"; public PhotinoWebViewManager(PhotinoWindow window, IServiceProvider provider, Dispatcher dispatcher, Uri appBaseUri, IFileProvider fileProvider, string hostPageRelativePath) diff --git a/src/Components/WebView/WebView/src/StaticContentProvider.cs b/src/Components/WebView/WebView/src/StaticContentProvider.cs index d1df73709379..f3c729c93067 100644 --- a/src/Components/WebView/WebView/src/StaticContentProvider.cs +++ b/src/Components/WebView/WebView/src/StaticContentProvider.cs @@ -15,7 +15,7 @@ internal class StaticContentProvider private readonly Uri _appBaseUri; private readonly string _hostPageRelativePath; private static readonly FileExtensionContentTypeProvider ContentTypeProvider = new(); - private static ManifestEmbeddedFileProvider _manifestProvider = + private static readonly ManifestEmbeddedFileProvider _manifestProvider = new ManifestEmbeddedFileProvider(typeof(StaticContentProvider).Assembly); public StaticContentProvider(IFileProvider fileProvider, Uri appBaseUri, string hostPageRelativePath) diff --git a/src/Components/WebView/WebView/test/Infrastructure/TestWebViewManager.cs b/src/Components/WebView/WebView/test/Infrastructure/TestWebViewManager.cs index e88a24f7f015..71fafbf0118f 100644 --- a/src/Components/WebView/WebView/test/Infrastructure/TestWebViewManager.cs +++ b/src/Components/WebView/WebView/test/Infrastructure/TestWebViewManager.cs @@ -9,8 +9,8 @@ namespace Microsoft.AspNetCore.Components.WebView { public class TestWebViewManager : WebViewManager { - private static Uri AppBaseUri = new Uri("app://testhost/"); - private List _sentIpcMessages = new(); + private static readonly Uri AppBaseUri = new Uri("app://testhost/"); + private readonly List _sentIpcMessages = new(); public TestWebViewManager(IServiceProvider provider, IFileProvider fileProvider) : base(provider, Dispatcher.CreateDefault(), AppBaseUri, fileProvider, hostPageRelativePath: "index.html") diff --git a/src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs b/src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs index 666e1a0ea7fc..0752937771df 100644 --- a/src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs +++ b/src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs @@ -14,9 +14,9 @@ namespace Wasm.Performance.Driver class Selenium { const int SeleniumPort = 4444; - static bool RunHeadlessBrowser = true; + const bool RunHeadlessBrowser = true; - static bool PoolForBrowserLogs = true; + const bool PoolForBrowserLogs = true; private static async ValueTask WaitForServerAsync(int port, CancellationToken cancellationToken) { diff --git a/src/Components/test/E2ETest/ServerExecutionTests/IgnitorTest.cs b/src/Components/test/E2ETest/ServerExecutionTests/IgnitorTest.cs index af7d29cff743..bb1a943fbb64 100644 --- a/src/Components/test/E2ETest/ServerExecutionTests/IgnitorTest.cs +++ b/src/Components/test/E2ETest/ServerExecutionTests/IgnitorTest.cs @@ -83,7 +83,7 @@ protected virtual Task InitializeAsync() return Task.CompletedTask; } - protected async virtual Task DisposeAsync() + protected virtual async Task DisposeAsync() { if (TestSink != null) { diff --git a/src/Components/test/E2ETest/ServerExecutionTests/InteropReliabilityTests.cs b/src/Components/test/E2ETest/ServerExecutionTests/InteropReliabilityTests.cs index 984998a7886d..3e68c7ee3fe9 100644 --- a/src/Components/test/E2ETest/ServerExecutionTests/InteropReliabilityTests.cs +++ b/src/Components/test/E2ETest/ServerExecutionTests/InteropReliabilityTests.cs @@ -27,7 +27,7 @@ public InteropReliabilityTests(BasicTestAppServerSiteFixture serv { } - protected async override Task InitializeAsync() + protected override async Task InitializeAsync() { var rootUri = ServerFixture.RootUri; await ConnectAutomaticallyAndWait(new Uri(rootUri, "/subdir")); diff --git a/src/Components/test/E2ETestMigration/Infrastructure/PlaywrightTestBase.cs b/src/Components/test/E2ETestMigration/Infrastructure/PlaywrightTestBase.cs index 967c720f4485..106d6b5c9941 100644 --- a/src/Components/test/E2ETestMigration/Infrastructure/PlaywrightTestBase.cs +++ b/src/Components/test/E2ETestMigration/Infrastructure/PlaywrightTestBase.cs @@ -25,7 +25,7 @@ public class PlaywrightTestBase : LoggedTest, IAsyncLifetime public PlaywrightTestBase(ITestOutputHelper output) : base(output) { } - protected async override Task InitializeCoreAsync(TestContext context) + protected override async Task InitializeCoreAsync(TestContext context) { BrowserManager = await BrowserManager.CreateAsync(CreateConfiguration(), LoggerFactory); BrowserContextInfo = new ContextInformation(LoggerFactory); diff --git a/src/Components/test/testassets/BasicTestApp/PrependMessageLoggerProvider.cs b/src/Components/test/testassets/BasicTestApp/PrependMessageLoggerProvider.cs index 35d4fd72bb98..d339cde7915e 100644 --- a/src/Components/test/testassets/BasicTestApp/PrependMessageLoggerProvider.cs +++ b/src/Components/test/testassets/BasicTestApp/PrependMessageLoggerProvider.cs @@ -13,8 +13,8 @@ namespace BasicTestApp internal class PrependMessageLoggerProvider : ILoggerProvider { ILogger _logger; - string _message; - ILogger _defaultLogger; + readonly string _message; + readonly ILogger _defaultLogger; private bool _disposed = false; public PrependMessageLoggerProvider(string message, IJSRuntime runtime) diff --git a/src/Components/test/testassets/TestServer/Controllers/UserController.cs b/src/Components/test/testassets/TestServer/Controllers/UserController.cs index d6e289c7279a..3d4f81d90f3f 100644 --- a/src/Components/test/testassets/TestServer/Controllers/UserController.cs +++ b/src/Components/test/testassets/TestServer/Controllers/UserController.cs @@ -13,7 +13,7 @@ public class UserController : Controller // to the client. It's up to the developer to choose what kind of authentication state // data is needed on the client so it can display suitable options in the UI. // In this class, we inform the client only about certain roles and certain other claims. - static string[] ExposedRoles = new[] { "IrrelevantRole", "TestRole" }; + static readonly string[] ExposedRoles = new[] { "IrrelevantRole", "TestRole" }; // GET api/user [HttpGet] diff --git a/src/Components/test/testassets/TestServer/ResourceRequestLog.cs b/src/Components/test/testassets/TestServer/ResourceRequestLog.cs index 0af9e34afae9..c411cbb39264 100644 --- a/src/Components/test/testassets/TestServer/ResourceRequestLog.cs +++ b/src/Components/test/testassets/TestServer/ResourceRequestLog.cs @@ -8,7 +8,7 @@ namespace TestServer { public class ResourceRequestLog { - private List _requestPaths = new List(); + private readonly List _requestPaths = new List(); public IReadOnlyCollection RequestPaths => _requestPaths; diff --git a/src/DataProtection/Cryptography.Internal/src/Cng/BCryptUtil.cs b/src/DataProtection/Cryptography.Internal/src/Cng/BCryptUtil.cs index 86c86c64a8ba..de4b6c4e17fe 100644 --- a/src/DataProtection/Cryptography.Internal/src/Cng/BCryptUtil.cs +++ b/src/DataProtection/Cryptography.Internal/src/Cng/BCryptUtil.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Cryptography.Cng /// /// Wraps utility BCRYPT APIs that don't work directly with handles. /// - internal unsafe static class BCryptUtil + internal static unsafe class BCryptUtil { /// /// Fills a buffer with cryptographically secure random data. diff --git a/src/DataProtection/Cryptography.Internal/src/CryptoUtil.cs b/src/DataProtection/Cryptography.Internal/src/CryptoUtil.cs index b51699912e0d..2e2f07d61a63 100644 --- a/src/DataProtection/Cryptography.Internal/src/CryptoUtil.cs +++ b/src/DataProtection/Cryptography.Internal/src/CryptoUtil.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography { - internal unsafe static class CryptoUtil + internal static unsafe class CryptoUtil { // This isn't a typical Debug.Assert; the check is always performed, even in retail builds. [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs index 95efc7026541..2377754cc069 100644 --- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs +++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles /// /// Represents a handle to a BCrypt algorithm provider from which keys and hashes can be created. /// - internal unsafe sealed class BCryptAlgorithmHandle : BCryptHandle + internal sealed unsafe class BCryptAlgorithmHandle : BCryptHandle { // Called by P/Invoke when returning SafeHandles private BCryptAlgorithmHandle() { } diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs index 66b2c1dbd474..2f04fe9f443a 100644 --- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs +++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs @@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles { - internal unsafe abstract class BCryptHandle : SafeHandleZeroOrMinusOneIsInvalid + internal abstract unsafe class BCryptHandle : SafeHandleZeroOrMinusOneIsInvalid { protected BCryptHandle() : base(ownsHandle: true) diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs index f997f1576db4..2e5c76dafc2b 100644 --- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs +++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs @@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles { - internal unsafe sealed class BCryptHashHandle : BCryptHandle + internal sealed unsafe class BCryptHashHandle : BCryptHandle { private BCryptAlgorithmHandle? _algProviderHandle; diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/NCryptDescriptorHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/NCryptDescriptorHandle.cs index 3a181cf06b99..bd6bc0bc9f6e 100644 --- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/NCryptDescriptorHandle.cs +++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/NCryptDescriptorHandle.cs @@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles { - internal unsafe sealed class NCryptDescriptorHandle : SafeHandleZeroOrMinusOneIsInvalid + internal sealed unsafe class NCryptDescriptorHandle : SafeHandleZeroOrMinusOneIsInvalid { private NCryptDescriptorHandle() : base(ownsHandle: true) diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs index 8a38bb4e0eda..5f721e92b2bb 100644 --- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs +++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles /// /// Represents a handle to a Windows module (DLL). /// - internal unsafe sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid + internal sealed unsafe class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid { // Called by P/Invoke when returning SafeHandles private SafeLibraryHandle() diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/SecureLocalAllocHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/SecureLocalAllocHandle.cs index 3e1c7a79bab5..8baa92113bae 100644 --- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/SecureLocalAllocHandle.cs +++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/SecureLocalAllocHandle.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles /// Represents a handle returned by LocalAlloc. /// The memory will be zeroed out before it's freed. /// - internal unsafe sealed class SecureLocalAllocHandle : LocalAllocHandle + internal sealed unsafe class SecureLocalAllocHandle : LocalAllocHandle { private readonly IntPtr _cb; diff --git a/src/DataProtection/Cryptography.Internal/src/UnsafeBufferUtil.cs b/src/DataProtection/Cryptography.Internal/src/UnsafeBufferUtil.cs index c0f5a7959d92..e41c558fd6e5 100644 --- a/src/DataProtection/Cryptography.Internal/src/UnsafeBufferUtil.cs +++ b/src/DataProtection/Cryptography.Internal/src/UnsafeBufferUtil.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Cryptography { - internal unsafe static class UnsafeBufferUtil + internal static unsafe class UnsafeBufferUtil { [MethodImpl(MethodImplOptions.AggressiveInlining)] #if NETSTANDARD2_0 diff --git a/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs b/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs index 840ca22daeac..93b3884d0afa 100644 --- a/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs +++ b/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Cryptography { [SuppressUnmanagedCodeSecurity] - internal unsafe static class UnsafeNativeMethods + internal static unsafe class UnsafeNativeMethods { private const string BCRYPT_LIB = "bcrypt.dll"; private static readonly Lazy _lazyBCryptLibHandle = GetLazyLibraryHandle(BCRYPT_LIB); diff --git a/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs b/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs index 4c359b80f40c..492d4024e0e4 100644 --- a/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs +++ b/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Cryptography.KeyDerivation.PBKDF2 /// /// A PBKDF2 provider which utilizes the Win7 API BCryptDeriveKeyPBKDF2. /// - internal unsafe sealed class Win7Pbkdf2Provider : IPbkdf2Provider + internal sealed unsafe class Win7Pbkdf2Provider : IPbkdf2Provider { public byte[] DeriveKey(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested) { diff --git a/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win8Pbkdf2Provider.cs b/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win8Pbkdf2Provider.cs index 296e85b7dd48..e03dfa359adb 100644 --- a/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win8Pbkdf2Provider.cs +++ b/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win8Pbkdf2Provider.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.KeyDerivation.PBKDF2 /// /// A PBKDF2 provider which utilizes the Win8 API BCryptKeyDerivation. /// - internal unsafe sealed class Win8Pbkdf2Provider : IPbkdf2Provider + internal sealed unsafe class Win8Pbkdf2Provider : IPbkdf2Provider { public byte[] DeriveKey(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested) { diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/SecretExtensions.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/SecretExtensions.cs index 4876247762d2..d08e2918ec0e 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/SecretExtensions.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/SecretExtensions.cs @@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel { - internal unsafe static class SecretExtensions + internal static unsafe class SecretExtensions { /// /// Converts an to an <masterKey> element which is marked diff --git a/src/DataProtection/DataProtection/src/BitHelpers.cs b/src/DataProtection/DataProtection/src/BitHelpers.cs index 65e74150087b..092807d8d86a 100644 --- a/src/DataProtection/DataProtection/src/BitHelpers.cs +++ b/src/DataProtection/DataProtection/src/BitHelpers.cs @@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.DataProtection { - internal unsafe static class BitHelpers + internal static unsafe class BitHelpers { /// /// Writes an unsigned 32-bit value to a memory address, big-endian. diff --git a/src/DataProtection/DataProtection/src/Cng/BCryptGenRandomImpl.cs b/src/DataProtection/DataProtection/src/Cng/BCryptGenRandomImpl.cs index 5bdceabb6dd9..0852218e21a1 100644 --- a/src/DataProtection/DataProtection/src/Cng/BCryptGenRandomImpl.cs +++ b/src/DataProtection/DataProtection/src/Cng/BCryptGenRandomImpl.cs @@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng { - internal unsafe sealed class BCryptGenRandomImpl : IBCryptGenRandom + internal sealed unsafe class BCryptGenRandomImpl : IBCryptGenRandom { public static readonly BCryptGenRandomImpl Instance = new BCryptGenRandomImpl(); diff --git a/src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs b/src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs index 72166edf0b42..c102afd884d0 100644 --- a/src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs +++ b/src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng // An encryptor which does Encrypt(CBC) + HMAC using the Windows CNG (BCrypt*) APIs. // The payloads produced by this encryptor should be compatible with the payloads // produced by the managed Encrypt(CBC) + HMAC encryptor. - internal unsafe sealed class CbcAuthenticatedEncryptor : CngAuthenticatedEncryptorBase + internal sealed unsafe class CbcAuthenticatedEncryptor : CngAuthenticatedEncryptorBase { // Even when IVs are chosen randomly, CBC is susceptible to IV collisions within a single // key. For a 64-bit block cipher (like 3DES), we'd expect a collision after 2^32 block diff --git a/src/DataProtection/DataProtection/src/Cng/CngGcmAuthenticatedEncryptor.cs b/src/DataProtection/DataProtection/src/Cng/CngGcmAuthenticatedEncryptor.cs index 1566fabba4f4..af510ac00b64 100644 --- a/src/DataProtection/DataProtection/src/Cng/CngGcmAuthenticatedEncryptor.cs +++ b/src/DataProtection/DataProtection/src/Cng/CngGcmAuthenticatedEncryptor.cs @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng // going to the IV. This means that we'll only hit the 2^-32 probability limit after 2^96 encryption // operations, which will realistically never happen. (At the absurd rate of one encryption operation // per nanosecond, it would still take 180 times the age of the universe to hit 2^96 operations.) - internal unsafe sealed class CngGcmAuthenticatedEncryptor : CngAuthenticatedEncryptorBase + internal sealed unsafe class CngGcmAuthenticatedEncryptor : CngAuthenticatedEncryptorBase { // Having a key modifier ensures with overwhelming probability that no two encryption operations // will ever derive the same (encryption subkey, MAC subkey) pair. This limits an attacker's diff --git a/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs b/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs index 2fa693851fe6..b59f812186c9 100644 --- a/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs +++ b/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng { - internal unsafe static class DpapiSecretSerializerHelper + internal static unsafe class DpapiSecretSerializerHelper { // from ncrypt.h private const uint NCRYPT_SILENT_FLAG = 0x00000040; diff --git a/src/DataProtection/DataProtection/src/Cng/Internal/CngAuthenticatedEncryptorBase.cs b/src/DataProtection/DataProtection/src/Cng/Internal/CngAuthenticatedEncryptorBase.cs index a6f9bef9eb25..9093b92aa25d 100644 --- a/src/DataProtection/DataProtection/src/Cng/Internal/CngAuthenticatedEncryptorBase.cs +++ b/src/DataProtection/DataProtection/src/Cng/Internal/CngAuthenticatedEncryptorBase.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng.Internal /// /// Base class used for all CNG-related authentication encryption operations. /// - internal unsafe abstract class CngAuthenticatedEncryptorBase : IOptimizedAuthenticatedEncryptor, IDisposable + internal abstract unsafe class CngAuthenticatedEncryptorBase : IOptimizedAuthenticatedEncryptor, IDisposable { public byte[] Decrypt(ArraySegment ciphertext, ArraySegment additionalAuthenticatedData) { diff --git a/src/DataProtection/DataProtection/src/Internal/ContainerUtils.cs b/src/DataProtection/DataProtection/src/Internal/ContainerUtils.cs index 6b366686a7a5..2b263bfef36e 100644 --- a/src/DataProtection/DataProtection/src/Internal/ContainerUtils.cs +++ b/src/DataProtection/DataProtection/src/Internal/ContainerUtils.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.DataProtection.Internal { internal static class ContainerUtils { - private static Lazy _isContainer = new Lazy(IsProcessRunningInContainer); + private static readonly Lazy _isContainer = new Lazy(IsProcessRunningInContainer); private const string RunningInContainerVariableName = "DOTNET_RUNNING_IN_CONTAINER"; private const string DeprecatedRunningInContainerVariableName = "DOTNET_RUNNING_IN_CONTAINERS"; diff --git a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs index f7f785cc3bce..76c66e57f526 100644 --- a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs +++ b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs @@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement { - internal unsafe sealed class KeyRingBasedDataProtectionProvider : IDataProtectionProvider + internal sealed unsafe class KeyRingBasedDataProtectionProvider : IDataProtectionProvider { private readonly IKeyRingProvider _keyRingProvider; private readonly ILogger _logger; diff --git a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs index a5ce5e593a4a..2a9d64a82ab8 100644 --- a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs +++ b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement { - internal unsafe sealed class KeyRingBasedDataProtector : IDataProtector, IPersistedDataProtector + internal sealed unsafe class KeyRingBasedDataProtector : IDataProtector, IPersistedDataProtector { // This magic header identifies a v0 protected data blob. It's the high 28 bits of the SHA1 hash of // "Microsoft.AspNet.DataProtection.KeyManagement.KeyRingBasedDataProtector" [US-ASCII], big-endian. diff --git a/src/DataProtection/DataProtection/src/LoggingExtensions.cs b/src/DataProtection/DataProtection/src/LoggingExtensions.cs index 909d05008dc3..15866671c11b 100644 --- a/src/DataProtection/DataProtection/src/LoggingExtensions.cs +++ b/src/DataProtection/DataProtection/src/LoggingExtensions.cs @@ -17,137 +17,137 @@ namespace Microsoft.Extensions.Logging /// internal static class LoggingExtensions { - private static Action _usingFallbackKeyWithExpirationAsDefaultKey; + private static readonly Action _usingFallbackKeyWithExpirationAsDefaultKey; - private static Action _usingKeyAsDefaultKey; + private static readonly Action _usingKeyAsDefaultKey; - private static Action _openingCNGAlgorithmFromProviderWithHMAC; + private static readonly Action _openingCNGAlgorithmFromProviderWithHMAC; - private static Action _openingCNGAlgorithmFromProviderWithChainingModeCBC; + private static readonly Action _openingCNGAlgorithmFromProviderWithChainingModeCBC; - private static Action _performingUnprotectOperationToKeyWithPurposes; + private static readonly Action _performingUnprotectOperationToKeyWithPurposes; - private static Action _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed; + private static readonly Action _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed; - private static Action _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless; + private static readonly Action _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless; - private static Action _keyWasRevokedUnprotectOperationCannotProceed; + private static readonly Action _keyWasRevokedUnprotectOperationCannotProceed; - private static Action _openingCNGAlgorithmFromProviderWithChainingModeGCM; + private static readonly Action _openingCNGAlgorithmFromProviderWithChainingModeGCM; - private static Action _usingManagedKeyedHashAlgorithm; + private static readonly Action _usingManagedKeyedHashAlgorithm; - private static Action _usingManagedSymmetricAlgorithm; + private static readonly Action _usingManagedSymmetricAlgorithm; - private static Action _keyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed; + private static readonly Action _keyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed; - private static Action _consideringKeyWithExpirationDateAsDefaultKey; + private static readonly Action _consideringKeyWithExpirationDateAsDefaultKey; - private static Action _keyIsNoLongerUnderConsiderationAsDefault; + private static readonly Action _keyIsNoLongerUnderConsiderationAsDefault; - private static Action _unknownElementWithNameFoundInKeyringSkipping; + private static readonly Action _unknownElementWithNameFoundInKeyringSkipping; - private static Action _markedKeyAsRevokedInTheKeyring; + private static readonly Action _markedKeyAsRevokedInTheKeyring; - private static Action _triedToProcessRevocationOfKeyButNoSuchKeyWasFound; + private static readonly Action _triedToProcessRevocationOfKeyButNoSuchKeyWasFound; - private static Action _foundKey; + private static readonly Action _foundKey; - private static Action _foundRevocationOfAllKeysCreatedPriorTo; + private static readonly Action _foundRevocationOfAllKeysCreatedPriorTo; - private static Action _foundRevocationOfKey; + private static readonly Action _foundRevocationOfKey; - private static Action _exceptionWhileProcessingRevocationElement; + private static readonly Action _exceptionWhileProcessingRevocationElement; - private static Action _revokingAllKeysAsOfForReason; + private static readonly Action _revokingAllKeysAsOfForReason; - private static Action _keyCacheExpirationTokenTriggeredByOperation; + private static readonly Action _keyCacheExpirationTokenTriggeredByOperation; - private static Action _anExceptionOccurredWhileProcessingTheKeyElement; + private static readonly Action _anExceptionOccurredWhileProcessingTheKeyElement; - private static Action _anExceptionOccurredWhileProcessingTheKeyElementDebug; + private static readonly Action _anExceptionOccurredWhileProcessingTheKeyElementDebug; - private static Action _encryptingToWindowsDPAPIForCurrentUserAccount; + private static readonly Action _encryptingToWindowsDPAPIForCurrentUserAccount; - private static Action _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule; + private static readonly Action _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule; - private static Action _anErrorOccurredWhileEncryptingToX509CertificateWithThumbprint; + private static readonly Action _anErrorOccurredWhileEncryptingToX509CertificateWithThumbprint; - private static Action _encryptingToX509CertificateWithThumbprint; + private static readonly Action _encryptingToX509CertificateWithThumbprint; - private static Action _exceptionOccurredWhileTryingToResolveCertificateWithThumbprint; + private static readonly Action _exceptionOccurredWhileTryingToResolveCertificateWithThumbprint; - private static Action _performingProtectOperationToKeyWithPurposes; + private static readonly Action _performingProtectOperationToKeyWithPurposes; - private static Action _creatingKey; + private static readonly Action _creatingKey; - private static Action _descriptorDeserializerTypeForKeyIs; + private static readonly Action _descriptorDeserializerTypeForKeyIs; - private static Action _keyEscrowSinkFoundWritingKeyToEscrow; + private static readonly Action _keyEscrowSinkFoundWritingKeyToEscrow; - private static Action _noKeyEscrowSinkFoundNotWritingKeyToEscrow; + private static readonly Action _noKeyEscrowSinkFoundNotWritingKeyToEscrow; - private static Action _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm; + private static readonly Action _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm; - private static Action _revokingKeyForReason; + private static readonly Action _revokingKeyForReason; - private static Action _readingDataFromFile; + private static readonly Action _readingDataFromFile; - private static Action _nameIsNotSafeFileName; + private static readonly Action _nameIsNotSafeFileName; - private static Action _writingDataToFile; + private static readonly Action _writingDataToFile; - private static Action? _readingDataFromRegistryKeyValue; + private static readonly Action? _readingDataFromRegistryKeyValue; - private static Action _nameIsNotSafeRegistryValueName; + private static readonly Action _nameIsNotSafeRegistryValueName; - private static Action _decryptingSecretElementUsingWindowsDPAPING; + private static readonly Action _decryptingSecretElementUsingWindowsDPAPING; - private static Action _exceptionOccurredTryingToDecryptElement; + private static readonly Action _exceptionOccurredTryingToDecryptElement; - private static Action _encryptingUsingNullEncryptor; + private static readonly Action _encryptingUsingNullEncryptor; - private static Action _usingEphemeralDataProtectionProvider; + private static readonly Action _usingEphemeralDataProtectionProvider; - private static Action _existingCachedKeyRingIsExpiredRefreshing; + private static readonly Action _existingCachedKeyRingIsExpiredRefreshing; - private static Action _errorOccurredWhileRefreshingKeyRing; + private static readonly Action _errorOccurredWhileRefreshingKeyRing; - private static Action _errorOccurredWhileReadingKeyRing; + private static readonly Action _errorOccurredWhileReadingKeyRing; - private static Action _keyRingDoesNotContainValidDefaultKey; + private static readonly Action _keyRingDoesNotContainValidDefaultKey; - private static Action _usingInmemoryRepository; + private static readonly Action _usingInmemoryRepository; - private static Action _decryptingSecretElementUsingWindowsDPAPI; + private static readonly Action _decryptingSecretElementUsingWindowsDPAPI; - private static Action _defaultKeyExpirationImminentAndRepository; + private static readonly Action _defaultKeyExpirationImminentAndRepository; - private static Action _repositoryContainsNoViableDefaultKey; + private static readonly Action _repositoryContainsNoViableDefaultKey; - private static Action _errorOccurredWhileEncryptingToWindowsDPAPI; + private static readonly Action _errorOccurredWhileEncryptingToWindowsDPAPI; - private static Action _encryptingToWindowsDPAPIForLocalMachineAccount; + private static readonly Action _encryptingToWindowsDPAPIForLocalMachineAccount; - private static Action _errorOccurredWhileEncryptingToWindowsDPAPING; + private static readonly Action _errorOccurredWhileEncryptingToWindowsDPAPING; - private static Action _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing; + private static readonly Action _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing; - private static Action _keyRingWasLoadedOnStartup; + private static readonly Action _keyRingWasLoadedOnStartup; - private static Action _keyRingFailedToLoadOnStartup; + private static readonly Action _keyRingFailedToLoadOnStartup; - private static Action _usingEphemeralKeyRepository; + private static readonly Action _usingEphemeralKeyRepository; - private static Action _usingRegistryAsKeyRepositoryWithDPAPI; + private static readonly Action _usingRegistryAsKeyRepositoryWithDPAPI; - private static Action _usingProfileAsKeyRepository; + private static readonly Action _usingProfileAsKeyRepository; - private static Action _usingProfileAsKeyRepositoryWithDPAPI; + private static readonly Action _usingProfileAsKeyRepositoryWithDPAPI; - private static Action _usingAzureAsKeyRepository; + private static readonly Action _usingAzureAsKeyRepository; - private static Action _usingEphemeralFileSystemLocationInContainer; + private static readonly Action _usingEphemeralFileSystemLocationInContainer; static LoggingExtensions() { diff --git a/src/DataProtection/DataProtection/src/Managed/AesGcmAuthenticatedEncryptor.cs b/src/DataProtection/DataProtection/src/Managed/AesGcmAuthenticatedEncryptor.cs index d883dfeaaaed..b4a9a92e94b0 100644 --- a/src/DataProtection/DataProtection/src/Managed/AesGcmAuthenticatedEncryptor.cs +++ b/src/DataProtection/DataProtection/src/Managed/AesGcmAuthenticatedEncryptor.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.DataProtection.Managed { // An encryptor that uses AesGcm to do encryption - internal unsafe sealed class AesGcmAuthenticatedEncryptor : IOptimizedAuthenticatedEncryptor, IDisposable + internal sealed unsafe class AesGcmAuthenticatedEncryptor : IOptimizedAuthenticatedEncryptor, IDisposable { // Having a key modifier ensures with overwhelming probability that no two encryption operations // will ever derive the same (encryption subkey, MAC subkey) pair. This limits an attacker's diff --git a/src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs b/src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs index c00ff06fcaf6..02d437940cda 100644 --- a/src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs +++ b/src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.DataProtection.Managed // An encryptor which does Encrypt(CBC) + HMAC using SymmetricAlgorithm and HashAlgorithm. // The payloads produced by this encryptor should be compatible with the payloads // produced by the CNG-based Encrypt(CBC) + HMAC authenticated encryptor. - internal unsafe sealed class ManagedAuthenticatedEncryptor : IAuthenticatedEncryptor, IDisposable + internal sealed unsafe class ManagedAuthenticatedEncryptor : IAuthenticatedEncryptor, IDisposable { // Even when IVs are chosen randomly, CBC is susceptible to IV collisions within a single // key. For a 64-bit block cipher (like 3DES), we'd expect a collision after 2^32 block diff --git a/src/DataProtection/DataProtection/src/Managed/ManagedGenRandomImpl.cs b/src/DataProtection/DataProtection/src/Managed/ManagedGenRandomImpl.cs index c94c2f21f51a..34712759becc 100644 --- a/src/DataProtection/DataProtection/src/Managed/ManagedGenRandomImpl.cs +++ b/src/DataProtection/DataProtection/src/Managed/ManagedGenRandomImpl.cs @@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.DataProtection.Managed { - internal unsafe sealed class ManagedGenRandomImpl : IManagedGenRandom + internal sealed unsafe class ManagedGenRandomImpl : IManagedGenRandom { #if NETSTANDARD2_0 || NET461 private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create(); diff --git a/src/DataProtection/DataProtection/src/MemoryProtection.cs b/src/DataProtection/DataProtection/src/MemoryProtection.cs index be87e3cde512..cb3f08853681 100644 --- a/src/DataProtection/DataProtection/src/MemoryProtection.cs +++ b/src/DataProtection/DataProtection/src/MemoryProtection.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.DataProtection /// /// Wrappers around CryptProtectMemory / CryptUnprotectMemory. /// - internal unsafe static class MemoryProtection + internal static unsafe class MemoryProtection { // from dpapi.h private const uint CRYPTPROTECTMEMORY_SAME_PROCESS = 0x00; diff --git a/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs b/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs index 900ff8e658cb..d4fd290116ea 100644 --- a/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs +++ b/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs @@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.DataProtection.SP800_108 { - internal unsafe static class SP800_108_CTR_HMACSHA512Extensions + internal static unsafe class SP800_108_CTR_HMACSHA512Extensions { public static void DeriveKeyWithContextHeader(this ISP800_108_CTR_HMACSHA512Provider provider, byte* pbLabel, uint cbLabel, byte[] contextHeader, byte* pbContext, uint cbContext, byte* pbDerivedKey, uint cbDerivedKey) { diff --git a/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Util.cs b/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Util.cs index c28af6f0a335..41205af1c4b4 100644 --- a/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Util.cs +++ b/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Util.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.DataProtection.SP800_108 /// /// More info at http://csrc.nist.gov/publications/nistpubs/800-108/sp800-108.pdf, Sec. 5.1. /// - internal unsafe static class SP800_108_CTR_HMACSHA512Util + internal static unsafe class SP800_108_CTR_HMACSHA512Util { // Creates a provider with an empty key. public static ISP800_108_CTR_HMACSHA512Provider CreateEmptyProvider() diff --git a/src/DataProtection/DataProtection/src/SP800_108/Win7SP800_108_CTR_HMACSHA512Provider.cs b/src/DataProtection/DataProtection/src/SP800_108/Win7SP800_108_CTR_HMACSHA512Provider.cs index a2143ff8720d..3cbf45cbd9f8 100644 --- a/src/DataProtection/DataProtection/src/SP800_108/Win7SP800_108_CTR_HMACSHA512Provider.cs +++ b/src/DataProtection/DataProtection/src/SP800_108/Win7SP800_108_CTR_HMACSHA512Provider.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.DataProtection.SP800_108 { - internal unsafe sealed class Win7SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider + internal sealed unsafe class Win7SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider { private readonly BCryptHashHandle _hashHandle; diff --git a/src/DataProtection/DataProtection/src/SP800_108/Win8SP800_108_CTR_HMACSHA512Provider.cs b/src/DataProtection/DataProtection/src/SP800_108/Win8SP800_108_CTR_HMACSHA512Provider.cs index be7fe7c91710..7e4f0babc396 100644 --- a/src/DataProtection/DataProtection/src/SP800_108/Win8SP800_108_CTR_HMACSHA512Provider.cs +++ b/src/DataProtection/DataProtection/src/SP800_108/Win8SP800_108_CTR_HMACSHA512Provider.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.DataProtection.SP800_108 { - internal unsafe sealed class Win8SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider + internal sealed unsafe class Win8SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider { private readonly BCryptKeyHandle _keyHandle; diff --git a/src/DataProtection/DataProtection/src/Secret.cs b/src/DataProtection/DataProtection/src/Secret.cs index ac3f71dc5553..dd5e330ac9cf 100644 --- a/src/DataProtection/DataProtection/src/Secret.cs +++ b/src/DataProtection/DataProtection/src/Secret.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.DataProtection /// /// Represents a secret value stored in memory. /// - public unsafe sealed class Secret : IDisposable, ISecret + public sealed unsafe class Secret : IDisposable, ISecret { // from wincrypt.h private const uint CRYPTPROTECTMEMORY_BLOCK_SIZE = 16; diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs b/src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs index 64dc4747afd9..567efab4e9e5 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption { - internal unsafe static class XmlEncryptionExtensions + internal static unsafe class XmlEncryptionExtensions { public static XElement DecryptElement(this XElement element, IActivator activator) { diff --git a/src/DataProtection/DataProtection/test/Cng/CngAuthenticatedEncryptorBaseTests.cs b/src/DataProtection/DataProtection/test/Cng/CngAuthenticatedEncryptorBaseTests.cs index ef0b405dab9b..da29deb155f9 100644 --- a/src/DataProtection/DataProtection/test/Cng/CngAuthenticatedEncryptorBaseTests.cs +++ b/src/DataProtection/DataProtection/test/Cng/CngAuthenticatedEncryptorBaseTests.cs @@ -94,14 +94,14 @@ public override void Dispose() public abstract byte[] DecryptHook(IntPtr pbCiphertext, uint cbCiphertext, IntPtr pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData); - protected override sealed unsafe byte[] DecryptImpl(byte* pbCiphertext, uint cbCiphertext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData) + protected sealed override unsafe byte[] DecryptImpl(byte* pbCiphertext, uint cbCiphertext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData) { return DecryptHook((IntPtr)pbCiphertext, cbCiphertext, (IntPtr)pbAdditionalAuthenticatedData, cbAdditionalAuthenticatedData); } public abstract byte[] EncryptHook(IntPtr pbPlaintext, uint cbPlaintext, IntPtr pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData, uint cbPreBuffer, uint cbPostBuffer); - protected override sealed unsafe byte[] EncryptImpl(byte* pbPlaintext, uint cbPlaintext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData, uint cbPreBuffer, uint cbPostBuffer) + protected sealed override unsafe byte[] EncryptImpl(byte* pbPlaintext, uint cbPlaintext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData, uint cbPreBuffer, uint cbPostBuffer) { return EncryptHook((IntPtr)pbPlaintext, cbPlaintext, (IntPtr)pbAdditionalAuthenticatedData, cbAdditionalAuthenticatedData, cbPreBuffer, cbPostBuffer); } diff --git a/src/Hosting/Hosting/src/Internal/HostingApplication.cs b/src/Hosting/Hosting/src/Internal/HostingApplication.cs index 9bb72ac668b4..7e7e934511f2 100644 --- a/src/Hosting/Hosting/src/Internal/HostingApplication.cs +++ b/src/Hosting/Hosting/src/Internal/HostingApplication.cs @@ -17,7 +17,7 @@ internal class HostingApplication : IHttpApplication private readonly RequestDelegate _application; private readonly IHttpContextFactory? _httpContextFactory; private readonly DefaultHttpContextFactory? _defaultHttpContextFactory; - private HostingApplicationDiagnostics _diagnostics; + private readonly HostingApplicationDiagnostics _diagnostics; public HostingApplication( RequestDelegate application, diff --git a/src/Hosting/Hosting/src/Startup/DelegateStartup.cs b/src/Hosting/Hosting/src/Startup/DelegateStartup.cs index c71f54c52e99..dfc1317ece00 100644 --- a/src/Hosting/Hosting/src/Startup/DelegateStartup.cs +++ b/src/Hosting/Hosting/src/Startup/DelegateStartup.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Hosting /// public class DelegateStartup : StartupBase { - private Action _configureApp; + private readonly Action _configureApp; /// /// Creates a new instance. diff --git a/src/Hosting/Server.IntegrationTesting/src/Common/LoggingHandler.cs b/src/Hosting/Server.IntegrationTesting/src/Common/LoggingHandler.cs index a1dc7e24dbd3..002e5c78bb20 100644 --- a/src/Hosting/Server.IntegrationTesting/src/Common/LoggingHandler.cs +++ b/src/Hosting/Server.IntegrationTesting/src/Common/LoggingHandler.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting { internal class LoggingHandler : DelegatingHandler { - private ILogger _logger; + private readonly ILogger _logger; public LoggingHandler(ILoggerFactory loggerFactory, HttpMessageHandler innerHandler) : base(innerHandler) { diff --git a/src/Hosting/TestHost/src/ResponseBodyReaderStream.cs b/src/Hosting/TestHost/src/ResponseBodyReaderStream.cs index 01a8ee748b10..c4799a1690b4 100644 --- a/src/Hosting/TestHost/src/ResponseBodyReaderStream.cs +++ b/src/Hosting/TestHost/src/ResponseBodyReaderStream.cs @@ -68,7 +68,7 @@ public override int Read(byte[] buffer, int offset, int count) return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); } - public async override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { VerifyBuffer(buffer, offset, count); CheckAborted(); diff --git a/src/Hosting/TestHost/src/TestServer.cs b/src/Hosting/TestHost/src/TestServer.cs index fdc43e3f9437..cd4898af1ee0 100644 --- a/src/Hosting/TestHost/src/TestServer.cs +++ b/src/Hosting/TestHost/src/TestServer.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.TestHost /// public class TestServer : IServer { - private IWebHost? _hostInstance; + private readonly IWebHost? _hostInstance; private bool _disposed; private ApplicationWrapper? _application; diff --git a/src/Hosting/TestHost/src/TestWebSocket.cs b/src/Hosting/TestHost/src/TestWebSocket.cs index e6ede4ec429e..3d17b24be64f 100644 --- a/src/Hosting/TestHost/src/TestWebSocket.cs +++ b/src/Hosting/TestHost/src/TestWebSocket.cs @@ -48,7 +48,7 @@ public override string? SubProtocol get { return _subProtocol; } } - public async override Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) + public override async Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) { ThrowIfDisposed(); @@ -71,7 +71,7 @@ public async override Task CloseAsync(WebSocketCloseStatus closeStatus, string? } } - public async override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) + public override async Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) { ThrowIfDisposed(); ThrowIfOutputClosed(); @@ -264,7 +264,7 @@ public ReceiverSenderBuffer() _messageQueue = new Queue(); } - public async virtual Task ReceiveAsync(CancellationToken cancellationToken) + public virtual async Task ReceiveAsync(CancellationToken cancellationToken) { if (_disposed) { diff --git a/src/Http/Headers/src/GenericHeaderParser.cs b/src/Http/Headers/src/GenericHeaderParser.cs index 1d4499e0b6fc..c2231b4e0ced 100644 --- a/src/Http/Headers/src/GenericHeaderParser.cs +++ b/src/Http/Headers/src/GenericHeaderParser.cs @@ -10,7 +10,7 @@ internal sealed class GenericHeaderParser : BaseHeaderParser { internal delegate int GetParsedValueLengthDelegate(StringSegment value, int startIndex, out T? parsedValue); - private GetParsedValueLengthDelegate _getParsedValueLength; + private readonly GetParsedValueLengthDelegate _getParsedValueLength; internal GenericHeaderParser(bool supportsMultipleValues, GetParsedValueLengthDelegate getParsedValueLength) : base(supportsMultipleValues) diff --git a/src/Http/Http.Abstractions/src/Internal/HostStringHelper.cs b/src/Http/Http.Abstractions/src/Internal/HostStringHelper.cs index 7644b1a06c6d..9e42e1294458 100644 --- a/src/Http/Http.Abstractions/src/Internal/HostStringHelper.cs +++ b/src/Http/Http.Abstractions/src/Internal/HostStringHelper.cs @@ -9,7 +9,7 @@ internal class HostStringHelper // A-Z, a-z, 0-9, ., // -, %, [, ], : // Above for IPV6 - private static bool[] SafeHostStringChars = { + private static readonly bool[] SafeHostStringChars = { false, false, false, false, false, false, false, false, // 0x00 - 0x07 false, false, false, false, false, false, false, false, // 0x08 - 0x0F false, false, false, false, false, false, false, false, // 0x10 - 0x17 diff --git a/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs b/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs index 6051068e527c..f7a60d4043e4 100644 --- a/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs +++ b/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs @@ -152,7 +152,7 @@ private T[] GetOrderedMetadataSlow() where T : class public struct Enumerator : IEnumerator { // Intentionally not readonly to prevent defensive struct copies - private object[] _items; + private readonly object[] _items; private int _index; internal Enumerator(EndpointMetadataCollection collection) diff --git a/src/Http/Http.Abstractions/test/UseMiddlewareTest.cs b/src/Http/Http.Abstractions/test/UseMiddlewareTest.cs index 71fd2324d945..b51db76cdb8b 100644 --- a/src/Http/Http.Abstractions/test/UseMiddlewareTest.cs +++ b/src/Http/Http.Abstractions/test/UseMiddlewareTest.cs @@ -268,7 +268,7 @@ public void Release(IMiddleware middleware) { } private class DummyServiceProvider : IServiceProvider { - private Dictionary _services = new Dictionary(); + private readonly Dictionary _services = new Dictionary(); public void AddService(Type type, object value) => _services[type] = value; diff --git a/src/Http/Http.Extensions/src/HeaderDictionaryTypeExtensions.cs b/src/Http/Http.Extensions/src/HeaderDictionaryTypeExtensions.cs index 89288c9f96c0..736f8607047e 100644 --- a/src/Http/Http.Extensions/src/HeaderDictionaryTypeExtensions.cs +++ b/src/Http/Http.Extensions/src/HeaderDictionaryTypeExtensions.cs @@ -168,7 +168,7 @@ internal static void SetDate(this IHeaderDictionary headers, string name, DateTi } } - private static IDictionary KnownParsers = new Dictionary() + private static readonly IDictionary KnownParsers = new Dictionary() { { typeof(CacheControlHeaderValue), new Func(value => { return CacheControlHeaderValue.TryParse(value, out var result) ? result : null; }) }, { typeof(ContentDispositionHeaderValue), new Func(value => { return ContentDispositionHeaderValue.TryParse(value, out var result) ? result : null; }) }, @@ -181,7 +181,7 @@ internal static void SetDate(this IHeaderDictionary headers, string name, DateTi { typeof(long?), new Func(value => { return HeaderUtilities.TryParseNonNegativeInt64(value, out var result) ? result : null; }) }, }; - private static IDictionary KnownListParsers = new Dictionary() + private static readonly IDictionary KnownListParsers = new Dictionary() { { typeof(MediaTypeHeaderValue), new Func, IList>(value => { return MediaTypeHeaderValue.TryParseList(value, out var result) ? result : Array.Empty(); }) }, { typeof(StringWithQualityHeaderValue), new Func, IList>(value => { return StringWithQualityHeaderValue.TryParseList(value, out var result) ? result : Array.Empty(); }) }, diff --git a/src/Http/Http.Extensions/src/QueryBuilder.cs b/src/Http/Http.Extensions/src/QueryBuilder.cs index 9f14cd9f7b15..3fb899efdf61 100644 --- a/src/Http/Http.Extensions/src/QueryBuilder.cs +++ b/src/Http/Http.Extensions/src/QueryBuilder.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Http.Extensions /// public class QueryBuilder : IEnumerable> { - private IList> _params; + private readonly IList> _params; /// /// Initializes a new instance of . diff --git a/src/Http/Http/src/Features/RequestBodyPipeFeature.cs b/src/Http/Http/src/Features/RequestBodyPipeFeature.cs index 994a813a7623..08db861a862a 100644 --- a/src/Http/Http/src/Features/RequestBodyPipeFeature.cs +++ b/src/Http/Http/src/Features/RequestBodyPipeFeature.cs @@ -15,7 +15,7 @@ public class RequestBodyPipeFeature : IRequestBodyPipeFeature { private PipeReader? _internalPipeReader; private Stream? _streamInstanceWhenWrapped; - private HttpContext _context; + private readonly HttpContext _context; /// /// Initializes a new instance of . diff --git a/src/Http/Http/src/Features/RequestCookiesFeature.cs b/src/Http/Http/src/Features/RequestCookiesFeature.cs index e5d36d3bf8dd..c3458fd94db7 100644 --- a/src/Http/Http/src/Features/RequestCookiesFeature.cs +++ b/src/Http/Http/src/Features/RequestCookiesFeature.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Http.Features public class RequestCookiesFeature : IRequestCookiesFeature { // Lambda hoisted to static readonly field to improve inlining https://github.com/dotnet/roslyn/issues/13624 - private readonly static Func _nullRequestFeature = f => null; + private static readonly Func _nullRequestFeature = f => null; private FeatureReferences _features; private StringValues _original; diff --git a/src/Http/Http/src/FormCollection.cs b/src/Http/Http/src/FormCollection.cs index e937dbd5eb4d..8dec9be3ab6e 100644 --- a/src/Http/Http/src/FormCollection.cs +++ b/src/Http/Http/src/FormCollection.cs @@ -23,7 +23,7 @@ public class FormCollection : IFormCollection private static readonly IEnumerator> EmptyIEnumeratorType = default(Enumerator); private static readonly IEnumerator EmptyIEnumerator = default(Enumerator); - private static IFormFileCollection EmptyFiles = new FormFileCollection(); + private static readonly IFormFileCollection EmptyFiles = new FormFileCollection(); private IFormFileCollection? _files; @@ -174,7 +174,7 @@ public struct Enumerator : IEnumerator> { // Do NOT make this readonly, or MoveNext will not work private Dictionary.Enumerator _dictionaryEnumerator; - private bool _notEmpty; + private readonly bool _notEmpty; internal Enumerator(Dictionary.Enumerator dictionaryEnumerator) { diff --git a/src/Http/Http/src/HeaderDictionary.cs b/src/Http/Http/src/HeaderDictionary.cs index 620d4fc207e1..3664e748bf04 100644 --- a/src/Http/Http/src/HeaderDictionary.cs +++ b/src/Http/Http/src/HeaderDictionary.cs @@ -376,7 +376,7 @@ public struct Enumerator : IEnumerator> { // Do NOT make this readonly, or MoveNext will not work private Dictionary.Enumerator _dictionaryEnumerator; - private bool _notEmpty; + private readonly bool _notEmpty; internal Enumerator(Dictionary.Enumerator dictionaryEnumerator) { diff --git a/src/Http/Http/src/HttpContextAccessor.cs b/src/Http/Http/src/HttpContextAccessor.cs index 553b512dbb23..6bdb99f30b53 100644 --- a/src/Http/Http/src/HttpContextAccessor.cs +++ b/src/Http/Http/src/HttpContextAccessor.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Http /// public class HttpContextAccessor : IHttpContextAccessor { - private static AsyncLocal _httpContextCurrent = new AsyncLocal(); + private static readonly AsyncLocal _httpContextCurrent = new AsyncLocal(); /// public HttpContext? HttpContext diff --git a/src/Http/Http/src/Internal/DefaultConnectionInfo.cs b/src/Http/Http/src/Internal/DefaultConnectionInfo.cs index 12f4ff2175f0..32cc822beead 100644 --- a/src/Http/Http/src/Internal/DefaultConnectionInfo.cs +++ b/src/Http/Http/src/Internal/DefaultConnectionInfo.cs @@ -14,9 +14,9 @@ namespace Microsoft.AspNetCore.Http internal sealed class DefaultConnectionInfo : ConnectionInfo { // Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624 - private readonly static Func _newHttpConnectionFeature = f => new HttpConnectionFeature(); - private readonly static Func _newTlsConnectionFeature = f => new TlsConnectionFeature(); - private readonly static Func _newConnectionLifetime = f => new DefaultConnectionLifetimeNotificationFeature(f.Get()); + private static readonly Func _newHttpConnectionFeature = f => new HttpConnectionFeature(); + private static readonly Func _newTlsConnectionFeature = f => new TlsConnectionFeature(); + private static readonly Func _newConnectionLifetime = f => new DefaultConnectionLifetimeNotificationFeature(f.Get()); private FeatureReferences _features; diff --git a/src/Http/Http/src/Internal/DefaultHttpRequest.cs b/src/Http/Http/src/Internal/DefaultHttpRequest.cs index 9c54c0883d58..2dd5468fc453 100644 --- a/src/Http/Http/src/Internal/DefaultHttpRequest.cs +++ b/src/Http/Http/src/Internal/DefaultHttpRequest.cs @@ -18,12 +18,12 @@ internal sealed class DefaultHttpRequest : HttpRequest private const string Https = "https"; // Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624 - private readonly static Func _nullRequestFeature = f => null; - private readonly static Func _newQueryFeature = f => new QueryFeature(f); - private readonly static Func _newFormFeature = r => new FormFeature(r, r._context.FormOptions ?? FormOptions.Default); - private readonly static Func _newRequestCookiesFeature = f => new RequestCookiesFeature(f); - private readonly static Func _newRouteValuesFeature = f => new RouteValuesFeature(); - private readonly static Func _newRequestBodyPipeFeature = context => new RequestBodyPipeFeature(context); + private static readonly Func _nullRequestFeature = f => null; + private static readonly Func _newQueryFeature = f => new QueryFeature(f); + private static readonly Func _newFormFeature = r => new FormFeature(r, r._context.FormOptions ?? FormOptions.Default); + private static readonly Func _newRequestCookiesFeature = f => new RequestCookiesFeature(f); + private static readonly Func _newRouteValuesFeature = f => new RouteValuesFeature(); + private static readonly Func _newRequestBodyPipeFeature = context => new RequestBodyPipeFeature(context); private readonly DefaultHttpContext _context; private FeatureReferences _features; diff --git a/src/Http/Http/src/Internal/DefaultWebSocketManager.cs b/src/Http/Http/src/Internal/DefaultWebSocketManager.cs index 8697904b952c..51bbd84bf353 100644 --- a/src/Http/Http/src/Internal/DefaultWebSocketManager.cs +++ b/src/Http/Http/src/Internal/DefaultWebSocketManager.cs @@ -13,11 +13,11 @@ namespace Microsoft.AspNetCore.Http internal sealed class DefaultWebSocketManager : WebSocketManager { // Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624 - private readonly static Func _nullRequestFeature = f => null; - private readonly static Func _nullWebSocketFeature = f => null; + private static readonly Func _nullRequestFeature = f => null; + private static readonly Func _nullWebSocketFeature = f => null; private FeatureReferences _features; - private readonly static WebSocketAcceptContext _defaultWebSocketAcceptContext = new WebSocketAcceptContext(); + private static readonly WebSocketAcceptContext _defaultWebSocketAcceptContext = new WebSocketAcceptContext(); public DefaultWebSocketManager(IFeatureCollection features) { diff --git a/src/Http/Http/src/Internal/ItemsDictionary.cs b/src/Http/Http/src/Internal/ItemsDictionary.cs index 0ea54f92c1cd..eda357038e21 100644 --- a/src/Http/Http/src/Internal/ItemsDictionary.cs +++ b/src/Http/Http/src/Internal/ItemsDictionary.cs @@ -140,7 +140,7 @@ private void EnsureDictionary() private class EmptyEnumerator : IEnumerator> { // In own class so only initalized if GetEnumerator is called on an empty ItemsDictionary - public readonly static IEnumerator> Instance = new EmptyEnumerator(); + public static readonly IEnumerator> Instance = new EmptyEnumerator(); public KeyValuePair Current => default; object? IEnumerator.Current => null; @@ -157,7 +157,7 @@ public void Reset() private static class EmptyDictionary { // In own class so only initalized if CopyTo is called on an empty ItemsDictionary - public readonly static IDictionary Dictionary = new Dictionary(); + public static readonly IDictionary Dictionary = new Dictionary(); public static ICollection> Collection => Dictionary; } } diff --git a/src/Http/Http/src/Internal/RequestCookieCollection.cs b/src/Http/Http/src/Internal/RequestCookieCollection.cs index 85d7d4b400be..e3554d5a711b 100644 --- a/src/Http/Http/src/Internal/RequestCookieCollection.cs +++ b/src/Http/Http/src/Internal/RequestCookieCollection.cs @@ -178,7 +178,7 @@ public struct Enumerator : IEnumerator> { // Do NOT make this readonly, or MoveNext will not work private AdaptiveCapacityDictionary.Enumerator _dictionaryEnumerator; - private bool _notEmpty; + private readonly bool _notEmpty; internal Enumerator(AdaptiveCapacityDictionary.Enumerator dictionaryEnumerator) { diff --git a/src/Http/Http/src/QueryCollection.cs b/src/Http/Http/src/QueryCollection.cs index bad48e4852b9..f2eb11ab2265 100644 --- a/src/Http/Http/src/QueryCollection.cs +++ b/src/Http/Http/src/QueryCollection.cs @@ -190,7 +190,7 @@ public struct Enumerator : IEnumerator> { // Do NOT make this readonly, or MoveNext will not work private Dictionary.Enumerator _dictionaryEnumerator; - private bool _notEmpty; + private readonly bool _notEmpty; internal Enumerator(Dictionary.Enumerator dictionaryEnumerator) { diff --git a/src/Http/Http/src/QueryCollectionInternal.cs b/src/Http/Http/src/QueryCollectionInternal.cs index 45b40fe5feb1..3ca061c1491b 100644 --- a/src/Http/Http/src/QueryCollectionInternal.cs +++ b/src/Http/Http/src/QueryCollectionInternal.cs @@ -83,7 +83,7 @@ public struct Enumerator : IEnumerator> { // Do NOT make this readonly, or MoveNext will not work private AdaptiveCapacityDictionary.Enumerator _dictionaryEnumerator; - private bool _notEmpty; + private readonly bool _notEmpty; internal Enumerator(AdaptiveCapacityDictionary.Enumerator dictionaryEnumerator) { diff --git a/src/Http/Http/test/DefaultHttpContextTests.cs b/src/Http/Http/test/DefaultHttpContextTests.cs index 5ca8688d04e7..cc59786cdda7 100644 --- a/src/Http/Http/test/DefaultHttpContextTests.cs +++ b/src/Http/Http/test/DefaultHttpContextTests.cs @@ -405,7 +405,7 @@ public void OnStarting(Func callback, object state) private class TestSession : ISession { - private Dictionary _store + private readonly Dictionary _store = new Dictionary(StringComparer.OrdinalIgnoreCase); public string Id { get; set; } diff --git a/src/Http/Http/test/Features/NonSeekableReadStream.cs b/src/Http/Http/test/Features/NonSeekableReadStream.cs index 279da7992b94..859ef12196f0 100644 --- a/src/Http/Http/test/Features/NonSeekableReadStream.cs +++ b/src/Http/Http/test/Features/NonSeekableReadStream.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Http.Features { public class NonSeekableReadStream : Stream { - private Stream _inner; + private readonly Stream _inner; public NonSeekableReadStream(byte[] data) : this(new MemoryStream(data)) diff --git a/src/Http/Http/test/Internal/DefaultHttpResponseTests.cs b/src/Http/Http/test/Internal/DefaultHttpResponseTests.cs index 40aa9390015a..989146d6a5ef 100644 --- a/src/Http/Http/test/Internal/DefaultHttpResponseTests.cs +++ b/src/Http/Http/test/Internal/DefaultHttpResponseTests.cs @@ -198,7 +198,7 @@ public async Task RegisterForDisposeHandlesDisposeAsyncIfObjectImplementsIAsyncD public class ResponseFeature : IHttpResponseFeature { - private List<(Func, object)> _callbacks = new(); + private readonly List<(Func, object)> _callbacks = new(); public int StatusCode { get; set; } public string ReasonPhrase { get; set; } public IHeaderDictionary Headers { get; set; } diff --git a/src/Http/Owin/test/OwinExtensionTests.cs b/src/Http/Owin/test/OwinExtensionTests.cs index be541ef44c74..26dbd963e710 100644 --- a/src/Http/Owin/test/OwinExtensionTests.cs +++ b/src/Http/Owin/test/OwinExtensionTests.cs @@ -24,7 +24,7 @@ namespace Microsoft.AspNetCore.Owin public class OwinExtensionTests { - static AppFunc notFound = env => new Task(() => { env["owin.ResponseStatusCode"] = 404; }); + static readonly AppFunc notFound = env => new Task(() => { env["owin.ResponseStatusCode"] = 404; }); [Fact] public async Task OwinConfigureServiceProviderAddsServices() diff --git a/src/Http/Routing/perf/Microbenchmarks/Matching/MatcherBuilderMultipleEntryBenchmark.cs b/src/Http/Routing/perf/Microbenchmarks/Matching/MatcherBuilderMultipleEntryBenchmark.cs index 5229c4f1d681..6dc5e373aa4d 100644 --- a/src/Http/Routing/perf/Microbenchmarks/Matching/MatcherBuilderMultipleEntryBenchmark.cs +++ b/src/Http/Routing/perf/Microbenchmarks/Matching/MatcherBuilderMultipleEntryBenchmark.cs @@ -187,7 +187,7 @@ public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) private abstract class TestMatcherPolicyBase : MatcherPolicy { - private int _order; + private readonly int _order; protected TestMatcherPolicyBase(int order) { diff --git a/src/Http/Routing/src/Constraints/StringRouteConstraint.cs b/src/Http/Routing/src/Constraints/StringRouteConstraint.cs index 737cf228128f..a6231d40020d 100644 --- a/src/Http/Routing/src/Constraints/StringRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/StringRouteConstraint.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Routing.Constraints /// public class StringRouteConstraint : IRouteConstraint { - private string _value; + private readonly string _value; /// /// Initializes a new instance of the class. diff --git a/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs b/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs index 620e63571689..d04ba767d2c4 100644 --- a/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs +++ b/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Routing.Matching /// public sealed class EndpointMetadataComparer : IComparer { - private IServiceProvider _services; + private readonly IServiceProvider _services; private IComparer[]? _comparers; // This type is **INTENDED** for use in MatcherPolicy instances yet is also needs the MatcherPolicy instances. diff --git a/src/Http/Routing/src/Matching/HostMatcherPolicy.cs b/src/Http/Routing/src/Matching/HostMatcherPolicy.cs index 7e39d449b428..8b580d5e3a66 100644 --- a/src/Http/Routing/src/Matching/HostMatcherPolicy.cs +++ b/src/Http/Routing/src/Matching/HostMatcherPolicy.cs @@ -359,8 +359,8 @@ protected override int CompareMetadata(IHostMetadata? x, IHostMetadata? y) private class HostPolicyJumpTable : PolicyJumpTable { - private (EdgeKey host, int destination)[] _destinations; - private int _exitDestination; + private readonly (EdgeKey host, int destination)[] _destinations; + private readonly int _exitDestination; public HostPolicyJumpTable(int exitDestination, (EdgeKey host, int destination)[] destinations) { diff --git a/src/Http/Routing/src/RouteCollection.cs b/src/Http/Routing/src/RouteCollection.cs index 2f644cbfb37c..1426abfc8089 100644 --- a/src/Http/Routing/src/RouteCollection.cs +++ b/src/Http/Routing/src/RouteCollection.cs @@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Routing /// public class RouteCollection : IRouteCollection { - private readonly static char[] UrlQueryDelimiters = new char[] { '?', '#' }; + private static readonly char[] UrlQueryDelimiters = new char[] { '?', '#' }; private readonly List _routes = new List(); private readonly List _unnamedRoutes = new List(); private readonly Dictionary _namedRoutes = @@ -69,7 +69,7 @@ public void Add(IRouter router) } /// - public async virtual Task RouteAsync(RouteContext context) + public virtual async Task RouteAsync(RouteContext context) { // Perf: We want to avoid allocating a new RouteData for each route we need to process. // We can do this by snapshotting the state at the beginning and then restoring it diff --git a/src/Http/Routing/src/Template/TemplateMatcher.cs b/src/Http/Routing/src/Template/TemplateMatcher.cs index 1cffb0d42c47..a6657aeaf6e2 100644 --- a/src/Http/Routing/src/Template/TemplateMatcher.cs +++ b/src/Http/Routing/src/Template/TemplateMatcher.cs @@ -18,7 +18,7 @@ public class TemplateMatcher private readonly bool[] _hasDefaultValue; private readonly object?[] _defaultValues; - private RoutePatternMatcher _routePatternMatcher; + private readonly RoutePatternMatcher _routePatternMatcher; /// /// Creates a new instance given a and . diff --git a/src/Http/Routing/src/UriBuildingContext.cs b/src/Http/Routing/src/UriBuildingContext.cs index bf68a9449cd5..d85e5970f97d 100644 --- a/src/Http/Routing/src/UriBuildingContext.cs +++ b/src/Http/Routing/src/UriBuildingContext.cs @@ -16,7 +16,7 @@ internal class UriBuildingContext { // Holds the 'accepted' parts of the path. private readonly StringBuilder _path; - private StringBuilder _query; + private readonly StringBuilder _query; // Holds the 'optional' parts of the path. We need a secondary buffer to handle cases where an optional // segment is in the middle of the uri. We don't know if we need to write it out - if it's diff --git a/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs b/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs index e2957e54704e..4ce27b93992d 100644 --- a/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs +++ b/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs @@ -127,7 +127,7 @@ private TestEndpointConventionBuilder CreateBuilder() private class TestEndpointConventionBuilder : IEndpointConventionBuilder { - private DefaultEndpointConventionBuilder _endpointConventionBuilder; + private readonly DefaultEndpointConventionBuilder _endpointConventionBuilder; public bool TestProperty { get; } = true; public TestEndpointConventionBuilder(DefaultEndpointConventionBuilder endpointConventionBuilder) diff --git a/src/Http/Routing/test/UnitTests/Constraints/CompositeRouteConstraintTests.cs b/src/Http/Routing/test/UnitTests/Constraints/CompositeRouteConstraintTests.cs index b4df74c26287..ece4da2c9c86 100644 --- a/src/Http/Routing/test/UnitTests/Constraints/CompositeRouteConstraintTests.cs +++ b/src/Http/Routing/test/UnitTests/Constraints/CompositeRouteConstraintTests.cs @@ -34,7 +34,7 @@ public void CompositeRouteConstraint_Match_CallsMatchOnInnerConstraints( Assert.Equal(expected, actual); } - static Expression> ConstraintMatchMethodExpression = + static readonly Expression> ConstraintMatchMethodExpression = c => c.Match( It.IsAny(), It.IsAny(), diff --git a/src/Http/Routing/test/UnitTests/DefaultInlineConstraintResolverTest.cs b/src/Http/Routing/test/UnitTests/DefaultInlineConstraintResolverTest.cs index da4cf39c0957..a50c8aa6d9b7 100644 --- a/src/Http/Routing/test/UnitTests/DefaultInlineConstraintResolverTest.cs +++ b/src/Http/Routing/test/UnitTests/DefaultInlineConstraintResolverTest.cs @@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.Routing.Tests { public class DefaultInlineConstraintResolverTest { - private IInlineConstraintResolver _constraintResolver; + private readonly IInlineConstraintResolver _constraintResolver; public DefaultInlineConstraintResolverTest() { diff --git a/src/Http/Routing/test/UnitTests/MatcherPolicyTest.cs b/src/Http/Routing/test/UnitTests/MatcherPolicyTest.cs index 3c62aa1eccdc..ee618241f6c7 100644 --- a/src/Http/Routing/test/UnitTests/MatcherPolicyTest.cs +++ b/src/Http/Routing/test/UnitTests/MatcherPolicyTest.cs @@ -83,7 +83,7 @@ private class TestMatcherPolicy : MatcherPolicy { public override int Order => throw new System.NotImplementedException(); - public new static bool ContainsDynamicEndpoints(IReadOnlyList endpoints) + public static new bool ContainsDynamicEndpoints(IReadOnlyList endpoints) { return MatcherPolicy.ContainsDynamicEndpoints(endpoints); } diff --git a/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcherBuilder.cs b/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcherBuilder.cs index d55d0dcdf096..9259cdac8f15 100644 --- a/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcherBuilder.cs +++ b/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcherBuilder.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Routing.Matching { internal class BarebonesMatcherBuilder : MatcherBuilder { - private List _endpoints = new List(); + private readonly List _endpoints = new List(); public override void AddEndpoint(RouteEndpoint endpoint) { diff --git a/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs b/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs index 540fc2e07b5d..e18035d718ad 100644 --- a/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs +++ b/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs @@ -17,7 +17,7 @@ internal RouteMatcher(RouteCollection inner) _inner = inner; } - public async override Task MatchAsync(HttpContext httpContext) + public override async Task MatchAsync(HttpContext httpContext) { if (httpContext == null) { diff --git a/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs b/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs index 6145013c8039..3d9112274baf 100644 --- a/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs +++ b/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs @@ -19,7 +19,7 @@ internal TreeRouterMatcher(TreeRouter inner) _inner = inner; } - public async override Task MatchAsync(HttpContext httpContext) + public override async Task MatchAsync(HttpContext httpContext) { if (httpContext == null) { diff --git a/src/Http/Routing/test/UnitTests/RouteTest.cs b/src/Http/Routing/test/UnitTests/RouteTest.cs index 16e7571e2e55..f83d50c5e1e2 100644 --- a/src/Http/Routing/test/UnitTests/RouteTest.cs +++ b/src/Http/Routing/test/UnitTests/RouteTest.cs @@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.Routing public class RouteTest { private static readonly RequestDelegate NullHandler = (c) => Task.CompletedTask; - private static IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver(); + private static readonly IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver(); [Fact] public void CreateTemplate_InlineConstraint_Regex_Malformed() diff --git a/src/Http/Routing/test/UnitTests/RouterMiddlewareTest.cs b/src/Http/Routing/test/UnitTests/RouterMiddlewareTest.cs index 29a03c7e0831..41d4bf0ba1e7 100644 --- a/src/Http/Routing/test/UnitTests/RouterMiddlewareTest.cs +++ b/src/Http/Routing/test/UnitTests/RouterMiddlewareTest.cs @@ -128,7 +128,7 @@ public async Task Invoke_DoesNotLog_WhenHandled() private class TestRouter : IRouter { - private bool _isHandled; + private readonly bool _isHandled; public TestRouter(bool isHandled) { diff --git a/src/Http/Routing/test/UnitTests/TemplateParserDefaultValuesTests.cs b/src/Http/Routing/test/UnitTests/TemplateParserDefaultValuesTests.cs index 2a5ae1f91849..6cd29194a541 100644 --- a/src/Http/Routing/test/UnitTests/TemplateParserDefaultValuesTests.cs +++ b/src/Http/Routing/test/UnitTests/TemplateParserDefaultValuesTests.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Routing.Tests { public class TemplateParserDefaultValuesTests { - private static IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver(); + private static readonly IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver(); [Fact] public void InlineDefaultValueSpecified_InlineValueIsUsed() diff --git a/src/Http/WebUtilities/perf/Microbenchmarks/FormPipeReaderInternalsBenchmark.cs b/src/Http/WebUtilities/perf/Microbenchmarks/FormPipeReaderInternalsBenchmark.cs index e82e96da1438..b56afb9f9c9d 100644 --- a/src/Http/WebUtilities/perf/Microbenchmarks/FormPipeReaderInternalsBenchmark.cs +++ b/src/Http/WebUtilities/perf/Microbenchmarks/FormPipeReaderInternalsBenchmark.cs @@ -12,9 +12,9 @@ namespace Microsoft.AspNetCore.WebUtilities.Microbenchmarks /// public class FormPipeReaderInternalsBenchmark { - private byte[] _singleUtf8 = Encoding.UTF8.GetBytes("foo=bar&baz=boo&haha=hehe&lol=temp"); - private byte[] _firstUtf8 = Encoding.UTF8.GetBytes("foo=bar&baz=bo"); - private byte[] _secondUtf8 = Encoding.UTF8.GetBytes("o&haha=hehe&lol=temp"); + private readonly byte[] _singleUtf8 = Encoding.UTF8.GetBytes("foo=bar&baz=boo&haha=hehe&lol=temp"); + private readonly byte[] _firstUtf8 = Encoding.UTF8.GetBytes("foo=bar&baz=bo"); + private readonly byte[] _secondUtf8 = Encoding.UTF8.GetBytes("o&haha=hehe&lol=temp"); private FormPipeReader _formPipeReader; [IterationSetup] diff --git a/src/Http/WebUtilities/src/FileMultipartSection.cs b/src/Http/WebUtilities/src/FileMultipartSection.cs index daf7b3d0e918..2cd8ef6c3e35 100644 --- a/src/Http/WebUtilities/src/FileMultipartSection.cs +++ b/src/Http/WebUtilities/src/FileMultipartSection.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.WebUtilities /// public class FileMultipartSection { - private ContentDispositionHeaderValue _contentDispositionHeader; + private readonly ContentDispositionHeaderValue _contentDispositionHeader; /// /// Creates a new instance of the class diff --git a/src/Http/WebUtilities/src/FormMultipartSection.cs b/src/Http/WebUtilities/src/FormMultipartSection.cs index 520c67112cef..170e45728d73 100644 --- a/src/Http/WebUtilities/src/FormMultipartSection.cs +++ b/src/Http/WebUtilities/src/FormMultipartSection.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.WebUtilities /// public class FormMultipartSection { - private ContentDispositionHeaderValue _contentDispositionHeader; + private readonly ContentDispositionHeaderValue _contentDispositionHeader; /// /// Creates a new instance of the class diff --git a/src/Http/WebUtilities/src/FormPipeReader.cs b/src/Http/WebUtilities/src/FormPipeReader.cs index 92c340f973ae..49fcdafbf557 100644 --- a/src/Http/WebUtilities/src/FormPipeReader.cs +++ b/src/Http/WebUtilities/src/FormPipeReader.cs @@ -34,8 +34,8 @@ public class FormPipeReader private static ReadOnlySpan UTF8AndEncoded => new byte[] { (byte)'&' }; // Used for other encodings - private byte[]? _otherEqualEncoding; - private byte[]? _otherAndEncoding; + private readonly byte[]? _otherEqualEncoding; + private readonly byte[]? _otherAndEncoding; private readonly PipeReader _pipeReader; private readonly Encoding _encoding; diff --git a/src/Http/WebUtilities/src/HttpRequestStreamReader.cs b/src/Http/WebUtilities/src/HttpRequestStreamReader.cs index 338d14491012..6ef2fb430b85 100644 --- a/src/Http/WebUtilities/src/HttpRequestStreamReader.cs +++ b/src/Http/WebUtilities/src/HttpRequestStreamReader.cs @@ -19,7 +19,7 @@ public class HttpRequestStreamReader : TextReader { private const int DefaultBufferSize = 1024; - private Stream _stream; + private readonly Stream _stream; private readonly Encoding _encoding; private readonly Decoder _decoder; @@ -27,8 +27,8 @@ public class HttpRequestStreamReader : TextReader private readonly ArrayPool _charPool; private readonly int _byteBufferSize; - private byte[] _byteBuffer; - private char[] _charBuffer; + private readonly byte[] _byteBuffer; + private readonly char[] _charBuffer; private int _charBufferIndex; private int _charsRead; diff --git a/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs b/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs index 252c535c8701..3eab97915948 100644 --- a/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs +++ b/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs @@ -21,14 +21,14 @@ public class HttpResponseStreamWriter : TextWriter { internal const int DefaultBufferSize = 16 * 1024; - private Stream _stream; + private readonly Stream _stream; private readonly Encoder _encoder; private readonly ArrayPool _bytePool; private readonly ArrayPool _charPool; private readonly int _charBufferSize; - private byte[] _byteBuffer; - private char[] _charBuffer; + private readonly byte[] _byteBuffer; + private readonly char[] _charBuffer; private int _charBufferCount; private bool _disposed; diff --git a/src/Http/WebUtilities/test/HttpRequestStreamReaderTest.cs b/src/Http/WebUtilities/test/HttpRequestStreamReaderTest.cs index 87b2408d1508..426f2edb2129 100644 --- a/src/Http/WebUtilities/test/HttpRequestStreamReaderTest.cs +++ b/src/Http/WebUtilities/test/HttpRequestStreamReaderTest.cs @@ -309,7 +309,7 @@ public static void Read_Span_WithMoreDataThanInternalBufferSize() } [Fact] - public async static Task ReadAsync_Memory_ReadAllCharactersAtOnce() + public static async Task ReadAsync_Memory_ReadAllCharactersAtOnce() { // Arrange var reader = CreateReader(); @@ -328,7 +328,7 @@ public async static Task ReadAsync_Memory_ReadAllCharactersAtOnce() } [Fact] - public async static Task ReadAsync_Memory_WithMoreDataThanInternalBufferSize() + public static async Task ReadAsync_Memory_WithMoreDataThanInternalBufferSize() { // Arrange var reader = CreateReader(10); diff --git a/src/Http/WebUtilities/test/NonSeekableReadStream.cs b/src/Http/WebUtilities/test/NonSeekableReadStream.cs index f3c77abb3852..faadac69f7af 100644 --- a/src/Http/WebUtilities/test/NonSeekableReadStream.cs +++ b/src/Http/WebUtilities/test/NonSeekableReadStream.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.WebUtilities { public class NonSeekableReadStream : Stream { - private Stream _inner; + private readonly Stream _inner; public NonSeekableReadStream(byte[] data) : this(new MemoryStream(data)) diff --git a/src/Identity/ApiAuthorization.IdentityServer/src/Options/ApiResourceBuilder.cs b/src/Identity/ApiAuthorization.IdentityServer/src/Options/ApiResourceBuilder.cs index 0f51c08de702..bff201bcba1f 100644 --- a/src/Identity/ApiAuthorization.IdentityServer/src/Options/ApiResourceBuilder.cs +++ b/src/Identity/ApiAuthorization.IdentityServer/src/Options/ApiResourceBuilder.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.ApiAuthorization.IdentityServer /// public class ApiResourceBuilder { - private ApiResource _apiResource; + private readonly ApiResource _apiResource; private bool _built; /// diff --git a/src/Identity/ApiAuthorization.IdentityServer/src/Options/ClientBuilder.cs b/src/Identity/ApiAuthorization.IdentityServer/src/Options/ClientBuilder.cs index a2bc51e943de..2e66158f0d08 100644 --- a/src/Identity/ApiAuthorization.IdentityServer/src/Options/ClientBuilder.cs +++ b/src/Identity/ApiAuthorization.IdentityServer/src/Options/ClientBuilder.cs @@ -14,8 +14,7 @@ namespace Microsoft.AspNetCore.ApiAuthorization.IdentityServer public class ClientBuilder { private const string NativeAppClientRedirectUri = "urn:ietf:wg:oauth:2.0:oob"; - - Client _client; + readonly Client _client; private bool _built; /// diff --git a/src/Identity/ApiAuthorization.IdentityServer/src/Options/IdentityResourceBuilder.cs b/src/Identity/ApiAuthorization.IdentityServer/src/Options/IdentityResourceBuilder.cs index 623777afb45a..6a04a6640ee4 100644 --- a/src/Identity/ApiAuthorization.IdentityServer/src/Options/IdentityResourceBuilder.cs +++ b/src/Identity/ApiAuthorization.IdentityServer/src/Options/IdentityResourceBuilder.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.ApiAuthorization.IdentityServer /// public class IdentityResourceBuilder { - private IdentityResource _identityResource; + private readonly IdentityResource _identityResource; private bool _built; /// diff --git a/src/Identity/Core/src/SignInManager.cs b/src/Identity/Core/src/SignInManager.cs index b08078d8a23d..838a90319c2b 100644 --- a/src/Identity/Core/src/SignInManager.cs +++ b/src/Identity/Core/src/SignInManager.cs @@ -65,8 +65,8 @@ public SignInManager(UserManager userManager, private readonly IHttpContextAccessor _contextAccessor; private HttpContext _context; - private IAuthenticationSchemeProvider _schemes; - private IUserConfirmation _confirmation; + private readonly IAuthenticationSchemeProvider _schemes; + private readonly IUserConfirmation _confirmation; /// /// Gets the used to log messages from the manager. diff --git a/src/Identity/EntityFrameworkCore/src/RoleStore.cs b/src/Identity/EntityFrameworkCore/src/RoleStore.cs index 8cacb89b5f28..f221c9f29c4d 100644 --- a/src/Identity/EntityFrameworkCore/src/RoleStore.cs +++ b/src/Identity/EntityFrameworkCore/src/RoleStore.cs @@ -135,7 +135,7 @@ private async Task SaveChanges(CancellationToken cancellationToken) /// The role to create in the store. /// The used to propagate notifications that the operation should be canceled. /// A that represents the of the asynchronous query. - public async virtual Task CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) + public virtual async Task CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -154,7 +154,7 @@ private async Task SaveChanges(CancellationToken cancellationToken) /// The role to update in the store. /// The used to propagate notifications that the operation should be canceled. /// A that represents the of the asynchronous query. - public async virtual Task UpdateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) + public virtual async Task UpdateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -182,7 +182,7 @@ private async Task SaveChanges(CancellationToken cancellationToken) /// The role to delete from the store. /// The used to propagate notifications that the operation should be canceled. /// A that represents the of the asynchronous query. - public async virtual Task DeleteAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) + public virtual async Task DeleteAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -368,7 +368,7 @@ protected void ThrowIfDisposed() /// The role whose claims should be retrieved. /// The used to propagate notifications that the operation should be canceled. /// A that contains the claims granted to a role. - public async virtual Task> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) + public virtual async Task> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (role == null) @@ -409,7 +409,7 @@ protected void ThrowIfDisposed() /// The claim to remove from the role. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation. - public async virtual Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)) + public virtual async Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (role == null) diff --git a/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs b/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs index ec77780b83b7..0e54aee3ea1d 100644 --- a/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs +++ b/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs @@ -153,7 +153,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) /// The user to create. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation, containing the of the creation operation. - public async override Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -172,7 +172,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) /// The user to update. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation, containing the of the update operation. - public async override Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -201,7 +201,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) /// The user to delete. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation, containing the of the update operation. - public async override Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -304,7 +304,7 @@ protected override Task FindUserLoginAsync(string loginProvider, str /// The user whose claims should be retrieved. /// The used to propagate notifications that the operation should be canceled. /// A that contains the claims granted to a user. - public async override Task> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (user == null) @@ -348,7 +348,7 @@ protected override Task FindUserLoginAsync(string loginProvider, str /// The new claim replacing the . /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation. - public async override Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (user == null) @@ -379,7 +379,7 @@ protected override Task FindUserLoginAsync(string loginProvider, str /// The claim to remove. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation. - public async override Task RemoveClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task RemoveClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (user == null) @@ -456,7 +456,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st /// /// The for the asynchronous operation, containing a list of for the specified , if any. /// - public async override Task> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -478,7 +478,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st /// /// The for the asynchronous operation, containing the user, if any which matched the specified login provider and key. /// - public async override Task FindByLoginAsync(string loginProvider, string providerKey, + public override async Task FindByLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); @@ -515,7 +515,7 @@ public async override Task FindByLoginAsync(string loginProvider, string /// /// The contains a list of users, if any, that contain the specified claim. /// - public async override Task> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); diff --git a/src/Identity/EntityFrameworkCore/src/UserStore.cs b/src/Identity/EntityFrameworkCore/src/UserStore.cs index e1133ddc7d2d..7220db5e86af 100644 --- a/src/Identity/EntityFrameworkCore/src/UserStore.cs +++ b/src/Identity/EntityFrameworkCore/src/UserStore.cs @@ -154,7 +154,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) /// The user to create. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation, containing the of the creation operation. - public async override Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -173,7 +173,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) /// The user to update. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation, containing the of the update operation. - public async override Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -202,7 +202,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) /// The user to delete. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation, containing the of the update operation. - public async override Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -329,7 +329,7 @@ protected override Task FindUserLoginAsync(string loginProvider, str /// The role to add. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation. - public async override Task AddToRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task AddToRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -356,7 +356,7 @@ protected override Task FindUserLoginAsync(string loginProvider, str /// The role to remove. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation. - public async override Task RemoveFromRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task RemoveFromRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -436,7 +436,7 @@ where userRole.UserId.Equals(userId) /// The user whose claims should be retrieved. /// The used to propagate notifications that the operation should be canceled. /// A that contains the claims granted to a user. - public async override Task> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (user == null) @@ -480,7 +480,7 @@ where userRole.UserId.Equals(userId) /// The new claim replacing the . /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation. - public async override Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (user == null) @@ -511,7 +511,7 @@ where userRole.UserId.Equals(userId) /// The claim to remove. /// The used to propagate notifications that the operation should be canceled. /// The that represents the asynchronous operation. - public async override Task RemoveClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task RemoveClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (user == null) @@ -588,7 +588,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st /// /// The for the asynchronous operation, containing a list of for the specified , if any. /// - public async override Task> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -610,7 +610,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st /// /// The for the asynchronous operation, containing the user, if any which matched the specified login provider and key. /// - public async override Task FindByLoginAsync(string loginProvider, string providerKey, + public override async Task FindByLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); @@ -647,7 +647,7 @@ public async override Task FindByLoginAsync(string loginProvider, string /// /// The contains a list of users, if any, that contain the specified claim. /// - public async override Task> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -673,7 +673,7 @@ join user in Users on userclaims.UserId equals user.Id /// /// The contains a list of users, if any, that are in the specified role. /// - public async override Task> GetUsersInRoleAsync(string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) + public override async Task> GetUsersInRoleAsync(string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); diff --git a/src/Identity/EntityFrameworkCore/test/EF.InMemory.Test/InMemoryContext.cs b/src/Identity/EntityFrameworkCore/test/EF.InMemory.Test/InMemoryContext.cs index 04d58d31bf56..b24e71993114 100644 --- a/src/Identity/EntityFrameworkCore/test/EF.InMemory.Test/InMemoryContext.cs +++ b/src/Identity/EntityFrameworkCore/test/EF.InMemory.Test/InMemoryContext.cs @@ -14,7 +14,7 @@ public class InMemoryContext : private InMemoryContext(DbConnection connection) : base(connection) { } - public new static InMemoryContext Create(DbConnection connection) + public static new InMemoryContext Create(DbConnection connection) => Initialize(new InMemoryContext(connection)); public static TContext Initialize(TContext context) where TContext : DbContext diff --git a/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs b/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs index 5e7d850f012e..c58ec9fcb8c6 100644 --- a/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs +++ b/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs @@ -18,7 +18,7 @@ public class AuthenticatorTokenProvider : IUserTwoFactorTokenProviderThe to retrieve the from. /// The to check for the possibility of generating a two-factor authentication token. /// True if the user has an authenticator key set, otherwise false. - public async virtual Task CanGenerateTwoFactorTokenAsync(UserManager manager, TUser user) + public virtual async Task CanGenerateTwoFactorTokenAsync(UserManager manager, TUser user) { var key = await manager.GetAuthenticatorKeyAsync(user); diff --git a/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs b/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs index 925c5e745228..c3b344965b81 100644 --- a/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs +++ b/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs @@ -17,7 +17,7 @@ public class DefaultUserConfirmation : IUserConfirmation where TUs /// The that can be used to retrieve user properties. /// The user. /// The that represents the asynchronous operation, containing the of the confirmation operation. - public async virtual Task IsConfirmedAsync(UserManager manager, TUser user) + public virtual async Task IsConfirmedAsync(UserManager manager, TUser user) { return await manager.IsEmailConfirmedAsync(user); } diff --git a/src/Identity/Extensions.Core/src/IdentityResult.cs b/src/Identity/Extensions.Core/src/IdentityResult.cs index e137dcd4283a..17a23ee56c07 100644 --- a/src/Identity/Extensions.Core/src/IdentityResult.cs +++ b/src/Identity/Extensions.Core/src/IdentityResult.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Identity public class IdentityResult { private static readonly IdentityResult _success = new IdentityResult { Succeeded = true }; - private List _errors = new List(); + private readonly List _errors = new List(); /// /// Flag indicating whether if the operation succeeded or not. diff --git a/src/Identity/Extensions.Core/src/UserManager.cs b/src/Identity/Extensions.Core/src/UserManager.cs index 778a35900d07..374c5646a046 100644 --- a/src/Identity/Extensions.Core/src/UserManager.cs +++ b/src/Identity/Extensions.Core/src/UserManager.cs @@ -45,7 +45,7 @@ public class UserManager : IDisposable where TUser : class #if NETSTANDARD2_0 || NET461 private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create(); #endif - private IServiceProvider _services; + private readonly IServiceProvider _services; /// /// The cancellation token used to cancel operations. diff --git a/src/Identity/Extensions.Stores/src/UserStoreBase.cs b/src/Identity/Extensions.Stores/src/UserStoreBase.cs index 4031f2d35294..5eea2d16f729 100644 --- a/src/Identity/Extensions.Stores/src/UserStoreBase.cs +++ b/src/Identity/Extensions.Stores/src/UserStoreBase.cs @@ -446,7 +446,7 @@ public void Dispose() /// /// The for the asynchronous operation, containing the user, if any which matched the specified login provider and key. /// - public async virtual Task FindByLoginAsync(string loginProvider, string providerKey, + public virtual async Task FindByLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/Identity/Specification.Tests/src/UserManagerSpecificationTests.cs b/src/Identity/Specification.Tests/src/UserManagerSpecificationTests.cs index a0749b0f366b..60e039eb4ee0 100644 --- a/src/Identity/Specification.Tests/src/UserManagerSpecificationTests.cs +++ b/src/Identity/Specification.Tests/src/UserManagerSpecificationTests.cs @@ -932,7 +932,7 @@ public async Task CanFindByEmail() /// /// Task [Fact] - public async virtual Task CanFindUsersViaUserQuerable() + public virtual async Task CanFindUsersViaUserQuerable() { var mgr = CreateManager(); if (mgr.SupportsQueryableUsers) diff --git a/src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Manage/ResetAuthenticator.cshtml.cs b/src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Manage/ResetAuthenticator.cshtml.cs index 52d1c38e0a92..dfced82d0d71 100644 --- a/src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Manage/ResetAuthenticator.cshtml.cs +++ b/src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Manage/ResetAuthenticator.cshtml.cs @@ -38,9 +38,9 @@ public abstract class ResetAuthenticatorModel : PageModel internal class ResetAuthenticatorModel : ResetAuthenticatorModel where TUser : class { - UserManager _userManager; + readonly UserManager _userManager; private readonly SignInManager _signInManager; - ILogger _logger; + readonly ILogger _logger; public ResetAuthenticatorModel( UserManager userManager, diff --git a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/TaskGenericsUtil.cs b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/TaskGenericsUtil.cs index b5bf93724b77..2bf3aa092f0a 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/TaskGenericsUtil.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/TaskGenericsUtil.cs @@ -10,10 +10,10 @@ namespace Microsoft.JSInterop.Infrastructure { internal static class TaskGenericsUtil { - private static ConcurrentDictionary _cachedResultGetters + private static readonly ConcurrentDictionary _cachedResultGetters = new ConcurrentDictionary(); - private static ConcurrentDictionary _cachedResultSetters + private static readonly ConcurrentDictionary _cachedResultSetters = new ConcurrentDictionary(); public static void SetTaskCompletionSourceResult(object taskCompletionSource, object? result) diff --git a/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/DotNetDispatcherTest.cs b/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/DotNetDispatcherTest.cs index 4ed6c12438a8..1e32fdac70a7 100644 --- a/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/DotNetDispatcherTest.cs +++ b/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/DotNetDispatcherTest.cs @@ -12,7 +12,7 @@ namespace Microsoft.JSInterop.Infrastructure { public class DotNetDispatcherTest { - private readonly static string thisAssemblyName = typeof(DotNetDispatcherTest).Assembly.GetName().Name; + private static readonly string thisAssemblyName = typeof(DotNetDispatcherTest).Assembly.GetName().Name; [Fact] public void CannotInvokeWithEmptyAssemblyName() diff --git a/src/Localization/Abstractions/src/StringLocalizerOfT.cs b/src/Localization/Abstractions/src/StringLocalizerOfT.cs index 0f30ca6c877e..2db647a2c2fd 100644 --- a/src/Localization/Abstractions/src/StringLocalizerOfT.cs +++ b/src/Localization/Abstractions/src/StringLocalizerOfT.cs @@ -13,7 +13,7 @@ namespace Microsoft.Extensions.Localization /// The to provide strings for. public class StringLocalizer : IStringLocalizer { - private IStringLocalizer _localizer; + private readonly IStringLocalizer _localizer; /// /// Creates a new . diff --git a/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueFullOverhead.cs b/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueFullOverhead.cs index 64be1430641c..45c372582549 100644 --- a/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueFullOverhead.cs +++ b/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueFullOverhead.cs @@ -13,7 +13,7 @@ public class QueueFullOverhead { private const int _numRequests = 2000; private int _requestCount = 0; - private ManualResetEventSlim _mres = new ManualResetEventSlim(); + private readonly ManualResetEventSlim _mres = new ManualResetEventSlim(); private ConcurrencyLimiterMiddleware _middlewareQueue; private ConcurrencyLimiterMiddleware _middlewareStack; diff --git a/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueRequestsOverwritten.cs b/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueRequestsOverwritten.cs index 9d16fe0739b5..eadc0ab7ff30 100644 --- a/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueRequestsOverwritten.cs +++ b/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueRequestsOverwritten.cs @@ -12,9 +12,9 @@ namespace Microsoft.AspNetCore.ConcurrencyLimiter.Microbenchmarks public class QueueRequestsOverwritten { private const int _numRejects = 5000; - private int _queueLength = 20; + private readonly int _queueLength = 20; private int _rejectionCount = 0; - private ManualResetEventSlim _mres = new ManualResetEventSlim(); + private readonly ManualResetEventSlim _mres = new ManualResetEventSlim(); private ConcurrencyLimiterMiddleware _middlewareQueue; private ConcurrencyLimiterMiddleware _middlewareStack; diff --git a/src/Middleware/ConcurrencyLimiter/test/PolicyTests/ResettableBooleanCompletionSourceTests.cs b/src/Middleware/ConcurrencyLimiter/test/PolicyTests/ResettableBooleanCompletionSourceTests.cs index 79d36edfc4ca..5051549db9a6 100644 --- a/src/Middleware/ConcurrencyLimiter/test/PolicyTests/ResettableBooleanCompletionSourceTests.cs +++ b/src/Middleware/ConcurrencyLimiter/test/PolicyTests/ResettableBooleanCompletionSourceTests.cs @@ -11,10 +11,10 @@ namespace Microsoft.AspNetCore.ConcurrencyLimiter.Tests.PolicyTests { public static class ResettableBooleanCompletionSourceTests { - private static StackPolicy _testQueue = TestUtils.CreateStackPolicy(8); + private static readonly StackPolicy _testQueue = TestUtils.CreateStackPolicy(8); [Fact] - public async static void CanBeAwaitedMultipleTimes() + public static async Task CanBeAwaitedMultipleTimes() { var tcs = new ResettableBooleanCompletionSource(_testQueue); @@ -32,7 +32,7 @@ public async static void CanBeAwaitedMultipleTimes() } [Fact] - public async static void CanSetResultToTrue() + public static async Task CanSetResultToTrue() { var tcs = new ResettableBooleanCompletionSource(_testQueue); @@ -46,7 +46,7 @@ public async static void CanSetResultToTrue() } [Fact] - public async static void CanSetResultToFalse() + public static async Task CanSetResultToFalse() { var tcs = new ResettableBooleanCompletionSource(_testQueue); diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs index 549240cfc853..f6d72a6d1c77 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs @@ -553,13 +553,13 @@ private static async Task SetupServer(SqlTestStore return host; } - private static UrlEncoder _urlEncoder = UrlEncoder.Default; + private static readonly UrlEncoder _urlEncoder = UrlEncoder.Default; private static string UrlEncode(string content) { return _urlEncoder.Encode(content); } - private static JavaScriptEncoder _javaScriptEncoder = JavaScriptEncoder.Default; + private static readonly JavaScriptEncoder _javaScriptEncoder = JavaScriptEncoder.Default; private static string JavaScriptEncode(string content) { return _javaScriptEncoder.Encode(content); diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/Helpers/TestLoggerProvider.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/Helpers/TestLoggerProvider.cs index 1abb3989cddc..0044360b21f7 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/Helpers/TestLoggerProvider.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/Helpers/TestLoggerProvider.cs @@ -27,9 +27,9 @@ public void Dispose() public class TestLogger : ILogger { - private List _messages = new List(); + private readonly List _messages = new List(); - private object _sync = new object(); + private readonly object _sync = new object(); public IEnumerable Messages { diff --git a/src/Middleware/HeaderPropagation/src/HeaderPropagationValues.cs b/src/Middleware/HeaderPropagation/src/HeaderPropagationValues.cs index 6be18702edae..a13eb65ee734 100644 --- a/src/Middleware/HeaderPropagation/src/HeaderPropagationValues.cs +++ b/src/Middleware/HeaderPropagation/src/HeaderPropagationValues.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.HeaderPropagation /// public class HeaderPropagationValues { - private readonly static AsyncLocal?> _headers = new AsyncLocal?>(); + private static readonly AsyncLocal?> _headers = new AsyncLocal?>(); /// /// Gets or sets the headers values collected by the from the current request diff --git a/src/Middleware/HttpLogging/src/RequestBufferingStream.cs b/src/Middleware/HttpLogging/src/RequestBufferingStream.cs index 7165f355a278..07b5688c9f99 100644 --- a/src/Middleware/HttpLogging/src/RequestBufferingStream.cs +++ b/src/Middleware/HttpLogging/src/RequestBufferingStream.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.HttpLogging { internal sealed class RequestBufferingStream : BufferingStream { - private Encoding _encoding; + private readonly Encoding _encoding; private readonly int _limit; public bool HasLogged { get; private set; } diff --git a/src/Middleware/HttpLogging/test/W3CLoggerTests.cs b/src/Middleware/HttpLogging/test/W3CLoggerTests.cs index 5e8539e71896..6d6d2b329ceb 100644 --- a/src/Middleware/HttpLogging/test/W3CLoggerTests.cs +++ b/src/Middleware/HttpLogging/test/W3CLoggerTests.cs @@ -19,8 +19,7 @@ namespace Microsoft.AspNetCore.HttpLogging { public class W3CLoggerTests { - - DateTime _timestampOne = new DateTime(2021, 01, 02, 03, 04, 05); + readonly DateTime _timestampOne = new DateTime(2021, 01, 02, 03, 04, 05); [Fact] public async Task WritesDateTime() diff --git a/src/Middleware/HttpOverrides/src/CertificateForwardingFeature.cs b/src/Middleware/HttpOverrides/src/CertificateForwardingFeature.cs index f5abc1e59c41..280177d8deb7 100644 --- a/src/Middleware/HttpOverrides/src/CertificateForwardingFeature.cs +++ b/src/Middleware/HttpOverrides/src/CertificateForwardingFeature.cs @@ -13,9 +13,9 @@ namespace Microsoft.AspNetCore.HttpOverrides { internal class CertificateForwardingFeature : ITlsConnectionFeature { - private ILogger _logger; - private StringValues _header; - private CertificateForwardingOptions _options; + private readonly ILogger _logger; + private readonly StringValues _header; + private readonly CertificateForwardingOptions _options; private X509Certificate2? _certificate; public CertificateForwardingFeature(ILogger logger, StringValues header, CertificateForwardingOptions options) diff --git a/src/Middleware/HttpOverrides/src/LoggingExtensions.cs b/src/Middleware/HttpOverrides/src/LoggingExtensions.cs index 61f2f1b51fe9..e713f7e7ece7 100644 --- a/src/Middleware/HttpOverrides/src/LoggingExtensions.cs +++ b/src/Middleware/HttpOverrides/src/LoggingExtensions.cs @@ -7,7 +7,7 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _noCertificate; + private static readonly Action _noCertificate; static LoggingExtensions() { diff --git a/src/Middleware/ResponseCaching/test/SegmentWriteStreamTests.cs b/src/Middleware/ResponseCaching/test/SegmentWriteStreamTests.cs index 251b7e8777d6..03706ab121c3 100644 --- a/src/Middleware/ResponseCaching/test/SegmentWriteStreamTests.cs +++ b/src/Middleware/ResponseCaching/test/SegmentWriteStreamTests.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.ResponseCaching.Tests { public class SegmentWriteStreamTests { - private static byte[] WriteData = new byte[] + private static readonly byte[] WriteData = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }; diff --git a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs index 1632d16c6524..8c60d8540f84 100644 --- a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs +++ b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs @@ -1326,7 +1326,7 @@ public EncodingTestData(string encodingName, int expectedBodyLength) private class NoSyncWrapperStream : Stream { - private Stream _body; + private readonly Stream _body; public NoSyncWrapperStream(Stream body) { diff --git a/src/Middleware/Rewrite/src/ApacheModRewrite/RuleBuilder.cs b/src/Middleware/Rewrite/src/ApacheModRewrite/RuleBuilder.cs index ab7e50d681f9..b09b82d641a2 100644 --- a/src/Middleware/Rewrite/src/ApacheModRewrite/RuleBuilder.cs +++ b/src/Middleware/Rewrite/src/ApacheModRewrite/RuleBuilder.cs @@ -17,7 +17,7 @@ internal class RuleBuilder private IList? _conditions; internal IList _actions = new List(); private UrlMatch? _match; - private CookieActionFactory _cookieActionFactory = new CookieActionFactory(); + private readonly CookieActionFactory _cookieActionFactory = new CookieActionFactory(); private readonly TimeSpan _regexTimeout = TimeSpan.FromSeconds(1); diff --git a/src/Middleware/Rewrite/src/BackReferenceCollection.cs b/src/Middleware/Rewrite/src/BackReferenceCollection.cs index 439946129b4b..602942de752e 100644 --- a/src/Middleware/Rewrite/src/BackReferenceCollection.cs +++ b/src/Middleware/Rewrite/src/BackReferenceCollection.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Rewrite { internal class BackReferenceCollection { - private List _backReferences = new List(); + private readonly List _backReferences = new List(); public BackReferenceCollection(GroupCollection references) { diff --git a/src/Middleware/Session/src/DistributedSession.cs b/src/Middleware/Session/src/DistributedSession.cs index 356fb4464695..f3839f009e8f 100644 --- a/src/Middleware/Session/src/DistributedSession.cs +++ b/src/Middleware/Session/src/DistributedSession.cs @@ -35,7 +35,7 @@ public class DistributedSession : ISession private bool _isModified; private bool _loaded; private bool _isAvailable; - private bool _isNewSessionKey; + private readonly bool _isNewSessionKey; private string? _sessionId; private byte[]? _sessionIdBytes; diff --git a/src/Middleware/Session/src/LoggingExtensions.cs b/src/Middleware/Session/src/LoggingExtensions.cs index 2d36b21c129c..b103ba37a4c0 100644 --- a/src/Middleware/Session/src/LoggingExtensions.cs +++ b/src/Middleware/Session/src/LoggingExtensions.cs @@ -7,19 +7,19 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _errorClosingTheSession; - private static Action _accessingExpiredSession; - private static Action _sessionStarted; - private static Action _sessionLoaded; - private static Action _sessionStored; - private static Action _sessionCacheReadException; - private static Action _errorUnprotectingCookie; - private static Action _sessionLoadingTimeout; - private static Action _sessionCommitTimeout; - private static Action _sessionCommitCanceled; - private static Action _sessionRefreshTimeout; - private static Action _sessionRefreshCanceled; - private static Action _sessionNotAvailable; + private static readonly Action _errorClosingTheSession; + private static readonly Action _accessingExpiredSession; + private static readonly Action _sessionStarted; + private static readonly Action _sessionLoaded; + private static readonly Action _sessionStored; + private static readonly Action _sessionCacheReadException; + private static readonly Action _errorUnprotectingCookie; + private static readonly Action _sessionLoadingTimeout; + private static readonly Action _sessionCommitTimeout; + private static readonly Action _sessionCommitCanceled; + private static readonly Action _sessionRefreshTimeout; + private static readonly Action _sessionRefreshCanceled; + private static readonly Action _sessionNotAvailable; static LoggingExtensions() { diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliBuilder.cs b/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliBuilder.cs index f23382691f1a..8be7bbfa2267 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliBuilder.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliBuilder.cs @@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.SpaServices.AngularCli [Obsolete("Prerendering is no longer supported out of box")] public class AngularCliBuilder : ISpaPrerendererBuilder { - private static TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine + private static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine private readonly string _scriptName; diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddleware.cs b/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddleware.cs index 159531b6c7b6..cc89d6b492a2 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddleware.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddleware.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.SpaServices.AngularCli internal static class AngularCliMiddleware { private const string LogCategoryName = "Microsoft.AspNetCore.SpaServices"; - private static TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine + private static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine public static void Attach( ISpaBuilder spaBuilder, diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/Npm/NodeScriptRunner.cs b/src/Middleware/Spa/SpaServices.Extensions/src/Npm/NodeScriptRunner.cs index 60a4ae6f96b3..49766eaf9ae8 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/Npm/NodeScriptRunner.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/Npm/NodeScriptRunner.cs @@ -22,7 +22,7 @@ internal class NodeScriptRunner : IDisposable public EventedStreamReader StdOut { get; } public EventedStreamReader StdErr { get; } - private static Regex AnsiColorRegex = new Regex("\x001b\\[[0-9;]*m", RegexOptions.None, TimeSpan.FromSeconds(1)); + private static readonly Regex AnsiColorRegex = new Regex("\x001b\\[[0-9;]*m", RegexOptions.None, TimeSpan.FromSeconds(1)); public NodeScriptRunner(string workingDirectory, string scriptName, string? arguments, IDictionary? envVars, string pkgManagerCommand, DiagnosticSource diagnosticSource, CancellationToken applicationStoppingToken) { diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddleware.cs b/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddleware.cs index 59248e271ebb..ecb6fc7e4ac8 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddleware.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddleware.cs @@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer internal static class ReactDevelopmentServerMiddleware { private const string LogCategoryName = "Microsoft.AspNetCore.SpaServices"; - private static TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine + private static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine public static void Attach( ISpaBuilder spaBuilder, diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs b/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs index b28dac6fa575..cdd2ac8c3cfa 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs @@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.SpaServices.StaticFiles /// internal class DefaultSpaStaticFileProvider : ISpaStaticFileProvider { - private IFileProvider? _fileProvider; + private readonly IFileProvider? _fileProvider; public DefaultSpaStaticFileProvider( IServiceProvider serviceProvider, diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/Util/EventedStreamStringReader.cs b/src/Middleware/Spa/SpaServices.Extensions/src/Util/EventedStreamStringReader.cs index efe7c72efa26..d69d236ad853 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/Util/EventedStreamStringReader.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/Util/EventedStreamStringReader.cs @@ -12,9 +12,9 @@ namespace Microsoft.AspNetCore.NodeServices.Util /// internal class EventedStreamStringReader : IDisposable { - private EventedStreamReader _eventedStreamReader; + private readonly EventedStreamReader _eventedStreamReader; private bool _isDisposed; - private StringBuilder _stringBuilder = new StringBuilder(); + private readonly StringBuilder _stringBuilder = new StringBuilder(); public EventedStreamStringReader(EventedStreamReader eventedStreamReader) { diff --git a/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/AutobahnExpectations.cs b/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/AutobahnExpectations.cs index ea0667cf7783..f1dbf67495a3 100644 --- a/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/AutobahnExpectations.cs +++ b/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/AutobahnExpectations.cs @@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.WebSockets.ConformanceTest.Autobahn { public class AutobahnExpectations { - private Dictionary _expectations = new Dictionary(); + private readonly Dictionary _expectations = new Dictionary(); public bool Ssl { get; } public ServerType Server { get; } public string Environment { get; } diff --git a/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Wstest.cs b/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Wstest.cs index 775b00d4ab17..f02f23b231d4 100644 --- a/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Wstest.cs +++ b/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Wstest.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.WebSockets.ConformanceTest.Autobahn /// public class Wstest : Executable { - private static Lazy _instance = new Lazy(Create); + private static readonly Lazy _instance = new Lazy(Create); public static readonly string DefaultLocation = LocateWstest(); diff --git a/src/Middleware/WebSockets/test/UnitTests/BufferStream.cs b/src/Middleware/WebSockets/test/UnitTests/BufferStream.cs index ce7fd2f411b1..5f18539bdf1f 100644 --- a/src/Middleware/WebSockets/test/UnitTests/BufferStream.cs +++ b/src/Middleware/WebSockets/test/UnitTests/BufferStream.cs @@ -18,10 +18,10 @@ public class BufferStream : Stream private bool _aborted; private bool _terminated; private Exception _abortException; - private ConcurrentQueue _bufferedData; + private readonly ConcurrentQueue _bufferedData; private ArraySegment _topBuffer; - private SemaphoreSlim _readLock; - private SemaphoreSlim _writeLock; + private readonly SemaphoreSlim _readLock; + private readonly SemaphoreSlim _writeLock; private TaskCompletionSource _readWaitingForData; internal BufferStream() @@ -165,7 +165,7 @@ public override int EndRead(IAsyncResult asyncResult) return base.EndRead(asyncResult); } - public async override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (_terminated) { diff --git a/src/Middleware/perf/Microbenchmarks/HandshakeBenchmark.cs b/src/Middleware/perf/Microbenchmarks/HandshakeBenchmark.cs index ba736578b090..9e2872475553 100644 --- a/src/Middleware/perf/Microbenchmarks/HandshakeBenchmark.cs +++ b/src/Middleware/perf/Microbenchmarks/HandshakeBenchmark.cs @@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.WebSockets.Microbenchmarks { public class HandshakeBenchmark { - private string[] _requestKeys = { + private readonly string[] _requestKeys = { "F8/qpj9RYr2/sIymdDvlmw==", "PyQi8nyMkKnI7JKiAJ/IrA==", "CUe0z8ItSBRtgJlPqP1+SQ==", diff --git a/src/Mvc/Mvc.Analyzers/test/AvoidHtmlPartialAnalyzerTest.cs b/src/Mvc/Mvc.Analyzers/test/AvoidHtmlPartialAnalyzerTest.cs index cac606e97cde..98bc7807155c 100644 --- a/src/Mvc/Mvc.Analyzers/test/AvoidHtmlPartialAnalyzerTest.cs +++ b/src/Mvc/Mvc.Analyzers/test/AvoidHtmlPartialAnalyzerTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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.Runtime.CompilerServices; @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Mvc.Analyzers { public class AvoidHtmlPartialAnalyzerTest { - private static DiagnosticDescriptor DiagnosticDescriptor = DiagnosticDescriptors.MVC1000_HtmlHelperPartialShouldBeAvoided; + private static readonly DiagnosticDescriptor DiagnosticDescriptor = DiagnosticDescriptors.MVC1000_HtmlHelperPartialShouldBeAvoided; private MvcDiagnosticAnalyzerRunner Executor { get; } = new MvcDiagnosticAnalyzerRunner(new AvoidHtmlPartialAnalyzer()); diff --git a/src/Mvc/Mvc.Analyzers/test/Mvc.Analyzers.Test.csproj b/src/Mvc/Mvc.Analyzers/test/Mvc.Analyzers.Test.csproj index 0d2fecc2724b..f6b53b9ce7e4 100644 --- a/src/Mvc/Mvc.Analyzers/test/Mvc.Analyzers.Test.csproj +++ b/src/Mvc/Mvc.Analyzers/test/Mvc.Analyzers.Test.csproj @@ -1,9 +1,10 @@ - + $(DefaultNetCoreTargetFramework) true Microsoft.AspNetCore.Mvc.Analyzers + false diff --git a/src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs b/src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs index 1b4b93e2686f..14c92815126c 100644 --- a/src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs +++ b/src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs @@ -1953,7 +1953,7 @@ public void A() private class ApiExplorerIsVisibleConvention : IApplicationModelConvention { - private bool _isVisible; + private readonly bool _isVisible; public ApiExplorerIsVisibleConvention(bool isVisible) { diff --git a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs index 0ddfbe40e5ae..ce90ff26bcdb 100644 --- a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs +++ b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs @@ -345,7 +345,7 @@ private static IServiceCollection CreateServices() private class MockControllerFactory { - private object _controller; + private readonly object _controller; public MockControllerFactory(object controller) { @@ -415,7 +415,7 @@ public TestControllerActionInvoker( public MockControllerFactory ControllerFactory { get; } - public async override Task InvokeAsync() + public override async Task InvokeAsync() { await base.InvokeAsync(); diff --git a/src/Mvc/Mvc.Core/test/ModelBinding/Validation/DefaultComplexObjectValidationStrategyTest.cs b/src/Mvc/Mvc.Core/test/ModelBinding/Validation/DefaultComplexObjectValidationStrategyTest.cs index ed4cb6ad4280..bf565f90ad9e 100644 --- a/src/Mvc/Mvc.Core/test/ModelBinding/Validation/DefaultComplexObjectValidationStrategyTest.cs +++ b/src/Mvc/Mvc.Core/test/ModelBinding/Validation/DefaultComplexObjectValidationStrategyTest.cs @@ -141,7 +141,7 @@ private class Person private class LazyPerson { - private string _string; + private readonly string _string; public LazyPerson(string input) { diff --git a/src/Mvc/Mvc.Core/test/Routing/ActionEndpointDataSourceBaseTest.cs b/src/Mvc/Mvc.Core/test/Routing/ActionEndpointDataSourceBaseTest.cs index c620abf1612c..9371c6592e41 100644 --- a/src/Mvc/Mvc.Core/test/Routing/ActionEndpointDataSourceBaseTest.cs +++ b/src/Mvc/Mvc.Core/test/Routing/ActionEndpointDataSourceBaseTest.cs @@ -128,7 +128,7 @@ public void Endpoints_ChangeTokenTriggered_EndpointsRecreated() }); } - protected private ActionEndpointDataSourceBase CreateDataSource(IActionDescriptorCollectionProvider actions = null) + private protected ActionEndpointDataSourceBase CreateDataSource(IActionDescriptorCollectionProvider actions = null) { if (actions == null) { @@ -154,7 +154,7 @@ protected private ActionEndpointDataSourceBase CreateDataSource(IActionDescripto return CreateDataSource(actions, endpointFactory); } - protected private abstract ActionEndpointDataSourceBase CreateDataSource(IActionDescriptorCollectionProvider actions, ActionEndpointFactory endpointFactory); + private protected abstract ActionEndpointDataSourceBase CreateDataSource(IActionDescriptorCollectionProvider actions, ActionEndpointFactory endpointFactory); private class UpperCaseParameterTransform : IOutboundParameterTransformer { diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs index 793bbe014e59..2238175d8939 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs @@ -61,7 +61,7 @@ public override InputFormatterExceptionPolicy ExceptionPolicy } /// - public async override Task ReadRequestBodyAsync( + public override async Task ReadRequestBodyAsync( InputFormatterContext context, Encoding encoding) { diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectItem.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectItem.cs index 935921c90c8a..506e8c8f74de 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectItem.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectItem.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation /// public class FileProviderRazorProjectItem : RazorProjectItem { - private string _root; + private readonly string _root; private string? _relativePhysicalPath; private bool _isRelativePhysicalPathSet; diff --git a/src/Mvc/Mvc.Razor/test/TagHelpers/TagHelperComponentTagHelperTest.cs b/src/Mvc/Mvc.Razor/test/TagHelpers/TagHelperComponentTagHelperTest.cs index 80741ef6cd7b..66bca4062fa4 100644 --- a/src/Mvc/Mvc.Razor/test/TagHelpers/TagHelperComponentTagHelperTest.cs +++ b/src/Mvc/Mvc.Razor/test/TagHelpers/TagHelperComponentTagHelperTest.cs @@ -368,7 +368,7 @@ public Task ProcessAsync(TagHelperContext context, TagHelperOutput output) private class TestAddTagHelperComponent : ITagHelperComponent { - private int _order; + private readonly int _order; public TestAddTagHelperComponent(int order) { diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs index 2bec75388751..f16a8b18fa0f 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.ApplicationModels /// public class PageRouteTransformerConvention : IPageRouteModelConvention { - private IOutboundParameterTransformer _parameterTransformer; + private readonly IOutboundParameterTransformer _parameterTransformer; /// /// Creates a new instance of with the specified . diff --git a/src/Mvc/Mvc.RazorPages/src/PageContext.cs b/src/Mvc/Mvc.RazorPages/src/PageContext.cs index 2ca4ad8280ba..3f6f827bd828 100644 --- a/src/Mvc/Mvc.RazorPages/src/PageContext.cs +++ b/src/Mvc/Mvc.RazorPages/src/PageContext.cs @@ -41,7 +41,7 @@ public PageContext(ActionContext actionContext) /// /// Gets or sets the . /// - public virtual new CompiledPageActionDescriptor ActionDescriptor + public new virtual CompiledPageActionDescriptor ActionDescriptor { get => _actionDescriptor!; set diff --git a/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs index d9cebc65dfec..c8ae79793756 100644 --- a/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs @@ -83,7 +83,7 @@ public RenderMode RenderMode } /// - public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (context == null) { diff --git a/src/Mvc/Mvc.TagHelpers/test/TestableHtmlGenerator.cs b/src/Mvc/Mvc.TagHelpers/test/TestableHtmlGenerator.cs index 174240d203f6..ade416916a8f 100644 --- a/src/Mvc/Mvc.TagHelpers/test/TestableHtmlGenerator.cs +++ b/src/Mvc/Mvc.TagHelpers/test/TestableHtmlGenerator.cs @@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.Mvc.TagHelpers { public class TestableHtmlGenerator : DefaultHtmlGenerator { - private IDictionary _validationAttributes; + private readonly IDictionary _validationAttributes; public TestableHtmlGenerator(IModelMetadataProvider metadataProvider) : this(metadataProvider, Mock.Of()) diff --git a/src/Mvc/Mvc.TagHelpers/test/ValidationSummaryTagHelperTest.cs b/src/Mvc/Mvc.TagHelpers/test/ValidationSummaryTagHelperTest.cs index cba2243af436..194633d8f7d2 100644 --- a/src/Mvc/Mvc.TagHelpers/test/ValidationSummaryTagHelperTest.cs +++ b/src/Mvc/Mvc.TagHelpers/test/ValidationSummaryTagHelperTest.cs @@ -694,7 +694,7 @@ private class Model private class FormMetadata : IEnumerable { - private List _fields = new List(); + private readonly List _fields = new List(); public int ID { get; set; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/StaticComponentRenderer.cs b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/StaticComponentRenderer.cs index 8f620d4c5487..b256bb4cc00d 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/StaticComponentRenderer.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/StaticComponentRenderer.cs @@ -18,8 +18,8 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures internal class StaticComponentRenderer { private Task _initialized; - private HtmlRenderer _renderer; - private object _lock = new(); + private readonly HtmlRenderer _renderer; + private readonly object _lock = new(); public StaticComponentRenderer(HtmlRenderer renderer) { diff --git a/src/Mvc/Mvc.ViewFeatures/test/CookieTempDataProviderTest.cs b/src/Mvc/Mvc.ViewFeatures/test/CookieTempDataProviderTest.cs index db0d0e3a8a25..8cfd3dbe88e5 100644 --- a/src/Mvc/Mvc.ViewFeatures/test/CookieTempDataProviderTest.cs +++ b/src/Mvc/Mvc.ViewFeatures/test/CookieTempDataProviderTest.cs @@ -370,7 +370,7 @@ private void UpdateRequestWithCookies(HttpContext httpContext) private class MockResponseCookieCollection : IResponseCookies, IEnumerable { - private Dictionary _cookies = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _cookies = new Dictionary(StringComparer.OrdinalIgnoreCase); public int Count { diff --git a/src/Mvc/Mvc.ViewFeatures/test/RazorComponents/ComponentRendererTest.cs b/src/Mvc/Mvc.ViewFeatures/test/RazorComponents/ComponentRendererTest.cs index b7b364fc29a7..ad98ad233585 100644 --- a/src/Mvc/Mvc.ViewFeatures/test/RazorComponents/ComponentRendererTest.cs +++ b/src/Mvc/Mvc.ViewFeatures/test/RazorComponents/ComponentRendererTest.cs @@ -1012,7 +1012,7 @@ protected override void BuildRenderTree(RenderTreeBuilder builder) private class AsyncComponent : ComponentBase { - private static WeatherRow[] _weatherData = new[] + private static readonly WeatherRow[] _weatherData = new[] { new WeatherRow { diff --git a/src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperNameExtensionsTest.cs b/src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperNameExtensionsTest.cs index 25d43e0fe039..e419a43cfb92 100644 --- a/src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperNameExtensionsTest.cs +++ b/src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperNameExtensionsTest.cs @@ -18,13 +18,13 @@ namespace Microsoft.AspNetCore.Mvc.Core /// public class HtmlHelperNameExtensionsTest { - private static List _staticCollection = new List(); - private static int _staticIndex = 6; + private static readonly List _staticCollection = new List(); + private static readonly int _staticIndex = 6; - private List _collection = new List(); - private int _index = 7; - private List _nestedCollection = new List(); - private string _string = string.Empty; + private readonly List _collection = new List(); + private readonly int _index = 7; + private readonly List _nestedCollection = new List(); + private readonly string _string = string.Empty; private static List StaticCollection { get; } diff --git a/src/Mvc/Mvc.ViewFeatures/test/SessionStateTempDataProviderTest.cs b/src/Mvc/Mvc.ViewFeatures/test/SessionStateTempDataProviderTest.cs index 47db8ef2bc1e..778b225e9b25 100644 --- a/src/Mvc/Mvc.ViewFeatures/test/SessionStateTempDataProviderTest.cs +++ b/src/Mvc/Mvc.ViewFeatures/test/SessionStateTempDataProviderTest.cs @@ -104,7 +104,7 @@ private class SessionFeature : ISessionFeature private class TestSession : ISession { - private Dictionary _innerDictionary = new Dictionary(); + private readonly Dictionary _innerDictionary = new Dictionary(); public IEnumerable Keys { get { return _innerDictionary.Keys; } } diff --git a/src/Mvc/Mvc.ViewFeatures/test/TempDataDictionaryTest.cs b/src/Mvc/Mvc.ViewFeatures/test/TempDataDictionaryTest.cs index cf16b46aac4e..efaf67473018 100644 --- a/src/Mvc/Mvc.ViewFeatures/test/TempDataDictionaryTest.cs +++ b/src/Mvc/Mvc.ViewFeatures/test/TempDataDictionaryTest.cs @@ -194,7 +194,7 @@ public void SaveTempData(HttpContext context, IDictionary values private class TestTempDataProvider : ITempDataProvider { - private IDictionary _data; + private readonly IDictionary _data; public TestTempDataProvider(IDictionary data) { diff --git a/src/Mvc/Mvc.ViewFeatures/test/ViewComponentTests.cs b/src/Mvc/Mvc.ViewFeatures/test/ViewComponentTests.cs index 05a99dbb164b..8c91ab5e0516 100644 --- a/src/Mvc/Mvc.ViewFeatures/test/ViewComponentTests.cs +++ b/src/Mvc/Mvc.ViewFeatures/test/ViewComponentTests.cs @@ -270,7 +270,7 @@ private class SessionFeature : ISessionFeature private class TestSession : ISession { - private Dictionary _innerDictionary = new Dictionary(); + private readonly Dictionary _innerDictionary = new Dictionary(); public IEnumerable Keys { get { return _innerDictionary.Keys; } } diff --git a/src/Mvc/shared/Mvc.Core.TestCommon/NonSeekableReadableStream.cs b/src/Mvc/shared/Mvc.Core.TestCommon/NonSeekableReadableStream.cs index 62be4fc02b7b..8dcb8043bf27 100644 --- a/src/Mvc/shared/Mvc.Core.TestCommon/NonSeekableReadableStream.cs +++ b/src/Mvc/shared/Mvc.Core.TestCommon/NonSeekableReadableStream.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Mvc { public class NonSeekableReadStream : Stream { - private Stream _inner; + private readonly Stream _inner; private readonly bool _allowSyncReads; public NonSeekableReadStream(byte[] data, bool allowSyncReads = true) diff --git a/src/Mvc/shared/Mvc.Core.TestCommon/TestModelMetadataProvider.cs b/src/Mvc/shared/Mvc.Core.TestCommon/TestModelMetadataProvider.cs index 43aa7e1d2817..636c2234f601 100644 --- a/src/Mvc/shared/Mvc.Core.TestCommon/TestModelMetadataProvider.cs +++ b/src/Mvc/shared/Mvc.Core.TestCommon/TestModelMetadataProvider.cs @@ -186,9 +186,9 @@ public interface IMetadataBuilder private class MetadataBuilder : IMetadataBuilder { - private List> _bindingActions = new List>(); - private List> _displayActions = new List>(); - private List> _validationActions = new List>(); + private readonly List> _bindingActions = new List>(); + private readonly List> _displayActions = new List>(); + private readonly List> _validationActions = new List>(); private readonly ModelMetadataIdentity _key; diff --git a/src/Mvc/test/Mvc.FunctionalTests/ConsumesAttributeEndpointRoutingTests.cs b/src/Mvc/test/Mvc.FunctionalTests/ConsumesAttributeEndpointRoutingTests.cs index 2165e03f8338..b1fbc55077a0 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/ConsumesAttributeEndpointRoutingTests.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/ConsumesAttributeEndpointRoutingTests.cs @@ -16,7 +16,7 @@ public ConsumesAttributeEndpointRoutingTests(MvcTestFixture public static readonly bool GenerateBaselines = false; - private static object writeLock = new object(); + private static readonly object writeLock = new object(); public static void UpdateOrVerify(Assembly assembly, string outputFile, string expectedContent, string responseContent, string token = null) { diff --git a/src/Mvc/test/Mvc.FunctionalTests/RequestServicesEndpointRoutingTest.cs b/src/Mvc/test/Mvc.FunctionalTests/RequestServicesEndpointRoutingTest.cs index e386705bc060..e61ce738458d 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/RequestServicesEndpointRoutingTest.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/RequestServicesEndpointRoutingTest.cs @@ -17,7 +17,7 @@ public RequestServicesEndpointRoutingTest(MvcTestFixture f } [Fact] - public async override Task HasEndpointMatch() + public override async Task HasEndpointMatch() { // Arrange & Act var response = await Client.GetAsync("http://localhost/Routing/HasEndpointMatch"); diff --git a/src/Mvc/test/Mvc.FunctionalTests/RequestServicesTest.cs b/src/Mvc/test/Mvc.FunctionalTests/RequestServicesTest.cs index 31f2843fb490..dbb89b33c552 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/RequestServicesTest.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/RequestServicesTest.cs @@ -16,7 +16,7 @@ public RequestServicesTest(MvcTestFixture } [Fact] - public async override Task HasEndpointMatch() + public override async Task HasEndpointMatch() { // Arrange & Act var response = await Client.GetAsync("http://localhost/Routing/HasEndpointMatch"); @@ -47,7 +47,7 @@ public override async Task AttributeRoutedAction_MultipleRouteAttributes_RouteAt } [Fact] - public async override Task RouteData_Routers_ConventionalRoute() + public override async Task RouteData_Routers_ConventionalRoute() { // Arrange & Act var response = await Client.GetAsync("http://localhost/RouteData/Conventional"); @@ -69,7 +69,7 @@ public async override Task RouteData_Routers_ConventionalRoute() } [Fact] - public async override Task RouteData_Routers_AttributeRoute() + public override async Task RouteData_Routers_AttributeRoute() { // Arrange & Act var response = await Client.GetAsync("http://localhost/RouteData/Attribute"); diff --git a/src/Mvc/test/Mvc.FunctionalTests/VersioningEndpointRoutingTests.cs b/src/Mvc/test/Mvc.FunctionalTests/VersioningEndpointRoutingTests.cs index 890fcce2fc83..50564a05ad89 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/VersioningEndpointRoutingTests.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/VersioningEndpointRoutingTests.cs @@ -17,7 +17,7 @@ public VersioningEndpointRoutingTests(MvcTestFixture } [Fact] - public async override Task HasEndpointMatch() + public override async Task HasEndpointMatch() { // Arrange & Act var response = await Client.GetAsync("http://localhost/Routing/HasEndpointMatch"); diff --git a/src/Mvc/test/Mvc.FunctionalTests/VersioningTests.cs b/src/Mvc/test/Mvc.FunctionalTests/VersioningTests.cs index 4efc0561a4c8..94d3b075d37f 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/VersioningTests.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/VersioningTests.cs @@ -16,7 +16,7 @@ public VersioningTests(MvcTestFixture : ICollection { - private ICollection _original; + private readonly ICollection _original; public CustomReadOnlyCollection() : this(new List()) diff --git a/src/Mvc/test/Mvc.IntegrationTests/ComplexRecordIntegrationTest.cs b/src/Mvc/test/Mvc.IntegrationTests/ComplexRecordIntegrationTest.cs index f533be281214..14448ce988d9 100644 --- a/src/Mvc/test/Mvc.IntegrationTests/ComplexRecordIntegrationTest.cs +++ b/src/Mvc/test/Mvc.IntegrationTests/ComplexRecordIntegrationTest.cs @@ -3028,7 +3028,7 @@ private record TestInnerModel([ModelBinder(BinderType = typeof(NumberModelBinder private class NumberModelBinder : IModelBinder { private readonly NumberStyles _supportedStyles = NumberStyles.Float | NumberStyles.AllowThousands; - private DecimalModelBinder _innerBinder; + private readonly DecimalModelBinder _innerBinder; public NumberModelBinder(ILoggerFactory loggerFactory) { diff --git a/src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs b/src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs index b2ffbcc4c4e2..ed18ca10a706 100644 --- a/src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs +++ b/src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs @@ -3243,7 +3243,7 @@ private class TestInnerModel private class NumberModelBinder : IModelBinder { private readonly NumberStyles _supportedStyles = NumberStyles.Float | NumberStyles.AllowThousands; - private DecimalModelBinder _innerBinder; + private readonly DecimalModelBinder _innerBinder; public NumberModelBinder(ILoggerFactory loggerFactory) { diff --git a/src/Mvc/test/Mvc.IntegrationTests/TryUpdateModelIntegrationTest.cs b/src/Mvc/test/Mvc.IntegrationTests/TryUpdateModelIntegrationTest.cs index 1e5ebffeaf87..64c13b17e2f2 100644 --- a/src/Mvc/test/Mvc.IntegrationTests/TryUpdateModelIntegrationTest.cs +++ b/src/Mvc/test/Mvc.IntegrationTests/TryUpdateModelIntegrationTest.cs @@ -1296,7 +1296,7 @@ private void UpdateRequest(HttpRequest request, string data, string name) private class CustomReadOnlyCollection : ICollection { - private ICollection _original; + private readonly ICollection _original; public CustomReadOnlyCollection() : this(new List()) diff --git a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ActionDescriptionAttribute.cs b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ActionDescriptionAttribute.cs index 1056bddb1eaa..07df2be3ec04 100644 --- a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ActionDescriptionAttribute.cs +++ b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ActionDescriptionAttribute.cs @@ -9,7 +9,7 @@ namespace ApplicationModelWebSite { public class ActionDescriptionAttribute : Attribute, IActionModelConvention { - private object _value; + private readonly object _value; public ActionDescriptionAttribute(object value) { diff --git a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ApplicationDescription.cs b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ApplicationDescription.cs index 39f982706301..69835063769a 100644 --- a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ApplicationDescription.cs +++ b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ApplicationDescription.cs @@ -8,7 +8,7 @@ namespace ApplicationModelWebSite { public class ApplicationDescription : IApplicationModelConvention { - private string _description; + private readonly string _description; public ApplicationDescription(string description) { diff --git a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ControllerDescriptionAttribute.cs b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ControllerDescriptionAttribute.cs index 20109b08ad71..8a1e98647d34 100644 --- a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ControllerDescriptionAttribute.cs +++ b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ControllerDescriptionAttribute.cs @@ -8,7 +8,7 @@ namespace ApplicationModelWebSite { public class ControllerDescriptionAttribute : Attribute, IControllerModelConvention { - private object _value; + private readonly object _value; public ControllerDescriptionAttribute(object value) { diff --git a/src/Mvc/test/WebSites/BasicWebSite/Controllers/AsyncActionsController.cs b/src/Mvc/test/WebSites/BasicWebSite/Controllers/AsyncActionsController.cs index b9a5b688535b..a870daab5167 100644 --- a/src/Mvc/test/WebSites/BasicWebSite/Controllers/AsyncActionsController.cs +++ b/src/Mvc/test/WebSites/BasicWebSite/Controllers/AsyncActionsController.cs @@ -199,7 +199,7 @@ public CustomAwaitable(int simulateDelayMilliseconds, T result) public class CustomAwaiter : INotifyCompletion { - private IList _continuations = new List(); + private readonly IList _continuations = new List(); public CustomAwaiter(int simulateDelayMilliseconds) { diff --git a/src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs b/src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs index 2af557a16075..6b094048387c 100644 --- a/src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs +++ b/src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs @@ -8,7 +8,7 @@ namespace BasicWebSite.Controllers { public class RazorComponentsController : Controller { - private static WeatherRow[] _weatherData = new[] + private static readonly WeatherRow[] _weatherData = new[] { new WeatherRow { diff --git a/src/Mvc/test/WebSites/BasicWebSite/Controllers/TestingController.cs b/src/Mvc/test/WebSites/BasicWebSite/Controllers/TestingController.cs index 167d29e89dfd..bf9a2cf5c535 100644 --- a/src/Mvc/test/WebSites/BasicWebSite/Controllers/TestingController.cs +++ b/src/Mvc/test/WebSites/BasicWebSite/Controllers/TestingController.cs @@ -72,8 +72,8 @@ public IActionResult RedirectHandlerStatusCode303() public class RedirectUsingStatusCode : ActionResult { - private string _url; - private HttpStatusCode _statusCode; + private readonly string _url; + private readonly HttpStatusCode _statusCode; public RedirectUsingStatusCode(string url, HttpStatusCode statusCode) { diff --git a/src/Mvc/test/WebSites/BasicWebSite/Conventions/ApplicationDescription.cs b/src/Mvc/test/WebSites/BasicWebSite/Conventions/ApplicationDescription.cs index 88bf1f27e2ee..682eefac88fc 100644 --- a/src/Mvc/test/WebSites/BasicWebSite/Conventions/ApplicationDescription.cs +++ b/src/Mvc/test/WebSites/BasicWebSite/Conventions/ApplicationDescription.cs @@ -7,7 +7,7 @@ namespace BasicWebSite { public class ApplicationDescription : IApplicationModelConvention { - private string _description; + private readonly string _description; public ApplicationDescription(string description) { diff --git a/src/Mvc/test/WebSites/ControllersFromServicesWebSite/TagHelpers/InServicesTagHelper.cs b/src/Mvc/test/WebSites/ControllersFromServicesWebSite/TagHelpers/InServicesTagHelper.cs index 778bb1724d9a..dcb6be2efdda 100644 --- a/src/Mvc/test/WebSites/ControllersFromServicesWebSite/TagHelpers/InServicesTagHelper.cs +++ b/src/Mvc/test/WebSites/ControllersFromServicesWebSite/TagHelpers/InServicesTagHelper.cs @@ -9,7 +9,7 @@ namespace ControllersFromServicesWebSite.TagHelpers [HtmlTargetElement("InServices")] public class InServicesTagHelper : TagHelper { - private ValueService _value; + private readonly ValueService _value; public InServicesTagHelper(ValueService value) { diff --git a/src/Mvc/test/WebSites/GenericHostWebSite/Controllers/TestingController.cs b/src/Mvc/test/WebSites/GenericHostWebSite/Controllers/TestingController.cs index b79e078d19c7..9a35c53cdbf3 100644 --- a/src/Mvc/test/WebSites/GenericHostWebSite/Controllers/TestingController.cs +++ b/src/Mvc/test/WebSites/GenericHostWebSite/Controllers/TestingController.cs @@ -72,8 +72,8 @@ public IActionResult RedirectHandlerStatusCode303() public class RedirectUsingStatusCode : ActionResult { - private string _url; - private HttpStatusCode _statusCode; + private readonly string _url; + private readonly HttpStatusCode _statusCode; public RedirectUsingStatusCode(string url, HttpStatusCode statusCode) { diff --git a/src/Mvc/test/WebSites/RazorWebSite/Services/TestBodyTagHelperComponent.cs b/src/Mvc/test/WebSites/RazorWebSite/Services/TestBodyTagHelperComponent.cs index 750dd61d20a3..f83a7b6cf1c9 100644 --- a/src/Mvc/test/WebSites/RazorWebSite/Services/TestBodyTagHelperComponent.cs +++ b/src/Mvc/test/WebSites/RazorWebSite/Services/TestBodyTagHelperComponent.cs @@ -11,8 +11,8 @@ namespace RazorWebSite { public class TestBodyTagHelperComponent : ITagHelperComponent { - private int _order; - private string _html; + private readonly int _order; + private readonly string _html; public TestBodyTagHelperComponent() : this(1, "") { diff --git a/src/Mvc/test/WebSites/VersioningWebSite/Controllers/AddressController.cs b/src/Mvc/test/WebSites/VersioningWebSite/Controllers/AddressController.cs index 245699dfa880..bd3f40ac4e18 100644 --- a/src/Mvc/test/WebSites/VersioningWebSite/Controllers/AddressController.cs +++ b/src/Mvc/test/WebSites/VersioningWebSite/Controllers/AddressController.cs @@ -10,7 +10,7 @@ namespace VersioningWebSite // Same template overlapping version sets disambiguated by order. public class AddressController : Controller { - private TestResponseGenerator _generator; + private readonly TestResponseGenerator _generator; public AddressController(TestResponseGenerator generator) { diff --git a/src/ProjectTemplates/BlazorTemplates.Tests/BlazorTemplateTest.cs b/src/ProjectTemplates/BlazorTemplates.Tests/BlazorTemplateTest.cs index 121960ee852c..de296b9d254e 100644 --- a/src/ProjectTemplates/BlazorTemplates.Tests/BlazorTemplateTest.cs +++ b/src/ProjectTemplates/BlazorTemplates.Tests/BlazorTemplateTest.cs @@ -43,12 +43,12 @@ public ITestOutputHelper Output return _output; } } - + public abstract string ProjectType { get; } private static readonly bool _isCIEnvironment = !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ContinuousIntegrationBuild")); - protected async override Task InitializeCoreAsync(TestContext context) + protected override async Task InitializeCoreAsync(TestContext context) { BrowserManager = await BrowserManager.CreateAsync(CreateConfiguration(), LoggerFactory); BrowserContextInfo = new ContextInformation(LoggerFactory); diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTagHelperPass.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTagHelperPass.cs index ba9938a1238e..91865fc75d06 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTagHelperPass.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTagHelperPass.cs @@ -146,7 +146,7 @@ private void AddTagHelperClass(Context context, TagHelperDescriptor tagHelper) private struct Context { - private Dictionary _tagHelpers; + private readonly Dictionary _tagHelpers; public Context(NamespaceDeclarationIntermediateNode @namespace, ClassDeclarationIntermediateNode @class) { diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs index 86eb6afc0ddd..e4144fe7184f 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X.IntegrationTests { public class CodeGenerationIntegrationTest : IntegrationTestBase { - private readonly static CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode"); + private static readonly CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode"); public CodeGenerationIntegrationTest() : base(generateBaselines: null, projectDirectoryHint: "Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X") diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/ModelDirectiveTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/ModelDirectiveTest.cs index 7a4c811dbdad..0cb572a8a8a8 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/ModelDirectiveTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/ModelDirectiveTest.cs @@ -320,7 +320,7 @@ public override void VisitNamespaceDeclaration(NamespaceDeclarationIntermediateN private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature { - private bool _designTime; + private readonly bool _designTime; public DesignTimeOptionsFeature(bool designTime) { diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/ViewComponentTagHelperPass.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/ViewComponentTagHelperPass.cs index f5c37eb13b08..81c21566fc2c 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/ViewComponentTagHelperPass.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/ViewComponentTagHelperPass.cs @@ -146,7 +146,7 @@ private void AddTagHelperClass(Context context, TagHelperDescriptor tagHelper) private struct Context { - private Dictionary _tagHelpers; + private readonly Dictionary _tagHelpers; public Context(NamespaceDeclarationIntermediateNode @namespace, ClassDeclarationIntermediateNode @class) { diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs index 0fa87ec5f795..5bc78e055000 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X.IntegrationTests { public class CodeGenerationIntegrationTest : IntegrationTestBase { - private readonly static CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode"); + private static readonly CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode"); public CodeGenerationIntegrationTest() : base(generateBaselines: null, projectDirectoryHint: "Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X") diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/InstrumentationPassIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/InstrumentationPassIntegrationTest.cs index 4a4e752c3735..36611468a368 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/InstrumentationPassIntegrationTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/InstrumentationPassIntegrationTest.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X.IntegrationTests { public class InstrumentationPassIntegrationTest : IntegrationTestBase { - private readonly static CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode"); + private static readonly CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode"); public InstrumentationPassIntegrationTest() : base(generateBaselines: null, projectDirectoryHint: "Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X") diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/ModelDirectiveTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/ModelDirectiveTest.cs index d01195906be4..e20876455ef4 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/ModelDirectiveTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/ModelDirectiveTest.cs @@ -318,7 +318,7 @@ public override void VisitNamespaceDeclaration(NamespaceDeclarationIntermediateN private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature { - private bool _designTime; + private readonly bool _designTime; public DesignTimeOptionsFeature(bool designTime) { diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/MvcViewDocumentClassifierPass.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/MvcViewDocumentClassifierPass.cs index 9d5c43b1ab44..91378d632ff3 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/MvcViewDocumentClassifierPass.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/MvcViewDocumentClassifierPass.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions { public class MvcViewDocumentClassifierPass : DocumentClassifierPassBase { - private bool _useConsolidatedMvcViews; + private readonly bool _useConsolidatedMvcViews; public static readonly string MvcViewDocumentKind = "mvc.1.0.view"; diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/RazorPageDocumentClassifierPass.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/RazorPageDocumentClassifierPass.cs index 06752cf93a0d..65eed6f8554b 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/RazorPageDocumentClassifierPass.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/RazorPageDocumentClassifierPass.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions { public class RazorPageDocumentClassifierPass : DocumentClassifierPassBase { - private bool _useConsolidatedMvcViews; + private readonly bool _useConsolidatedMvcViews; public static readonly string RazorPageDocumentKind = "mvc.1.0.razor-page"; public static readonly string RouteTemplateKey = "RouteTemplate"; diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/ViewComponentTagHelperPass.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/ViewComponentTagHelperPass.cs index 0c3b14563e52..9292ae75cc6b 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/ViewComponentTagHelperPass.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/ViewComponentTagHelperPass.cs @@ -146,7 +146,7 @@ private void AddTagHelperClass(Context context, TagHelperDescriptor tagHelper) private struct Context { - private Dictionary _tagHelpers; + private readonly Dictionary _tagHelpers; public Context(NamespaceDeclarationIntermediateNode @namespace, ClassDeclarationIntermediateNode @class) { diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/IntegrationTests/CodeGenerationIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/IntegrationTests/CodeGenerationIntegrationTest.cs index 3386060adb7b..edfe250ed16b 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/IntegrationTests/CodeGenerationIntegrationTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/IntegrationTests/CodeGenerationIntegrationTest.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.IntegrationTests { public class CodeGenerationIntegrationTest : IntegrationTestBase { - private readonly static CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode"); + private static readonly CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode"); public CodeGenerationIntegrationTest() : base(generateBaselines: null, projectDirectoryHint: "Microsoft.AspNetCore.Mvc.Razor.Extensions") diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/ModelDirectiveTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/ModelDirectiveTest.cs index 527120915b4f..1d807edab3c9 100644 --- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/ModelDirectiveTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/ModelDirectiveTest.cs @@ -302,7 +302,7 @@ public override void VisitNamespaceDeclaration(NamespaceDeclarationIntermediateN private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature { - private bool _designTime; + private readonly bool _designTime; public DesignTimeOptionsFeature(bool designTime) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/ClassifiedSpanVisitor.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/ClassifiedSpanVisitor.cs index f1627441309c..96544078e367 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/ClassifiedSpanVisitor.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/ClassifiedSpanVisitor.cs @@ -11,8 +11,8 @@ namespace Microsoft.AspNetCore.Razor.Language { internal class ClassifiedSpanVisitor : SyntaxWalker { - private RazorSourceDocument _source; - private List _spans; + private readonly RazorSourceDocument _source; + private readonly List _spans; private BlockKindInternal _currentBlockKind; private SyntaxNode _currentBlock; diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/CodeGeneration/CodeWriterExtensions.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/CodeGeneration/CodeWriterExtensions.cs index 734cfa49d719..c17a41af4e8e 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/CodeGeneration/CodeWriterExtensions.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/CodeGeneration/CodeWriterExtensions.cs @@ -586,9 +586,9 @@ private static void WriteCStyleStringLiteral(CodeWriter writer, string literal) public struct CSharpCodeWritingScope : IDisposable { - private CodeWriter _writer; - private bool _autoSpace; - private int _tabSize; + private readonly CodeWriter _writer; + private readonly bool _autoSpace; + private readonly int _tabSize; private int _startIndent; public CSharpCodeWritingScope(CodeWriter writer, bool autoSpace = true) 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 36a0e0da916c..5d6014e6c72f 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDuplicateAttributeDiagnosticPass.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDuplicateAttributeDiagnosticPass.cs @@ -21,7 +21,7 @@ protected override void ExecuteCore(RazorCodeDocument codeDocument, DocumentInte private class Visitor : IntermediateNodeWalker { - private Dictionary _attributes = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _attributes = new Dictionary(StringComparer.OrdinalIgnoreCase); public override void VisitMarkupElement(MarkupElementIntermediateNode node) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultDirectiveSyntaxTreePass.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultDirectiveSyntaxTreePass.cs index ae4ba4989153..563d8148da4a 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultDirectiveSyntaxTreePass.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultDirectiveSyntaxTreePass.cs @@ -27,8 +27,8 @@ public RazorSyntaxTree Execute(RazorCodeDocument codeDocument, RazorSyntaxTree s private class NestedSectionVerifier : SyntaxRewriter { private int _nestedLevel; - private RazorSyntaxTree _syntaxTree; - private List _diagnostics; + private readonly RazorSyntaxTree _syntaxTree; + private readonly List _diagnostics; public NestedSectionVerifier(RazorSyntaxTree syntaxTree) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRazorTagHelperBinderPhase.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRazorTagHelperBinderPhase.cs index 53e6c378f46f..3d9825b009f2 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRazorTagHelperBinderPhase.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRazorTagHelperBinderPhase.cs @@ -228,7 +228,7 @@ private bool AssemblyContainsTagHelpers(string assemblyName, IReadOnlyList _notFullyQualifiedComponents; - private string _filePath; + private readonly string _filePath; private RazorSourceDocument _source; public ComponentDirectiveVisitor(string filePath, IReadOnlyList tagHelpers, string currentNamespace) diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRequiredAttributeDescriptorBuilder.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRequiredAttributeDescriptorBuilder.cs index 0f68f2967721..9a642486ae50 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRequiredAttributeDescriptorBuilder.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRequiredAttributeDescriptorBuilder.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Razor.Language { internal class DefaultRequiredAttributeDescriptorBuilder : RequiredAttributeDescriptorBuilder { - private DefaultTagMatchingRuleDescriptorBuilder _parent; + private readonly DefaultTagMatchingRuleDescriptorBuilder _parent; private RazorDiagnosticCollection _diagnostics; private readonly Dictionary _metadata = new Dictionary(); diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultTagMatchingRuleDescriptorBuilder.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultTagMatchingRuleDescriptorBuilder.cs index 4c8524ccb79d..40c836f782ef 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultTagMatchingRuleDescriptorBuilder.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultTagMatchingRuleDescriptorBuilder.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Razor.Language { internal class DefaultTagMatchingRuleDescriptorBuilder : TagMatchingRuleDescriptorBuilder { - private DefaultTagHelperDescriptorBuilder _parent; + private readonly DefaultTagHelperDescriptorBuilder _parent; private List _requiredAttributeBuilders; private RazorDiagnosticCollection _diagnostics; diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/IntermediateNodeFormatterBase.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/IntermediateNodeFormatterBase.cs index 16498f2fbc6b..ce1fb6facb4f 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/IntermediateNodeFormatterBase.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/IntermediateNodeFormatterBase.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Intermediate internal class IntermediateNodeFormatterBase : IntermediateNodeFormatter { private string _content; - private Dictionary _properties = new Dictionary(StringComparer.Ordinal); + private readonly Dictionary _properties = new Dictionary(StringComparer.Ordinal); protected FormatterContentMode ContentMode { get; set; } diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs index c6f701153137..56391ea3fc33 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy { internal class CSharpCodeParser : TokenizerBackedParser { - private static HashSet InvalidNonWhitespaceNameCharacters = new HashSet(new[] + private static readonly HashSet InvalidNonWhitespaceNameCharacters = new HashSet(new[] { '@', '!', '<', '/', '?', '[', '>', ']', '=', '"', '\'', '*' }); @@ -67,8 +67,8 @@ internal class CSharpCodeParser : TokenizerBackedParser private readonly ISet CurrentKeywords = new HashSet(DefaultKeywords); - private Dictionary, CSharpTransitionSyntax>> _keywordParserMap = new Dictionary, CSharpTransitionSyntax>>(); - private Dictionary, CSharpTransitionSyntax>> _directiveParserMap = new Dictionary, CSharpTransitionSyntax>>(StringComparer.Ordinal); + private readonly Dictionary, CSharpTransitionSyntax>> _keywordParserMap = new Dictionary, CSharpTransitionSyntax>>(); + private readonly Dictionary, CSharpTransitionSyntax>> _directiveParserMap = new Dictionary, CSharpTransitionSyntax>>(StringComparer.Ordinal); public CSharpCodeParser(ParserContext context) : this(directives: Enumerable.Empty(), context: context) diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpLanguageCharacteristics.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpLanguageCharacteristics.cs index 50a07886a687..de870adb821f 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpLanguageCharacteristics.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpLanguageCharacteristics.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy { internal class CSharpLanguageCharacteristics : LanguageCharacteristics { - private static Dictionary _tokenSamples = new Dictionary() + private static readonly Dictionary _tokenSamples = new Dictionary() { { SyntaxKind.Arrow, "->" }, { SyntaxKind.Minus, "-" }, @@ -64,7 +64,7 @@ internal class CSharpLanguageCharacteristics : LanguageCharacteristics _keywordNames = new Dictionary() + private static readonly IReadOnlyDictionary _keywordNames = new Dictionary() { { CSharpKeyword.Await, "await" }, { CSharpKeyword.Abstract, "abstract" }, diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpTokenizer.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpTokenizer.cs index 765f63e38892..d0a95cd876c4 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpTokenizer.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpTokenizer.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy { internal class CSharpTokenizer : Tokenizer { - private Dictionary> _operatorHandlers; + private readonly Dictionary> _operatorHandlers; private static readonly Dictionary _keywords = new Dictionary(StringComparer.Ordinal) { @@ -559,8 +559,8 @@ private StateResult VerbatimStringLiteral() private StateResult QuotedStringLiteral() => QuotedLiteral('\"', IsEndQuotedStringLiteral, SyntaxKind.StringLiteral); - private Func IsEndQuotedCharacterLiteral = (c) => c == '\\' || c == '\'' || ParserHelpers.IsNewLine(c); - private Func IsEndQuotedStringLiteral = (c) => c == '\\' || c == '\"' || ParserHelpers.IsNewLine(c); + private readonly Func IsEndQuotedCharacterLiteral = (c) => c == '\\' || c == '\'' || ParserHelpers.IsNewLine(c); + private readonly Func IsEndQuotedStringLiteral = (c) => c == '\\' || c == '\"' || ParserHelpers.IsNewLine(c); private StateResult QuotedLiteral(char quote, Func isEndQuotedLiteral, SyntaxKind literalType) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveCSharpLanguageCharacteristics.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveCSharpLanguageCharacteristics.cs index c3761ce5c593..8d4e033f60b7 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveCSharpLanguageCharacteristics.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveCSharpLanguageCharacteristics.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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. namespace Microsoft.AspNetCore.Razor.Language.Legacy @@ -11,7 +11,7 @@ private FirstDirectiveCSharpLanguageCharacteristics() { } - public new static FirstDirectiveCSharpLanguageCharacteristics Instance => _instance; + public static new FirstDirectiveCSharpLanguageCharacteristics Instance => _instance; public override CSharpTokenizer CreateTokenizer(ITextDocument source) => new DirectiveCSharpTokenizer(source); } diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveHtmlLanguageCharacteristics.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveHtmlLanguageCharacteristics.cs index 2e2c7bea6bb8..ce969c758c26 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveHtmlLanguageCharacteristics.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveHtmlLanguageCharacteristics.cs @@ -11,7 +11,7 @@ private FirstDirectiveHtmlLanguageCharacteristics() { } - public new static FirstDirectiveHtmlLanguageCharacteristics Instance => _instance; + public static new FirstDirectiveHtmlLanguageCharacteristics Instance => _instance; public override HtmlTokenizer CreateTokenizer(ITextDocument source) => new DirectiveHtmlTokenizer(source); } 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 fef11964c684..ef83e8f93757 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/TagHelperParseTreeRewriter.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/TagHelperParseTreeRewriter.cs @@ -58,7 +58,7 @@ internal sealed class Rewriter : SyntaxRewriter private readonly TagHelperBinder _tagHelperBinder; private readonly Stack _trackerStack; private readonly ErrorSink _errorSink; - private RazorParserFeatureFlags _featureFlags; + private readonly RazorParserFeatureFlags _featureFlags; public Rewriter( RazorSourceDocument source, diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorCodeDocumentExtensions.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorCodeDocumentExtensions.cs index 69338cf6a0c9..861329cd66d9 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorCodeDocumentExtensions.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorCodeDocumentExtensions.cs @@ -14,7 +14,7 @@ public static class RazorCodeDocumentExtensions { private static readonly char[] PathSeparators = new char[] { '/', '\\' }; private static readonly char[] NamespaceSeparators = new char[] { '.' }; - private static object CssScopeKey = new object(); + private static readonly object CssScopeKey = new object(); public static TagHelperDocumentContext GetTagHelperContext(this RazorCodeDocument document) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorDiagnostic.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorDiagnostic.cs index 2f74cfbfad74..f1bfdc377ecb 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorDiagnostic.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorDiagnostic.cs @@ -22,7 +22,7 @@ public abstract class RazorDiagnostic : IEquatable, IFormattabl public abstract bool Equals(RazorDiagnostic other); - public override abstract int GetHashCode(); + public abstract override int GetHashCode(); public static RazorDiagnostic Create(RazorDiagnosticDescriptor descriptor, SourceSpan span) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxListOfT.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxListOfT.cs index e5552cceaf9f..416b368bf266 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxListOfT.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxListOfT.cs @@ -153,7 +153,7 @@ public static implicit operator SyntaxList(SyntaxList nodes) internal struct Enumerator { - private SyntaxList _list; + private readonly SyntaxList _list; private int _index; internal Enumerator(SyntaxList list) diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxToken.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxToken.cs index 2b958788ee16..05493700439e 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxToken.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxToken.cs @@ -81,7 +81,7 @@ protected override void WriteTokenTo(TextWriter writer, bool leading, bool trail } } - public override sealed GreenNode GetLeadingTrivia() + public sealed override GreenNode GetLeadingTrivia() { return _leadingTrivia; } @@ -91,7 +91,7 @@ public override int GetLeadingTriviaWidth() return _leadingTrivia == null ? 0 : _leadingTrivia.FullWidth; } - public override sealed GreenNode GetTrailingTrivia() + public sealed override GreenNode GetTrailingTrivia() { return _trailingTrivia; } @@ -131,12 +131,12 @@ internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) return new SyntaxToken(Kind, Content, _leadingTrivia, _trailingTrivia, GetDiagnostics(), annotations); } - protected override sealed int GetSlotCount() + protected sealed override int GetSlotCount() { return 0; } - internal override sealed GreenNode GetSlot(int index) + internal sealed override GreenNode GetSlot(int index) { throw new InvalidOperationException("Tokens don't have slots."); } diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxTrivia.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxTrivia.cs index 84ad53155ac6..841d134f380f 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxTrivia.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxTrivia.cs @@ -47,12 +47,12 @@ public sealed override int GetTrailingTriviaWidth() return 0; } - protected override sealed int GetSlotCount() + protected sealed override int GetSlotCount() { return 0; } - internal override sealed GreenNode GetSlot(int index) + internal sealed override GreenNode GetSlot(int index) { throw new InvalidOperationException(); } diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SpecializedCollections.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SpecializedCollections.cs index 3e1094003fe1..48b51cecdd7e 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SpecializedCollections.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SpecializedCollections.cs @@ -130,7 +130,7 @@ public bool Remove(T item) internal class List : Collection, IList, IReadOnlyList { - public static readonly new List Instance = new List(); + public static new readonly List Instance = new List(); protected List() { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxToken.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxToken.cs index e3ecd35bf66b..92f288dc9471 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxToken.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxToken.cs @@ -20,12 +20,12 @@ internal SyntaxToken(GreenNode green, SyntaxNode parent, int position) public string Content => Green.Content; - internal override sealed SyntaxNode GetCachedSlot(int index) + internal sealed override SyntaxNode GetCachedSlot(int index) { throw new InvalidOperationException("Tokens can't have slots."); } - internal override sealed SyntaxNode GetNodeSlot(int slot) + internal sealed override SyntaxNode GetNodeSlot(int slot) { throw new InvalidOperationException("Tokens can't have slots."); } diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTrivia.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTrivia.cs index d16e42f1edba..f94fa5ddb291 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTrivia.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTrivia.cs @@ -16,12 +16,12 @@ internal SyntaxTrivia(GreenNode green, SyntaxNode parent, int position) public string Text => Green.Text; - internal override sealed SyntaxNode GetCachedSlot(int index) + internal sealed override SyntaxNode GetCachedSlot(int index) { throw new InvalidOperationException(); } - internal override sealed SyntaxNode GetNodeSlot(int slot) + internal sealed override SyntaxNode GetNodeSlot(int slot) { throw new InvalidOperationException(); } diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTriviaList.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTriviaList.cs index 2097e9391c18..22d1760fbc4d 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTriviaList.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTriviaList.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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; @@ -507,7 +507,7 @@ public static SyntaxTriviaList Create(SyntaxTrivia trivia) /// public struct Reversed : IEnumerable, IEquatable { - private SyntaxTriviaList _list; + private readonly SyntaxTriviaList _list; public Reversed(in SyntaxTriviaList list) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/TagHelperSpanVisitor.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/TagHelperSpanVisitor.cs index 836a45ae983c..422d1bf447fa 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/TagHelperSpanVisitor.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/TagHelperSpanVisitor.cs @@ -9,8 +9,8 @@ namespace Microsoft.AspNetCore.Razor.Language { internal class TagHelperSpanVisitor : SyntaxWalker { - private RazorSourceDocument _source; - private List _spans; + private readonly RazorSourceDocument _source; + private readonly List _spans; public TagHelperSpanVisitor(RazorSourceDocument source) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/DefaultRazorIntermediateNodeLoweringPhaseIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/DefaultRazorIntermediateNodeLoweringPhaseIntegrationTest.cs index 4d008b89d90a..8611b720e86b 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/DefaultRazorIntermediateNodeLoweringPhaseIntegrationTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/DefaultRazorIntermediateNodeLoweringPhaseIntegrationTest.cs @@ -516,7 +516,7 @@ private static TagHelperDescriptor CreateTagHelperDescriptor( private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature { - private bool _designTime; + private readonly bool _designTime; public DesignTimeOptionsFeature(bool designTime) { 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 2a8bc2b33524..a9ef4d18b8b6 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/DefaultTagHelperTargetExtensionTest.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/DefaultTagHelperTargetExtensionTest.cs @@ -1209,7 +1209,7 @@ private static TagHelperDescriptor CreateTagHelperDescriptor( private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature { - private bool _designTime; + private readonly bool _designTime; public DesignTimeOptionsFeature(bool designTime) { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/BaselineWriter.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/BaselineWriter.cs index e84bfd7a6c4c..56af6e242260 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/BaselineWriter.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/BaselineWriter.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy { public static class BaselineWriter { - private static object baselineLock = new object(); + private static readonly object baselineLock = new object(); [Conditional("GENERATE_BASELINES")] public static void WriteBaseline(string baselineFile, string output) diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpTokenizerTestBase.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpTokenizerTestBase.cs index 83b2adc684fb..98f3e0119488 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpTokenizerTestBase.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpTokenizerTestBase.cs @@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy { public abstract class CSharpTokenizerTestBase : TokenizerTestBase { - private static SyntaxToken _ignoreRemaining = SyntaxFactory.Token(SyntaxKind.Marker, string.Empty); + private static readonly SyntaxToken _ignoreRemaining = SyntaxFactory.Token(SyntaxKind.Marker, string.Empty); internal override object IgnoreRemaining { diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/HtmlTokenizerTestBase.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/HtmlTokenizerTestBase.cs index 0b6250d6d8f1..dc89c9909bf7 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/HtmlTokenizerTestBase.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/HtmlTokenizerTestBase.cs @@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy { public abstract class HtmlTokenizerTestBase : TokenizerTestBase { - private static SyntaxToken _ignoreRemaining = SyntaxFactory.Token(SyntaxKind.Marker, string.Empty); + private static readonly SyntaxToken _ignoreRemaining = SyntaxFactory.Token(SyntaxKind.Marker, string.Empty); internal override object IgnoreRemaining { diff --git a/src/Razor/Microsoft.CodeAnalysis.Razor/src/BindTagHelperDescriptorProvider.cs b/src/Razor/Microsoft.CodeAnalysis.Razor/src/BindTagHelperDescriptorProvider.cs index 3916a28c2900..828b7e82adc8 100644 --- a/src/Razor/Microsoft.CodeAnalysis.Razor/src/BindTagHelperDescriptorProvider.cs +++ b/src/Razor/Microsoft.CodeAnalysis.Razor/src/BindTagHelperDescriptorProvider.cs @@ -579,7 +579,7 @@ public ElementBindData( private class BindElementDataVisitor : SymbolVisitor { - private List _results; + private readonly List _results; public BindElementDataVisitor(List results) { diff --git a/src/Razor/Microsoft.CodeAnalysis.Razor/src/EventHandlerTagHelperDescriptorProvider.cs b/src/Razor/Microsoft.CodeAnalysis.Razor/src/EventHandlerTagHelperDescriptorProvider.cs index 9c83533509ff..aa9f7b611011 100644 --- a/src/Razor/Microsoft.CodeAnalysis.Razor/src/EventHandlerTagHelperDescriptorProvider.cs +++ b/src/Razor/Microsoft.CodeAnalysis.Razor/src/EventHandlerTagHelperDescriptorProvider.cs @@ -260,7 +260,7 @@ public EventHandlerData( private class EventHandlerDataVisitor : SymbolVisitor { - private List _results; + private readonly List _results; public EventHandlerDataVisitor(List results) { diff --git a/src/Razor/Microsoft.CodeAnalysis.Razor/src/RequiredAttributeParser.cs b/src/Razor/Microsoft.CodeAnalysis.Razor/src/RequiredAttributeParser.cs index 898e065439ed..fc74d678d629 100644 --- a/src/Razor/Microsoft.CodeAnalysis.Razor/src/RequiredAttributeParser.cs +++ b/src/Razor/Microsoft.CodeAnalysis.Razor/src/RequiredAttributeParser.cs @@ -35,7 +35,7 @@ private class DefaultRequiredAttributeParser private static readonly char[] InvalidCssQuotelessValueCharacters = { ' ', '\t', ']' }; private int _index; - private string _requiredAttributes; + private readonly string _requiredAttributes; public DefaultRequiredAttributeParser(string requiredAttributes) { diff --git a/src/Razor/Microsoft.CodeAnalysis.Razor/src/TagHelperTypeVisitor.cs b/src/Razor/Microsoft.CodeAnalysis.Razor/src/TagHelperTypeVisitor.cs index 3387cfd1e87f..cc19de3cf942 100644 --- a/src/Razor/Microsoft.CodeAnalysis.Razor/src/TagHelperTypeVisitor.cs +++ b/src/Razor/Microsoft.CodeAnalysis.Razor/src/TagHelperTypeVisitor.cs @@ -8,8 +8,8 @@ namespace Microsoft.CodeAnalysis.Razor // Visits top-level types and finds interface implementations. internal class TagHelperTypeVisitor : SymbolVisitor { - private INamedTypeSymbol _interface; - private List _results; + private readonly INamedTypeSymbol _interface; + private readonly List _results; public TagHelperTypeVisitor(INamedTypeSymbol @interface, List results) { diff --git a/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs b/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs index 5443bcd5444a..05c1242005af 100644 --- a/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs +++ b/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs @@ -21,7 +21,7 @@ public class TagHelperExecutionContext private TagHelperContent _childContent; private Func _executeChildContentAsync; private Dictionary _perEncoderChildContent; - private TagHelperAttributeList _allAttributes; + private readonly TagHelperAttributeList _allAttributes; /// /// Internal for testing purposes only. diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorIntegrationTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorIntegrationTestBase.cs index 0488941c0e8a..180fde3c9f46 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorIntegrationTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorIntegrationTestBase.cs @@ -465,7 +465,7 @@ protected override void ExecuteCore(RazorCodeDocument codeDocument) private class TestImportProjectFeature : IImportProjectFeature { - private List _imports; + private readonly List _imports; public TestImportProjectFeature(List imports) { diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/TestRazorProjectFileSystem.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/TestRazorProjectFileSystem.cs index 271c6224372d..754ec32088ac 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/TestRazorProjectFileSystem.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/TestRazorProjectFileSystem.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Razor.Language { internal class TestRazorProjectFileSystem : DefaultRazorProjectFileSystem { - public new static RazorProjectFileSystem Empty = new TestRazorProjectFileSystem(); + public static new RazorProjectFileSystem Empty = new TestRazorProjectFileSystem(); private readonly Dictionary _lookup; diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.Forms.netstandard2.0.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.Forms.netstandard2.0.cs index 4674ff0fb4e2..f6161b164cc5 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.Forms.netstandard2.0.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.Forms.netstandard2.0.cs @@ -64,12 +64,12 @@ public void Clear(System.Linq.Expressions.Expression> access } public sealed partial class ValidationRequestedEventArgs : System.EventArgs { - public static readonly new Microsoft.AspNetCore.Components.Forms.ValidationRequestedEventArgs Empty; + public static new readonly Microsoft.AspNetCore.Components.Forms.ValidationRequestedEventArgs Empty; public ValidationRequestedEventArgs() { } } public sealed partial class ValidationStateChangedEventArgs : System.EventArgs { - public static readonly new Microsoft.AspNetCore.Components.Forms.ValidationStateChangedEventArgs Empty; + public static new readonly Microsoft.AspNetCore.Components.Forms.ValidationStateChangedEventArgs Empty; public ValidationStateChangedEventArgs() { } } } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.netstandard2.0.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.netstandard2.0.cs index 7e807c0f675a..d9e1409a4bbc 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.netstandard2.0.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.netstandard2.0.cs @@ -337,8 +337,8 @@ public void SetParameterProperties(object target) { } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator { - private object _dummy; - private int _dummyPrimitive; + private readonly object _dummy; + private readonly int _dummyPrimitive; public Microsoft.AspNetCore.Components.ParameterValue Current { get { throw null; } } public bool MoveNext() { throw null; } } diff --git a/src/Security/Authentication/Certificate/src/LoggingExtensions.cs b/src/Security/Authentication/Certificate/src/LoggingExtensions.cs index e6a67c0ffa40..2d97f194bcf0 100644 --- a/src/Security/Authentication/Certificate/src/LoggingExtensions.cs +++ b/src/Security/Authentication/Certificate/src/LoggingExtensions.cs @@ -8,10 +8,10 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _noCertificate; - private static Action _notHttps; - private static Action _certRejected; - private static Action _certFailedValidation; + private static readonly Action _noCertificate; + private static readonly Action _notHttps; + private static readonly Action _certRejected; + private static readonly Action _certFailedValidation; static LoggingExtensions() { diff --git a/src/Security/Authentication/Cookies/samples/CookieSessionSample/MemoryCacheTicketStore.cs b/src/Security/Authentication/Cookies/samples/CookieSessionSample/MemoryCacheTicketStore.cs index ebb660361b43..158921b07cf7 100644 --- a/src/Security/Authentication/Cookies/samples/CookieSessionSample/MemoryCacheTicketStore.cs +++ b/src/Security/Authentication/Cookies/samples/CookieSessionSample/MemoryCacheTicketStore.cs @@ -9,7 +9,7 @@ namespace CookieSessionSample public class MemoryCacheTicketStore : ITicketStore { private const string KeyPrefix = "AuthSessionStore-"; - private IMemoryCache _cache; + private readonly IMemoryCache _cache; public MemoryCacheTicketStore() { diff --git a/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs b/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs index 28e5545a141e..b42a64be7834 100644 --- a/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs +++ b/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs @@ -276,7 +276,7 @@ protected virtual async Task FinishResponseAsync() } /// - protected async override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties) + protected override async Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties) { if (user == null) { @@ -369,7 +369,7 @@ protected async override Task HandleSignInAsync(ClaimsPrincipal user, Authentica } /// - protected async override Task HandleSignOutAsync(AuthenticationProperties? properties) + protected override async Task HandleSignOutAsync(AuthenticationProperties? properties) { properties = properties ?? new AuthenticationProperties(); diff --git a/src/Security/Authentication/Core/src/HandleRequestResult.cs b/src/Security/Authentication/Core/src/HandleRequestResult.cs index 7fd664b080bf..73eb461df720 100644 --- a/src/Security/Authentication/Core/src/HandleRequestResult.cs +++ b/src/Security/Authentication/Core/src/HandleRequestResult.cs @@ -97,7 +97,7 @@ public static HandleRequestResult SkipHandler() /// Indicates that there were no results produced during authentication. /// /// The result. - public new static HandleRequestResult NoResult() + public static new HandleRequestResult NoResult() { return new HandleRequestResult() { None = true }; } diff --git a/src/Security/Authentication/JwtBearer/src/JwtBearerOptions.cs b/src/Security/Authentication/JwtBearer/src/JwtBearerOptions.cs index 6017853304d2..efd79d9a9dd7 100644 --- a/src/Security/Authentication/JwtBearer/src/JwtBearerOptions.cs +++ b/src/Security/Authentication/JwtBearer/src/JwtBearerOptions.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Authentication.JwtBearer /// public class JwtBearerOptions : AuthenticationSchemeOptions { - private JwtSecurityTokenHandler _defaultHandler = new JwtSecurityTokenHandler(); + private readonly JwtSecurityTokenHandler _defaultHandler = new JwtSecurityTokenHandler(); /// /// Initializes a new instance of . diff --git a/src/Security/Authentication/Negotiate/src/Internal/NegotiateLoggingExtensions.cs b/src/Security/Authentication/Negotiate/src/Internal/NegotiateLoggingExtensions.cs index 90a0f4c0c637..61c75b5bfdb3 100644 --- a/src/Security/Authentication/Negotiate/src/Internal/NegotiateLoggingExtensions.cs +++ b/src/Security/Authentication/Negotiate/src/Internal/NegotiateLoggingExtensions.cs @@ -7,18 +7,18 @@ namespace Microsoft.Extensions.Logging { internal static class NegotiateLoggingExtensions { - private static Action _incompleteNegotiateChallenge; - private static Action _negotiateComplete; - private static Action _enablingCredentialPersistence; - private static Action _disablingCredentialPersistence; - private static Action _exceptionProcessingAuth; - private static Action _credentialError; - private static Action _clientError; - private static Action _challengeNegotiate; - private static Action _reauthenticating; - private static Action _deferring; - private static Action _negotiateError; - private static Action _protocolNotSupported; + private static readonly Action _incompleteNegotiateChallenge; + private static readonly Action _negotiateComplete; + private static readonly Action _enablingCredentialPersistence; + private static readonly Action _disablingCredentialPersistence; + private static readonly Action _exceptionProcessingAuth; + private static readonly Action _credentialError; + private static readonly Action _clientError; + private static readonly Action _challengeNegotiate; + private static readonly Action _reauthenticating; + private static readonly Action _deferring; + private static readonly Action _negotiateError; + private static readonly Action _protocolNotSupported; static NegotiateLoggingExtensions() { diff --git a/src/Security/Authentication/OAuth/src/LoggingExtensions.cs b/src/Security/Authentication/OAuth/src/LoggingExtensions.cs index 2ec9befe172a..003e9638a779 100644 --- a/src/Security/Authentication/OAuth/src/LoggingExtensions.cs +++ b/src/Security/Authentication/OAuth/src/LoggingExtensions.cs @@ -7,7 +7,7 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _handleChallenge; + private static readonly Action _handleChallenge; static LoggingExtensions() { diff --git a/src/Security/Authentication/OpenIdConnect/src/LoggingExtensions.cs b/src/Security/Authentication/OpenIdConnect/src/LoggingExtensions.cs index 2692942a495a..61399b1d101f 100644 --- a/src/Security/Authentication/OpenIdConnect/src/LoggingExtensions.cs +++ b/src/Security/Authentication/OpenIdConnect/src/LoggingExtensions.cs @@ -7,58 +7,58 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _redirectToIdentityProviderForSignOutHandledResponse; - private static Action _redirectToIdentityProviderHandledResponse; - private static Action _signOutCallbackRedirectHandledResponse; - private static Action _signOutCallbackRedirectSkipped; - private static Action _updatingConfiguration; - private static Action _receivedIdToken; - private static Action _redeemingCodeForTokens; - private static Action _enteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync; - private static Action _enteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync; - private static Action _enteringOpenIdAuthenticationHandlerHandleSignOutAsync; - private static Action _messageReceived; - private static Action _messageReceivedContextHandledResponse; - private static Action _messageReceivedContextSkipped; - private static Action _authorizationCodeReceived; - private static Action _configurationManagerRequestRefreshCalled; - private static Action _tokenResponseReceived; - private static Action _tokenValidatedHandledResponse; - private static Action _tokenValidatedSkipped; - private static Action _authenticationFailedContextHandledResponse; - private static Action _authenticationFailedContextSkipped; - private static Action _authorizationCodeReceivedContextHandledResponse; - private static Action _authorizationCodeReceivedContextSkipped; - private static Action _tokenResponseReceivedHandledResponse; - private static Action _tokenResponseReceivedSkipped; - private static Action _userInformationReceived; - private static Action _userInformationReceivedHandledResponse; - private static Action _userInformationReceivedSkipped; - private static Action _invalidLogoutQueryStringRedirectUrl; - private static Action _nullOrEmptyAuthorizationResponseState; - private static Action _unableToReadAuthorizationResponseState; - private static Action _responseError; - private static Action _responseErrorWithStatusCode; - private static Action _exceptionProcessingMessage; - private static Action _accessTokenNotAvailable; - private static Action _retrievingClaims; - private static Action _userInfoEndpointNotSet; - private static Action _unableToProtectNonceCookie; - private static Action _invalidAuthenticationRequestUrl; - private static Action _unableToReadIdToken; - private static Action _invalidSecurityTokenType; - private static Action _unableToValidateIdToken; - private static Action _postAuthenticationLocalRedirect; - private static Action _postSignOutRedirect; - private static Action _remoteSignOutHandledResponse; - private static Action _remoteSignOutSkipped; - private static Action _remoteSignOut; - private static Action _remoteSignOutSessionIdMissing; - private static Action _remoteSignOutSessionIdInvalid; - private static Action _authenticationSchemeSignedOut; - private static Action _handleChallenge; - private static Action _remoteSignOutIssuerMissing; - private static Action _remoteSignOutIssuerInvalid; + private static readonly Action _redirectToIdentityProviderForSignOutHandledResponse; + private static readonly Action _redirectToIdentityProviderHandledResponse; + private static readonly Action _signOutCallbackRedirectHandledResponse; + private static readonly Action _signOutCallbackRedirectSkipped; + private static readonly Action _updatingConfiguration; + private static readonly Action _receivedIdToken; + private static readonly Action _redeemingCodeForTokens; + private static readonly Action _enteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync; + private static readonly Action _enteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync; + private static readonly Action _enteringOpenIdAuthenticationHandlerHandleSignOutAsync; + private static readonly Action _messageReceived; + private static readonly Action _messageReceivedContextHandledResponse; + private static readonly Action _messageReceivedContextSkipped; + private static readonly Action _authorizationCodeReceived; + private static readonly Action _configurationManagerRequestRefreshCalled; + private static readonly Action _tokenResponseReceived; + private static readonly Action _tokenValidatedHandledResponse; + private static readonly Action _tokenValidatedSkipped; + private static readonly Action _authenticationFailedContextHandledResponse; + private static readonly Action _authenticationFailedContextSkipped; + private static readonly Action _authorizationCodeReceivedContextHandledResponse; + private static readonly Action _authorizationCodeReceivedContextSkipped; + private static readonly Action _tokenResponseReceivedHandledResponse; + private static readonly Action _tokenResponseReceivedSkipped; + private static readonly Action _userInformationReceived; + private static readonly Action _userInformationReceivedHandledResponse; + private static readonly Action _userInformationReceivedSkipped; + private static readonly Action _invalidLogoutQueryStringRedirectUrl; + private static readonly Action _nullOrEmptyAuthorizationResponseState; + private static readonly Action _unableToReadAuthorizationResponseState; + private static readonly Action _responseError; + private static readonly Action _responseErrorWithStatusCode; + private static readonly Action _exceptionProcessingMessage; + private static readonly Action _accessTokenNotAvailable; + private static readonly Action _retrievingClaims; + private static readonly Action _userInfoEndpointNotSet; + private static readonly Action _unableToProtectNonceCookie; + private static readonly Action _invalidAuthenticationRequestUrl; + private static readonly Action _unableToReadIdToken; + private static readonly Action _invalidSecurityTokenType; + private static readonly Action _unableToValidateIdToken; + private static readonly Action _postAuthenticationLocalRedirect; + private static readonly Action _postSignOutRedirect; + private static readonly Action _remoteSignOutHandledResponse; + private static readonly Action _remoteSignOutSkipped; + private static readonly Action _remoteSignOut; + private static readonly Action _remoteSignOutSessionIdMissing; + private static readonly Action _remoteSignOutSessionIdInvalid; + private static readonly Action _authenticationSchemeSignedOut; + private static readonly Action _handleChallenge; + private static readonly Action _remoteSignOutIssuerMissing; + private static readonly Action _remoteSignOutIssuerInvalid; static LoggingExtensions() { diff --git a/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectHandler.cs b/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectHandler.cs index 6acb9c220e73..6cc9ff5b435d 100644 --- a/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectHandler.cs +++ b/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectHandler.cs @@ -186,7 +186,7 @@ protected virtual async Task HandleRemoteSignOutAsync() /// Redirect user to the identity provider for sign out /// /// A task executing the sign out procedure - public async virtual Task SignOutAsync(AuthenticationProperties? properties) + public virtual async Task SignOutAsync(AuthenticationProperties? properties) { var target = ResolveTarget(Options.ForwardSignOut); if (target != null) @@ -290,7 +290,7 @@ public async virtual Task SignOutAsync(AuthenticationProperties? properties) /// Response to the callback from OpenId provider after session ended. /// /// A task executing the callback procedure - protected async virtual Task HandleSignOutCallbackAsync() + protected virtual async Task HandleSignOutCallbackAsync() { var message = new OpenIdConnectMessage(Request.Query.Select(pair => new KeyValuePair(pair.Key, pair.Value))); AuthenticationProperties? properties = null; diff --git a/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectOptions.cs b/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectOptions.cs index 702e4cb0f687..b4e6b4b2c04b 100644 --- a/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectOptions.cs +++ b/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectOptions.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Authentication.OpenIdConnect public class OpenIdConnectOptions : RemoteAuthenticationOptions { private CookieBuilder _nonceCookieBuilder; - private JwtSecurityTokenHandler _defaultHandler = new JwtSecurityTokenHandler(); + private readonly JwtSecurityTokenHandler _defaultHandler = new JwtSecurityTokenHandler(); /// /// Initializes a new diff --git a/src/Security/Authentication/Twitter/src/LoggingExtensions.cs b/src/Security/Authentication/Twitter/src/LoggingExtensions.cs index c6a50793ae1b..c962a845cb69 100644 --- a/src/Security/Authentication/Twitter/src/LoggingExtensions.cs +++ b/src/Security/Authentication/Twitter/src/LoggingExtensions.cs @@ -7,9 +7,9 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _obtainRequestToken; - private static Action _obtainAccessToken; - private static Action _retrieveUserDetails; + private static readonly Action _obtainRequestToken; + private static readonly Action _obtainAccessToken; + private static readonly Action _retrieveUserDetails; static LoggingExtensions() { diff --git a/src/Security/Authentication/WsFederation/src/LoggingExtensions.cs b/src/Security/Authentication/WsFederation/src/LoggingExtensions.cs index 8976c21bff27..9d144226e787 100644 --- a/src/Security/Authentication/WsFederation/src/LoggingExtensions.cs +++ b/src/Security/Authentication/WsFederation/src/LoggingExtensions.cs @@ -7,13 +7,13 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _signInWithoutWResult; - private static Action _signInWithoutToken; - private static Action _exceptionProcessingMessage; - private static Action _malformedRedirectUri; - private static Action _remoteSignOutHandledResponse; - private static Action _remoteSignOutSkipped; - private static Action _remoteSignOut; + private static readonly Action _signInWithoutWResult; + private static readonly Action _signInWithoutToken; + private static readonly Action _exceptionProcessingMessage; + private static readonly Action _malformedRedirectUri; + private static readonly Action _remoteSignOutHandledResponse; + private static readonly Action _remoteSignOutSkipped; + private static readonly Action _remoteSignOut; static LoggingExtensions() { diff --git a/src/Security/Authentication/WsFederation/src/WsFederationHandler.cs b/src/Security/Authentication/WsFederation/src/WsFederationHandler.cs index 851f19b335f6..bd7dbdae1c55 100644 --- a/src/Security/Authentication/WsFederation/src/WsFederationHandler.cs +++ b/src/Security/Authentication/WsFederation/src/WsFederationHandler.cs @@ -319,7 +319,7 @@ protected override async Task HandleRemoteAuthenticateAsync /// Handles Signout /// /// - public async virtual Task SignOutAsync(AuthenticationProperties? properties) + public virtual async Task SignOutAsync(AuthenticationProperties? properties) { var target = ResolveTarget(Options.ForwardSignOut); if (target != null) diff --git a/src/Security/Authentication/test/AuthenticationMiddlewareTests.cs b/src/Security/Authentication/test/AuthenticationMiddlewareTests.cs index cf48902da024..f35c64e74475 100644 --- a/src/Security/Authentication/test/AuthenticationMiddlewareTests.cs +++ b/src/Security/Authentication/test/AuthenticationMiddlewareTests.cs @@ -194,7 +194,7 @@ public SevenOhSevenHandler() : base(707) { } private class StatusCodeHandler : IAuthenticationRequestHandler { private HttpContext _context; - private int _code; + private readonly int _code; public StatusCodeHandler(int code) { diff --git a/src/Security/Authentication/test/CertificateTests.cs b/src/Security/Authentication/test/CertificateTests.cs index e7bf24a4a4b6..e0276a8f89d2 100644 --- a/src/Security/Authentication/test/CertificateTests.cs +++ b/src/Security/Authentication/test/CertificateTests.cs @@ -782,7 +782,7 @@ private static async Task CreateHost( return host; } - private CertificateAuthenticationEvents successfulValidationEvents = new CertificateAuthenticationEvents() + private readonly CertificateAuthenticationEvents successfulValidationEvents = new CertificateAuthenticationEvents() { OnCertificateValidated = context => { @@ -798,7 +798,7 @@ private static async Task CreateHost( } }; - private CertificateAuthenticationEvents failedValidationEvents = new CertificateAuthenticationEvents() + private readonly CertificateAuthenticationEvents failedValidationEvents = new CertificateAuthenticationEvents() { OnCertificateValidated = context => { @@ -807,7 +807,7 @@ private static async Task CreateHost( } }; - private CertificateAuthenticationEvents unprocessedValidationEvents = new CertificateAuthenticationEvents() + private readonly CertificateAuthenticationEvents unprocessedValidationEvents = new CertificateAuthenticationEvents() { OnCertificateValidated = context => { diff --git a/src/Security/Authentication/test/CookieTests.cs b/src/Security/Authentication/test/CookieTests.cs index c93f5e0a75cd..1ed0e8c92b2f 100644 --- a/src/Security/Authentication/test/CookieTests.cs +++ b/src/Security/Authentication/test/CookieTests.cs @@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Authentication.Cookies { public class CookieTests : SharedAuthenticationTests { - private TestClock _clock = new TestClock(); + private readonly TestClock _clock = new TestClock(); protected override string DefaultScheme => CookieAuthenticationDefaults.AuthenticationScheme; protected override Type HandlerType => typeof(CookieAuthenticationHandler); diff --git a/src/Security/Authentication/test/JwtBearerTests.cs b/src/Security/Authentication/test/JwtBearerTests.cs index dd21d7b2cb1a..3fa60880a223 100755 --- a/src/Security/Authentication/test/JwtBearerTests.cs +++ b/src/Security/Authentication/test/JwtBearerTests.cs @@ -984,7 +984,7 @@ public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParame class BlobTokenValidator : ISecurityTokenValidator { - private Action _tokenValidator; + private readonly Action _tokenValidator; public BlobTokenValidator(string authenticationScheme) { diff --git a/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectTests.cs b/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectTests.cs index eff8ae939dc0..6d94a940ca1a 100644 --- a/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectTests.cs +++ b/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectTests.cs @@ -20,8 +20,8 @@ namespace Microsoft.AspNetCore.Authentication.Test.OpenIdConnect { public class OpenIdConnectTests { - static string noncePrefix = "OpenIdConnect." + "Nonce."; - static string nonceDelimiter = "."; + static readonly string noncePrefix = "OpenIdConnect." + "Nonce."; + static readonly string nonceDelimiter = "."; const string DefaultHost = @"https://example.com"; /// diff --git a/src/Security/Authentication/test/WsFederation/CustomStateDataFormat.cs b/src/Security/Authentication/test/WsFederation/CustomStateDataFormat.cs index 0de867d286e6..900b4f83c1ab 100644 --- a/src/Security/Authentication/test/WsFederation/CustomStateDataFormat.cs +++ b/src/Security/Authentication/test/WsFederation/CustomStateDataFormat.cs @@ -12,7 +12,7 @@ public class CustomStateDataFormat : ISecureDataFormat public const string ValidStateData = "ValidStateData"; private string lastSavedAuthenticationProperties; - private DataContractSerializer serializer = new DataContractSerializer(typeof(AuthenticationProperties)); + private readonly DataContractSerializer serializer = new DataContractSerializer(typeof(AuthenticationProperties)); public string Protect(AuthenticationProperties data) { diff --git a/src/Security/Authorization/Core/src/AuthorizationHandlerContext.cs b/src/Security/Authorization/Core/src/AuthorizationHandlerContext.cs index 99d1951a779a..b2de5a5865c6 100644 --- a/src/Security/Authorization/Core/src/AuthorizationHandlerContext.cs +++ b/src/Security/Authorization/Core/src/AuthorizationHandlerContext.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Authorization /// public class AuthorizationHandlerContext { - private HashSet _pendingRequirements; + private readonly HashSet _pendingRequirements; private bool _failCalled; private bool _succeedCalled; diff --git a/src/Security/Authorization/test/DefaultAuthorizationServiceTests.cs b/src/Security/Authorization/test/DefaultAuthorizationServiceTests.cs index 70d3045eda90..6b3303f9ba4f 100644 --- a/src/Security/Authorization/test/DefaultAuthorizationServiceTests.cs +++ b/src/Security/Authorization/test/DefaultAuthorizationServiceTests.cs @@ -840,7 +840,7 @@ public ExpenseReportAuthorizationHandler(IEnumerable _allowed; + private readonly IEnumerable _allowed; protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OperationAuthorizationRequirement requirement, ExpenseReport resource) { @@ -1186,7 +1186,7 @@ public override string ToString() public class DefaultAuthorizationServiceTestLogger : ILogger { - private Action> _assertion; + private readonly Action> _assertion; public DefaultAuthorizationServiceTestLogger(Action> assertion) { diff --git a/src/Security/CookiePolicy/src/LoggingExtensions.cs b/src/Security/CookiePolicy/src/LoggingExtensions.cs index ac993c05467a..dc4aabddb594 100644 --- a/src/Security/CookiePolicy/src/LoggingExtensions.cs +++ b/src/Security/CookiePolicy/src/LoggingExtensions.cs @@ -7,15 +7,15 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _needsConsent; - private static Action _hasConsent; - private static Action _consentGranted; - private static Action _consentWithdrawn; - private static Action _cookieSuppressed; - private static Action _deleteCookieSuppressed; - private static Action _upgradedToSecure; - private static Action _upgradedSameSite; - private static Action _upgradedToHttpOnly; + private static readonly Action _needsConsent; + private static readonly Action _hasConsent; + private static readonly Action _consentGranted; + private static readonly Action _consentWithdrawn; + private static readonly Action _cookieSuppressed; + private static readonly Action _deleteCookieSuppressed; + private static readonly Action _upgradedToSecure; + private static readonly Action _upgradedSameSite; + private static readonly Action _upgradedToHttpOnly; static LoggingExtensions() { diff --git a/src/Security/CookiePolicy/test/CookiePolicyTests.cs b/src/Security/CookiePolicy/test/CookiePolicyTests.cs index 6f5c940c7d9e..7e7c2b9e0ccd 100644 --- a/src/Security/CookiePolicy/test/CookiePolicyTests.cs +++ b/src/Security/CookiePolicy/test/CookiePolicyTests.cs @@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.CookiePolicy.Test { public class CookiePolicyTests { - private RequestDelegate SecureCookieAppends = context => + private readonly RequestDelegate SecureCookieAppends = context => { context.Response.Cookies.Append("A", "A"); context.Response.Cookies.Append("B", "B", new CookieOptions { Secure = false }); @@ -29,7 +29,7 @@ public class CookiePolicyTests context.Response.Cookies.Append("D", "D", new CookieOptions { Secure = true }); return Task.FromResult(0); }; - private RequestDelegate HttpCookieAppends = context => + private readonly RequestDelegate HttpCookieAppends = context => { context.Response.Cookies.Append("A", "A"); context.Response.Cookies.Append("B", "B", new CookieOptions { HttpOnly = false }); @@ -37,7 +37,7 @@ public class CookiePolicyTests context.Response.Cookies.Append("D", "D", new CookieOptions { HttpOnly = true }); return Task.FromResult(0); }; - private RequestDelegate SameSiteCookieAppends = context => + private readonly RequestDelegate SameSiteCookieAppends = context => { context.Response.Cookies.Append("A", "A"); context.Response.Cookies.Append("B", "B", new CookieOptions()); diff --git a/src/Servers/Connections.Abstractions/src/DefaultConnectionContext.cs b/src/Servers/Connections.Abstractions/src/DefaultConnectionContext.cs index f64e71958783..3b474fde5e9f 100644 --- a/src/Servers/Connections.Abstractions/src/DefaultConnectionContext.cs +++ b/src/Servers/Connections.Abstractions/src/DefaultConnectionContext.cs @@ -24,7 +24,7 @@ public class DefaultConnectionContext : ConnectionContext, IConnectionLifetimeFeature, IConnectionEndPointFeature { - private CancellationTokenSource _connectionClosedTokenSource = new CancellationTokenSource(); + private readonly CancellationTokenSource _connectionClosedTokenSource = new CancellationTokenSource(); /// /// Creates the without Pipes to avoid upfront allocations. diff --git a/src/Servers/HttpSys/src/HttpSysListener.cs b/src/Servers/HttpSys/src/HttpSysListener.cs index 2007c64f95ad..84523cf52fe4 100644 --- a/src/Servers/HttpSys/src/HttpSysListener.cs +++ b/src/Servers/HttpSys/src/HttpSysListener.cs @@ -37,12 +37,12 @@ internal partial class HttpSysListener : IDisposable private volatile State _state; // m_State is set only within lock blocks, but often read outside locks. - private ServerSession _serverSession; - private UrlGroup _urlGroup; - private RequestQueue _requestQueue; - private DisconnectListener _disconnectListener; + private readonly ServerSession _serverSession; + private readonly UrlGroup _urlGroup; + private readonly RequestQueue _requestQueue; + private readonly DisconnectListener _disconnectListener; - private object _internalLock; + private readonly object _internalLock; public HttpSysListener(HttpSysOptions options, ILoggerFactory loggerFactory) { diff --git a/src/Servers/HttpSys/src/MessagePump.cs b/src/Servers/HttpSys/src/MessagePump.cs index 431cc3942843..9444611a0969 100644 --- a/src/Servers/HttpSys/src/MessagePump.cs +++ b/src/Servers/HttpSys/src/MessagePump.cs @@ -22,7 +22,7 @@ internal partial class MessagePump : IServer private readonly ILogger _logger; private readonly HttpSysOptions _options; - private int _maxAccepts; + private readonly int _maxAccepts; private int _acceptorCounts; private volatile int _stopping; diff --git a/src/Servers/HttpSys/src/NativeInterop/HttpServerSessionHandle.cs b/src/Servers/HttpSys/src/NativeInterop/HttpServerSessionHandle.cs index 903e4d90658f..fca83ecb5fba 100644 --- a/src/Servers/HttpSys/src/NativeInterop/HttpServerSessionHandle.cs +++ b/src/Servers/HttpSys/src/NativeInterop/HttpServerSessionHandle.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys internal sealed class HttpServerSessionHandle : CriticalHandleZeroOrMinusOneIsInvalid { private int disposed; - private ulong serverSessionId; + private readonly ulong serverSessionId; internal HttpServerSessionHandle(ulong id) : base() diff --git a/src/Servers/HttpSys/src/NativeInterop/SafeLibraryHandle.cs b/src/Servers/HttpSys/src/NativeInterop/SafeLibraryHandle.cs index b8b40335d103..9321e8a239ad 100644 --- a/src/Servers/HttpSys/src/NativeInterop/SafeLibraryHandle.cs +++ b/src/Servers/HttpSys/src/NativeInterop/SafeLibraryHandle.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys /// /// Represents a handle to a Windows module (DLL). /// - internal unsafe sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid + internal sealed unsafe class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid { // Called by P/Invoke when returning SafeHandles private SafeLibraryHandle() diff --git a/src/Servers/HttpSys/src/NativeInterop/TokenBindingUtil.cs b/src/Servers/HttpSys/src/NativeInterop/TokenBindingUtil.cs index 56e05a6af5af..a46231bf8997 100644 --- a/src/Servers/HttpSys/src/NativeInterop/TokenBindingUtil.cs +++ b/src/Servers/HttpSys/src/NativeInterop/TokenBindingUtil.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys /// Contains helpers for dealing with TLS token binding. /// // TODO: https://github.com/aspnet/HttpSysServer/issues/231 - internal unsafe static class TokenBindingUtil + internal static unsafe class TokenBindingUtil { private static byte[] ExtractIdentifierBlob(TOKENBINDING_RESULT_DATA* pTokenBindingResultData) { diff --git a/src/Servers/HttpSys/src/NativeInterop/UrlGroup.cs b/src/Servers/HttpSys/src/NativeInterop/UrlGroup.cs index b2a5f68e2034..d01091fdb50b 100644 --- a/src/Servers/HttpSys/src/NativeInterop/UrlGroup.cs +++ b/src/Servers/HttpSys/src/NativeInterop/UrlGroup.cs @@ -18,9 +18,9 @@ internal partial class UrlGroup : IDisposable private readonly ILogger _logger; - private ServerSession? _serverSession; + private readonly ServerSession? _serverSession; private bool _disposed; - private bool _created; + private readonly bool _created; internal unsafe UrlGroup(ServerSession serverSession, ILogger logger) { diff --git a/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs b/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs index cc38851b67f1..ec6819912fd4 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs @@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys { // This class is used to load the client certificate on-demand. Because client certs are optional, all // failures are handled internally and reported via ClientCertException or ClientCertError. - internal unsafe sealed partial class ClientCertLoader : IAsyncResult, IDisposable + internal sealed unsafe partial class ClientCertLoader : IAsyncResult, IDisposable { private const uint CertBoblSize = 1500; private static readonly IOCompletionCallback IOCallback = new IOCompletionCallback(WaitCallback); @@ -30,13 +30,13 @@ internal unsafe sealed partial class ClientCertLoader : IAsyncResult, IDisposabl private byte[]? _backingBuffer; private HttpApiTypes.HTTP_SSL_CLIENT_CERT_INFO* _memoryBlob; private uint _size; - private TaskCompletionSource _tcs; - private RequestContext _requestContext; + private readonly TaskCompletionSource _tcs; + private readonly RequestContext _requestContext; private int _clientCertError; private X509Certificate2? _clientCert; private Exception? _clientCertException; - private CancellationTokenRegistration _cancellationRegistration; + private readonly CancellationTokenRegistration _cancellationRegistration; internal ClientCertLoader(RequestContext requestContext, CancellationToken cancellationToken) { diff --git a/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs b/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs index 7b23136fdf20..120ed198984a 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs @@ -17,7 +17,7 @@ internal partial class RequestStream : Stream { private const int MaxReadSize = 0x20000; // http.sys recommends we limit reads to 128k - private RequestContext _requestContext; + private readonly RequestContext _requestContext; private uint _dataChunkOffset; private int _dataChunkIndex; private long? _maxSize; diff --git a/src/Servers/HttpSys/src/RequestProcessing/RequestStreamAsyncResult.cs b/src/Servers/HttpSys/src/RequestProcessing/RequestStreamAsyncResult.cs index 8f47c4a4be2a..0ab7ccd3c3d8 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/RequestStreamAsyncResult.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/RequestStreamAsyncResult.cs @@ -15,13 +15,13 @@ internal unsafe class RequestStreamAsyncResult : IAsyncResult, IDisposable { private static readonly IOCompletionCallback IOCallback = new IOCompletionCallback(Callback); - private SafeNativeOverlapped? _overlapped; - private IntPtr _pinnedBuffer; - private uint _dataAlreadyRead; - private TaskCompletionSource _tcs; - private RequestStream _requestStream; - private AsyncCallback? _callback; - private CancellationTokenRegistration _cancellationRegistration; + private readonly SafeNativeOverlapped? _overlapped; + private readonly IntPtr _pinnedBuffer; + private readonly uint _dataAlreadyRead; + private readonly TaskCompletionSource _tcs; + private readonly RequestStream _requestStream; + private readonly AsyncCallback? _callback; + private readonly CancellationTokenRegistration _cancellationRegistration; internal RequestStreamAsyncResult(RequestStream requestStream, object? userState, AsyncCallback? callback) { diff --git a/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs b/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs index 96529e027f9f..6e0a1b9dafcd 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys { internal class ResponseBody : Stream { - private RequestContext _requestContext; + private readonly RequestContext _requestContext; private long _leftToWrite = long.MinValue; private bool _skipWrites; private bool _disposed; diff --git a/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.cs b/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.cs index 3bfdaba56fa0..0d2eb8c59dfa 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.cs @@ -15,14 +15,14 @@ internal unsafe partial class ResponseStreamAsyncResult : IAsyncResult, IDisposa { private static readonly IOCompletionCallback IOCallback = new IOCompletionCallback(Callback); - private SafeNativeOverlapped? _overlapped; - private HttpApiTypes.HTTP_DATA_CHUNK[]? _dataChunks; - private FileStream? _fileStream; - private ResponseBody _responseStream; - private TaskCompletionSource _tcs; + private readonly SafeNativeOverlapped? _overlapped; + private readonly HttpApiTypes.HTTP_DATA_CHUNK[]? _dataChunks; + private readonly FileStream? _fileStream; + private readonly ResponseBody _responseStream; + private readonly TaskCompletionSource _tcs; private uint _bytesSent; - private CancellationToken _cancellationToken; - private CancellationTokenRegistration _cancellationRegistration; + private readonly CancellationToken _cancellationToken; + private readonly CancellationTokenRegistration _cancellationRegistration; internal ResponseStreamAsyncResult(ResponseBody responseStream, CancellationToken cancellationToken) { diff --git a/src/Servers/HttpSys/src/TimeoutManager.cs b/src/Servers/HttpSys/src/TimeoutManager.cs index 1455de647dfd..20393c0c78bf 100644 --- a/src/Servers/HttpSys/src/TimeoutManager.cs +++ b/src/Servers/HttpSys/src/TimeoutManager.cs @@ -20,7 +20,7 @@ public sealed class TimeoutManager Marshal.SizeOf(); private UrlGroup? _urlGroup; - private int[] _timeouts; + private readonly int[] _timeouts; private uint _minSendBytesPerSecond; internal TimeoutManager() diff --git a/src/Servers/HttpSys/test/FunctionalTests/Listener/RequestBodyTests.cs b/src/Servers/HttpSys/test/FunctionalTests/Listener/RequestBodyTests.cs index 2de69a8db2a5..da9356ead4c4 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/Listener/RequestBodyTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/Listener/RequestBodyTests.cs @@ -218,7 +218,7 @@ public StaggardContent() public SemaphoreSlim Block { get; private set; } - protected async override Task SerializeToStreamAsync(Stream stream, TransportContext context) + protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { await stream.WriteAsync(new byte[5], 0, 5); await stream.FlushAsync(); diff --git a/src/Servers/HttpSys/test/FunctionalTests/RequestBodyLimitTests.cs b/src/Servers/HttpSys/test/FunctionalTests/RequestBodyLimitTests.cs index d9c26166e64c..87ab2493a0cc 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/RequestBodyLimitTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/RequestBodyLimitTests.cs @@ -427,7 +427,7 @@ public StaggardContent() public SemaphoreSlim Block { get; private set; } - protected async override Task SerializeToStreamAsync(Stream stream, TransportContext context) + protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { await stream.WriteAsync(new byte[10], 0, 10); await stream.FlushAsync(); diff --git a/src/Servers/HttpSys/test/FunctionalTests/RequestBodyTests.cs b/src/Servers/HttpSys/test/FunctionalTests/RequestBodyTests.cs index 9637638d3b7d..224cf2f1709c 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/RequestBodyTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/RequestBodyTests.cs @@ -320,7 +320,7 @@ public StaggardContent() public SemaphoreSlim Block { get; private set; } - protected async override Task SerializeToStreamAsync(Stream stream, TransportContext context) + protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { await stream.WriteAsync(new byte[5], 0, 5); await stream.FlushAsync(); diff --git a/src/Servers/IIS/IIS/src/Core/DuplexStream.cs b/src/Servers/IIS/IIS/src/Core/DuplexStream.cs index 73dbd4cbb98b..c8e608bf14ae 100644 --- a/src/Servers/IIS/IIS/src/Core/DuplexStream.cs +++ b/src/Servers/IIS/IIS/src/Core/DuplexStream.cs @@ -11,8 +11,8 @@ namespace Microsoft.AspNetCore.Server.IIS.Core // See https://github.com/aspnet/IISIntegration/issues/426 internal class DuplexStream : Stream { - private Stream _requestBody; - private Stream _responseBody; + private readonly Stream _requestBody; + private readonly Stream _responseBody; public DuplexStream(Stream requestBody, Stream responseBody) { diff --git a/src/Servers/IIS/IIS/src/NativeMethods.cs b/src/Servers/IIS/IIS/src/NativeMethods.cs index 184a0c09661f..36f2980c9706 100644 --- a/src/Servers/IIS/IIS/src/NativeMethods.cs +++ b/src/Servers/IIS/IIS/src/NativeMethods.cs @@ -49,7 +49,7 @@ public enum REQUEST_NOTIFICATION_STATUS private static extern void http_indicate_completion(NativeSafeHandle pInProcessHandler, REQUEST_NOTIFICATION_STATUS notificationStatus); [DllImport(AspNetCoreModuleDll)] - private unsafe static extern int register_callbacks(NativeSafeHandle pInProcessApplication, + private static extern unsafe int register_callbacks(NativeSafeHandle pInProcessApplication, delegate* unmanaged requestCallback, delegate* unmanaged shutdownCallback, delegate* unmanaged disconnectCallback, diff --git a/src/Servers/IIS/IISIntegration/src/ForwardedTlsConnectionFeature.cs b/src/Servers/IIS/IISIntegration/src/ForwardedTlsConnectionFeature.cs index 5b4727bcee80..8935ebeb0e40 100644 --- a/src/Servers/IIS/IISIntegration/src/ForwardedTlsConnectionFeature.cs +++ b/src/Servers/IIS/IISIntegration/src/ForwardedTlsConnectionFeature.cs @@ -15,7 +15,7 @@ internal class ForwardedTlsConnectionFeature : ITlsConnectionFeature { private StringValues _header; private X509Certificate2? _certificate; - private ILogger _logger; + private readonly ILogger _logger; public ForwardedTlsConnectionFeature(ILogger logger, StringValues header) { diff --git a/src/Servers/IIS/IntegrationTesting.IIS/src/IISDeployer.cs b/src/Servers/IIS/IntegrationTesting.IIS/src/IISDeployer.cs index 512da59e0f31..66c4e4373ac8 100644 --- a/src/Servers/IIS/IntegrationTesting.IIS/src/IISDeployer.cs +++ b/src/Servers/IIS/IntegrationTesting.IIS/src/IISDeployer.cs @@ -26,7 +26,7 @@ public class IISDeployer : IISDeployerBase private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(60); private static readonly TimeSpan _retryDelay = TimeSpan.FromMilliseconds(100); - private CancellationTokenSource _hostShutdownToken = new CancellationTokenSource(); + private readonly CancellationTokenSource _hostShutdownToken = new CancellationTokenSource(); private string _configPath; private string _debugLogFile; diff --git a/src/Servers/Kestrel/Core/src/Internal/ConfigurationReader.cs b/src/Servers/Kestrel/Core/src/Internal/ConfigurationReader.cs index 95deb07e3433..7969c14fc089 100644 --- a/src/Servers/Kestrel/Core/src/Internal/ConfigurationReader.cs +++ b/src/Servers/Kestrel/Core/src/Internal/ConfigurationReader.cs @@ -259,7 +259,7 @@ internal class EndpointDefaults // } internal class EndpointConfig { - private ConfigSectionClone _configSectionClone; + private readonly ConfigSectionClone _configSectionClone; public EndpointConfig( string name, diff --git a/src/Servers/Kestrel/Core/src/Internal/Http/HttpHeaders.cs b/src/Servers/Kestrel/Core/src/Internal/Http/HttpHeaders.cs index e27b38651920..c6dd7c1d6b50 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http/HttpHeaders.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http/HttpHeaders.cs @@ -299,9 +299,9 @@ public static void ValidateHeaderNameCharacters(string headerCharacters) #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; + private static readonly StringValues ConnectionValueKeepAlive = KeepAlive; + private static readonly StringValues ConnectionValueClose = "close"; + private static readonly StringValues ConnectionValueUpgrade = HeaderNames.Upgrade; public static ConnectionOptions ParseConnection(HttpHeaders headers) { diff --git a/src/Servers/Kestrel/Core/src/Internal/Http3/Http3FrameWriter.cs b/src/Servers/Kestrel/Core/src/Internal/Http3/Http3FrameWriter.cs index 1584d9af16d4..2a1f21ef0b5e 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http3/Http3FrameWriter.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http3/Http3FrameWriter.cs @@ -45,7 +45,7 @@ internal class Http3FrameWriter // Write headers to a buffer that can grow. Possible performance improvement // by writing directly to output writer (difficult as frame length is prefixed). private readonly ArrayBufferWriter _headerEncodingBuffer; - private Http3HeadersEnumerator _headersEnumerator = new(); + private readonly Http3HeadersEnumerator _headersEnumerator = new(); private int _headersTotalSize; private long _unflushedBytes; diff --git a/src/Servers/Kestrel/Core/src/KestrelServer.cs b/src/Servers/Kestrel/Core/src/KestrelServer.cs index b949df894142..619654199e0d 100644 --- a/src/Servers/Kestrel/Core/src/KestrelServer.cs +++ b/src/Servers/Kestrel/Core/src/KestrelServer.cs @@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core /// public class KestrelServer : IServer { - private KestrelServerImpl _innerKestrelServer; + private readonly KestrelServerImpl _innerKestrelServer; /// /// Initializes a new instance of . diff --git a/src/Servers/Kestrel/Core/src/Middleware/Internal/LoggingStream.cs b/src/Servers/Kestrel/Core/src/Middleware/Internal/LoggingStream.cs index 98f907c6f6cd..b16fee443cad 100644 --- a/src/Servers/Kestrel/Core/src/Middleware/Internal/LoggingStream.cs +++ b/src/Servers/Kestrel/Core/src/Middleware/Internal/LoggingStream.cs @@ -91,7 +91,7 @@ public override int Read(Span destination) return read; } - public async override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { int read = await _inner.ReadAsync(buffer.AsMemory(offset, count), cancellationToken); Log("ReadAsync", new ReadOnlySpan(buffer, offset, read)); diff --git a/src/Servers/Kestrel/Core/test/Http1ConnectionTests.cs b/src/Servers/Kestrel/Core/test/Http1ConnectionTests.cs index d30b00f598b4..2463a878e94b 100644 --- a/src/Servers/Kestrel/Core/test/Http1ConnectionTests.cs +++ b/src/Servers/Kestrel/Core/test/Http1ConnectionTests.cs @@ -38,7 +38,7 @@ public class Http1ConnectionTests : IDisposable private readonly MemoryPool _pipelineFactory; private SequencePosition _consumed; private SequencePosition _examined; - private Mock _timeoutControl; + private readonly Mock _timeoutControl; public Http1ConnectionTests() { @@ -1160,7 +1160,7 @@ public static TheoryData QueryStringWithNullCharData private class RequestHeadersWrapper : IHeaderDictionary { - IHeaderDictionary _innerHeaders; + readonly IHeaderDictionary _innerHeaders; public RequestHeadersWrapper(IHeaderDictionary headers) { diff --git a/src/Servers/Kestrel/Core/test/Http2FrameWriterTests.cs b/src/Servers/Kestrel/Core/test/Http2FrameWriterTests.cs index 03a4b818652d..8ab3c264181a 100644 --- a/src/Servers/Kestrel/Core/test/Http2FrameWriterTests.cs +++ b/src/Servers/Kestrel/Core/test/Http2FrameWriterTests.cs @@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class Http2FrameWriterTests { - private MemoryPool _dirtyMemoryPool; + private readonly MemoryPool _dirtyMemoryPool; public Http2FrameWriterTests() { diff --git a/src/Servers/Kestrel/Core/test/Http3FrameWriterTests.cs b/src/Servers/Kestrel/Core/test/Http3FrameWriterTests.cs index b3e39012de69..1ea9b566bc5b 100644 --- a/src/Servers/Kestrel/Core/test/Http3FrameWriterTests.cs +++ b/src/Servers/Kestrel/Core/test/Http3FrameWriterTests.cs @@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class Http3FrameWriterTests { - private MemoryPool _dirtyMemoryPool; + private readonly MemoryPool _dirtyMemoryPool; public Http3FrameWriterTests() { diff --git a/src/Servers/Kestrel/Core/test/HttpParserTests.cs b/src/Servers/Kestrel/Core/test/HttpParserTests.cs index 058f170c91a5..d2b9983369b4 100644 --- a/src/Servers/Kestrel/Core/test/HttpParserTests.cs +++ b/src/Servers/Kestrel/Core/test/HttpParserTests.cs @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class HttpParserTests { - private static IKestrelTrace _nullTrace = Mock.Of(); + private static readonly IKestrelTrace _nullTrace = Mock.Of(); [Theory] [MemberData(nameof(RequestLineValidData))] diff --git a/src/Servers/Kestrel/Core/test/KnownStringsTests.cs b/src/Servers/Kestrel/Core/test/KnownStringsTests.cs index a78099ee0612..d1b9030311cc 100644 --- a/src/Servers/Kestrel/Core/test/KnownStringsTests.cs +++ b/src/Servers/Kestrel/Core/test/KnownStringsTests.cs @@ -13,29 +13,29 @@ namespace Microsoft.AspNetCore.Server.KestrelTests { public class KnownStringsTests { - static byte[] _methodConnect = Encoding.ASCII.GetBytes("CONNECT "); - static byte[] _methodDelete = Encoding.ASCII.GetBytes("DELETE \0"); - static byte[] _methodGet = Encoding.ASCII.GetBytes("GET "); - static byte[] _methodHead = Encoding.ASCII.GetBytes("HEAD \0\0\0"); - static byte[] _methodPatch = Encoding.ASCII.GetBytes("PATCH \0\0"); - static byte[] _methodPost = Encoding.ASCII.GetBytes("POST \0\0\0"); - static byte[] _methodPut = Encoding.ASCII.GetBytes("PUT \0\0\0\0"); - static byte[] _methodOptions = Encoding.ASCII.GetBytes("OPTIONS "); - static byte[] _methodTrace = Encoding.ASCII.GetBytes("TRACE \0\0"); + static readonly byte[] _methodConnect = Encoding.ASCII.GetBytes("CONNECT "); + static readonly byte[] _methodDelete = Encoding.ASCII.GetBytes("DELETE \0"); + static readonly byte[] _methodGet = Encoding.ASCII.GetBytes("GET "); + static readonly byte[] _methodHead = Encoding.ASCII.GetBytes("HEAD \0\0\0"); + static readonly byte[] _methodPatch = Encoding.ASCII.GetBytes("PATCH \0\0"); + static readonly byte[] _methodPost = Encoding.ASCII.GetBytes("POST \0\0\0"); + static readonly byte[] _methodPut = Encoding.ASCII.GetBytes("PUT \0\0\0\0"); + static readonly byte[] _methodOptions = Encoding.ASCII.GetBytes("OPTIONS "); + static readonly byte[] _methodTrace = Encoding.ASCII.GetBytes("TRACE \0\0"); const int MagicNumber = 0x0600000C; - static byte[] _invalidMethod1 = BitConverter.GetBytes((ulong)MagicNumber); - static byte[] _invalidMethod2 = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; - static byte[] _invalidMethod3 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - static byte[] _invalidMethod4 = Encoding.ASCII.GetBytes("CONNECT_"); - static byte[] _invalidMethod5 = Encoding.ASCII.GetBytes("DELETE_\0"); - static byte[] _invalidMethod6 = Encoding.ASCII.GetBytes("GET_"); - static byte[] _invalidMethod7 = Encoding.ASCII.GetBytes("HEAD_\0\0\0"); - static byte[] _invalidMethod8 = Encoding.ASCII.GetBytes("PATCH_\0\0"); - static byte[] _invalidMethod9 = Encoding.ASCII.GetBytes("POST_\0\0\0"); - static byte[] _invalidMethod10 = Encoding.ASCII.GetBytes("PUT_\0\0\0\0"); - static byte[] _invalidMethod11 = Encoding.ASCII.GetBytes("OPTIONS_"); - static byte[] _invalidMethod12 = Encoding.ASCII.GetBytes("TRACE_\0\0"); + static readonly byte[] _invalidMethod1 = BitConverter.GetBytes((ulong)MagicNumber); + static readonly byte[] _invalidMethod2 = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + static readonly byte[] _invalidMethod3 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + static readonly byte[] _invalidMethod4 = Encoding.ASCII.GetBytes("CONNECT_"); + static readonly byte[] _invalidMethod5 = Encoding.ASCII.GetBytes("DELETE_\0"); + static readonly byte[] _invalidMethod6 = Encoding.ASCII.GetBytes("GET_"); + static readonly byte[] _invalidMethod7 = Encoding.ASCII.GetBytes("HEAD_\0\0\0"); + static readonly byte[] _invalidMethod8 = Encoding.ASCII.GetBytes("PATCH_\0\0"); + static readonly byte[] _invalidMethod9 = Encoding.ASCII.GetBytes("POST_\0\0\0"); + static readonly byte[] _invalidMethod10 = Encoding.ASCII.GetBytes("PUT_\0\0\0\0"); + static readonly byte[] _invalidMethod11 = Encoding.ASCII.GetBytes("OPTIONS_"); + static readonly byte[] _invalidMethod12 = Encoding.ASCII.GetBytes("TRACE_\0\0"); [MethodImpl(MethodImplOptions.AggressiveInlining)] private static object[] CreateTestDataEntry(byte[] methodData, int expectedMethod, int expectedLength, bool expectedResult) diff --git a/src/Servers/Kestrel/Core/test/LoggingStreamTests.cs b/src/Servers/Kestrel/Core/test/LoggingStreamTests.cs index 194a2648f6dc..61317235b24a 100644 --- a/src/Servers/Kestrel/Core/test/LoggingStreamTests.cs +++ b/src/Servers/Kestrel/Core/test/LoggingStreamTests.cs @@ -52,7 +52,7 @@ public void ExtraNewLineIsNotLoggedGivenEmptyBuffer() private class MockLogger : ILogger { - private StringBuilder _logs = new(); + private readonly StringBuilder _logs = new(); public string Logs => _logs.ToString(); diff --git a/src/Servers/Kestrel/Core/test/StartLineTests.cs b/src/Servers/Kestrel/Core/test/StartLineTests.cs index 1657199345ff..d7dc7f2ed665 100644 --- a/src/Servers/Kestrel/Core/test/StartLineTests.cs +++ b/src/Servers/Kestrel/Core/test/StartLineTests.cs @@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests { public class StartLineTests : IDisposable { - private readonly static IKestrelTrace _trace = Mock.Of(); + private static readonly IKestrelTrace _trace = Mock.Of(); private IDuplexPipe Transport { get; } private MemoryPool MemoryPool { get; } diff --git a/src/Servers/Kestrel/Core/test/TestHelpers/TestInput.cs b/src/Servers/Kestrel/Core/test/TestHelpers/TestInput.cs index 96ecdce60a96..175d52e3bfb9 100644 --- a/src/Servers/Kestrel/Core/test/TestHelpers/TestInput.cs +++ b/src/Servers/Kestrel/Core/test/TestHelpers/TestInput.cs @@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { class TestInput : IDisposable { - private MemoryPool _memoryPool; + private readonly MemoryPool _memoryPool; public TestInput(IKestrelTrace log = null, ITimeoutControl timeoutControl = null) { diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/LibuvAwaitable.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/LibuvAwaitable.cs index 7d8f85cdb01e..5a29293e0a60 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/LibuvAwaitable.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/LibuvAwaitable.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal { internal class LibuvAwaitable : ICriticalNotifyCompletion where TRequest : UvRequest { - private readonly static Action _callbackCompleted = () => { }; + private static readonly Action _callbackCompleted = () => { }; private Action _callback; diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/ListenerPrimary.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/ListenerPrimary.cs index 9fee8c9ba7b5..a478fc12b6f6 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/ListenerPrimary.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/ListenerPrimary.cs @@ -166,8 +166,8 @@ private void DetachFromIOCP(UvHandle handle) #pragma warning disable CA1823 // Avoid unused private fields private struct IO_STATUS_BLOCK { - uint status; - ulong information; + readonly uint status; + readonly ulong information; } #pragma warning restore CA1823 diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/LibuvFunctions.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/LibuvFunctions.cs index 4fb0a2b7e898..d02b13650ac5 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/LibuvFunctions.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/LibuvFunctions.cs @@ -301,18 +301,18 @@ public int try_write(UvStreamHandle handle, uv_buf_t[] bufs, int nbufs) [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void uv_write_cb(IntPtr req, int status); - unsafe protected delegate int uv_write_func(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, uv_write_cb cb); + protected unsafe delegate int uv_write_func(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, uv_write_cb cb); protected uv_write_func _uv_write; - unsafe public void write(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, uv_write_cb cb) + public unsafe void write(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, uv_write_cb cb) { req.Validate(); handle.Validate(); ThrowIfErrored(_uv_write(req, handle, bufs, nbufs, cb)); } - unsafe protected delegate int uv_write2_func(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, UvStreamHandle sendHandle, uv_write_cb cb); + protected unsafe delegate int uv_write2_func(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, UvStreamHandle sendHandle, uv_write_cb cb); protected uv_write2_func _uv_write2; - unsafe public void write2(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, UvStreamHandle sendHandle, uv_write_cb cb) + public unsafe void write2(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, UvStreamHandle sendHandle, uv_write_cb cb) { req.Validate(); handle.Validate(); @@ -375,7 +375,7 @@ public void walk(UvLoopHandle loop, uv_walk_cb walk_cb, IntPtr arg) } protected Func _uv_timer_init; - unsafe public void timer_init(UvLoopHandle loop, UvTimerHandle handle) + public unsafe void timer_init(UvLoopHandle loop, UvTimerHandle handle) { loop.Validate(); handle.Validate(); @@ -385,21 +385,21 @@ unsafe public void timer_init(UvLoopHandle loop, UvTimerHandle handle) [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void uv_timer_cb(IntPtr handle); protected Func _uv_timer_start; - unsafe public void timer_start(UvTimerHandle handle, uv_timer_cb cb, long timeout, long repeat) + public unsafe void timer_start(UvTimerHandle handle, uv_timer_cb cb, long timeout, long repeat) { handle.Validate(); ThrowIfErrored(_uv_timer_start(handle, cb, timeout, repeat)); } protected Func _uv_timer_stop; - unsafe public void timer_stop(UvTimerHandle handle) + public unsafe void timer_stop(UvTimerHandle handle) { handle.Validate(); ThrowIfErrored(_uv_timer_stop(handle)); } protected Func _uv_now; - unsafe public long now(UvLoopHandle loop) + public unsafe long now(UvLoopHandle loop) { loop.Validate(); return _uv_now(loop); @@ -519,10 +519,10 @@ private static class NativeMethods public static extern int uv_async_init(UvLoopHandle loop, UvAsyncHandle handle, uv_async_cb cb); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] - public extern static int uv_async_send(UvAsyncHandle handle); + public static extern int uv_async_send(UvAsyncHandle handle); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl, EntryPoint = "uv_async_send")] - public extern static int uv_unsafe_async_send(IntPtr handle); + public static extern int uv_unsafe_async_send(IntPtr handle); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] public static extern int uv_tcp_init(UvLoopHandle loop, UvTcpHandle handle); @@ -555,10 +555,10 @@ private static class NativeMethods public static extern void uv_pipe_connect(UvConnectRequest req, UvPipeHandle handle, string name, uv_connect_cb cb); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] - public extern static int uv_pipe_pending_count(UvPipeHandle handle); + public static extern int uv_pipe_pending_count(UvPipeHandle handle); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] - public extern static int uv_read_start(UvStreamHandle handle, uv_alloc_cb alloc_cb, uv_read_cb read_cb); + public static extern int uv_read_start(UvStreamHandle handle, uv_alloc_cb alloc_cb, uv_read_cb read_cb); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] public static extern int uv_read_stop(UvStreamHandle handle); @@ -567,13 +567,13 @@ private static class NativeMethods public static extern int uv_try_write(UvStreamHandle handle, uv_buf_t[] bufs, int nbufs); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] - unsafe public static extern int uv_write(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, uv_write_cb cb); + public static extern unsafe int uv_write(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, uv_write_cb cb); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] - unsafe public static extern int uv_write2(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, UvStreamHandle sendHandle, uv_write_cb cb); + public static extern unsafe int uv_write2(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, UvStreamHandle sendHandle, uv_write_cb cb); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] - public extern static IntPtr uv_err_name(int err); + public static extern IntPtr uv_err_name(int err); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr uv_strerror(int err); @@ -603,19 +603,19 @@ private static class NativeMethods public static extern int uv_walk(UvLoopHandle loop, uv_walk_cb walk_cb, IntPtr arg); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] - unsafe public static extern int uv_timer_init(UvLoopHandle loop, UvTimerHandle handle); + public static extern unsafe int uv_timer_init(UvLoopHandle loop, UvTimerHandle handle); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] - unsafe public static extern int uv_timer_start(UvTimerHandle handle, uv_timer_cb cb, long timeout, long repeat); + public static extern unsafe int uv_timer_start(UvTimerHandle handle, uv_timer_cb cb, long timeout, long repeat); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] - unsafe public static extern int uv_timer_stop(UvTimerHandle handle); + public static extern unsafe int uv_timer_stop(UvTimerHandle handle); [DllImport("libuv", CallingConvention = CallingConvention.Cdecl)] - unsafe public static extern long uv_now(UvLoopHandle loop); + public static extern unsafe long uv_now(UvLoopHandle loop); [DllImport("WS2_32.dll", CallingConvention = CallingConvention.Winapi)] - unsafe public static extern int WSAIoctl( + public static extern unsafe int WSAIoctl( IntPtr socket, int dwIoControlCode, int* lpvInBuffer, diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/SockAddr.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/SockAddr.cs index 45673ff6ce7d..51e80b0408da 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/SockAddr.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/SockAddr.cs @@ -13,9 +13,9 @@ internal struct SockAddr // https://msdn.microsoft.com/en-us/library/windows/desktop/ms740496(v=vs.85).aspx // although the c/c++ header defines it as a 2-byte short followed by a 14-byte array, // the simplest way to reserve the same size in c# is with four nameless long values - private long _field0; - private long _field1; - private long _field2; + private readonly long _field0; + private readonly long _field1; + private readonly long _field2; private long _field3; public SockAddr(long ignored) diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvConnectRequest.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvConnectRequest.cs index 1339c1089ec6..95b3f694f62c 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvConnectRequest.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvConnectRequest.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networkin /// internal class UvConnectRequest : UvRequest { - private readonly static LibuvFunctions.uv_connect_cb _uv_connect_cb = (req, status) => UvConnectCb(req, status); + private static readonly LibuvFunctions.uv_connect_cb _uv_connect_cb = (req, status) => UvConnectCb(req, status); private Action _callback; private object _state; diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvLoopHandle.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvLoopHandle.cs index 72ea03dc1fdf..0616a0e4162e 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvLoopHandle.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvLoopHandle.cs @@ -37,7 +37,7 @@ public long Now() return _uv.now(this); } - unsafe protected override bool ReleaseHandle() + protected override unsafe bool ReleaseHandle() { var memory = handle; if (memory != IntPtr.Zero) diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvMemory.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvMemory.cs index 2d635fa5206c..f6398d8161a3 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvMemory.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvMemory.cs @@ -47,7 +47,7 @@ private set } } - unsafe protected void CreateMemory(LibuvFunctions uv, int threadId, int size) + protected unsafe void CreateMemory(LibuvFunctions uv, int threadId, int size) { _uv = uv; ThreadId = threadId; @@ -56,7 +56,7 @@ unsafe protected void CreateMemory(LibuvFunctions uv, int threadId, int size) *(IntPtr*)handle = GCHandle.ToIntPtr(GCHandle.Alloc(this, _handleType)); } - unsafe protected static void DestroyMemory(IntPtr memory) + protected static unsafe void DestroyMemory(IntPtr memory) { var gcHandlePtr = *(IntPtr*)memory; DestroyMemory(memory, gcHandlePtr); @@ -84,7 +84,7 @@ public void Validate(bool closed = false) Debug.Assert(_threadId == Environment.CurrentManagedThreadId, "ThreadId is incorrect"); } - unsafe public static THandle FromIntPtr(IntPtr handle) + public static unsafe THandle FromIntPtr(IntPtr handle) { GCHandle gcHandle = GCHandle.FromIntPtr(*(IntPtr*)handle); return (THandle)gcHandle.Target; diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvStreamHandle.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvStreamHandle.cs index 5f679f6451e2..f045675a3a19 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvStreamHandle.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvStreamHandle.cs @@ -9,10 +9,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networkin { internal abstract class UvStreamHandle : UvHandle { - private readonly static LibuvFunctions.uv_connection_cb _uv_connection_cb = (handle, status) => UvConnectionCb(handle, status); + private static readonly LibuvFunctions.uv_connection_cb _uv_connection_cb = (handle, status) => UvConnectionCb(handle, status); // Ref and out lamda params must be explicitly typed - private readonly static LibuvFunctions.uv_alloc_cb _uv_alloc_cb = (IntPtr handle, int suggested_size, out LibuvFunctions.uv_buf_t buf) => UvAllocCb(handle, suggested_size, out buf); - private readonly static LibuvFunctions.uv_read_cb _uv_read_cb = (IntPtr handle, int status, ref LibuvFunctions.uv_buf_t buf) => UvReadCb(handle, status, ref buf); + private static readonly LibuvFunctions.uv_alloc_cb _uv_alloc_cb = (IntPtr handle, int suggested_size, out LibuvFunctions.uv_buf_t buf) => UvAllocCb(handle, suggested_size, out buf); + private static readonly LibuvFunctions.uv_read_cb _uv_read_cb = (IntPtr handle, int status, ref LibuvFunctions.uv_buf_t buf) => UvReadCb(handle, status, ref buf); private Action _listenCallback; private object _listenState; diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvTimerHandle.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvTimerHandle.cs index df500edad38e..20cac2bdba5f 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvTimerHandle.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvTimerHandle.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networkin { internal class UvTimerHandle : UvHandle { - private readonly static LibuvFunctions.uv_timer_cb _uv_timer_cb = UvTimerCb; + private static readonly LibuvFunctions.uv_timer_cb _uv_timer_cb = UvTimerCb; private Action _callback; diff --git a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvWriteReq.cs b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvWriteReq.cs index 18687d7d85c0..ab91bb564f62 100644 --- a/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvWriteReq.cs +++ b/src/Servers/Kestrel/Transport.Libuv/src/Internal/Networking/UvWriteReq.cs @@ -22,9 +22,9 @@ internal class UvWriteReq : UvRequest private object _state; private const int BUFFER_COUNT = 4; - private LibuvAwaitable _awaitable = new LibuvAwaitable(); - private List _pins = new List(BUFFER_COUNT + 1); - private List _handles = new List(BUFFER_COUNT + 1); + private readonly LibuvAwaitable _awaitable = new LibuvAwaitable(); + private readonly List _pins = new List(BUFFER_COUNT + 1); + private readonly List _handles = new List(BUFFER_COUNT + 1); public UvWriteReq(ILibuvTrace logger) : base(logger) { diff --git a/src/Servers/Kestrel/Transport.Libuv/test/TestHelpers/MockLibuv.cs b/src/Servers/Kestrel/Transport.Libuv/test/TestHelpers/MockLibuv.cs index f4828473486f..33537655dd7f 100644 --- a/src/Servers/Kestrel/Transport.Libuv/test/TestHelpers/MockLibuv.cs +++ b/src/Servers/Kestrel/Transport.Libuv/test/TestHelpers/MockLibuv.cs @@ -22,7 +22,7 @@ internal class MockLibuv : LibuvFunctions private readonly string _stackTrace; - unsafe public MockLibuv() + public unsafe MockLibuv() : base(onlyForTesting: true) { _stackTrace = Environment.StackTrace; @@ -157,7 +157,7 @@ private int UvReadStart(UvStreamHandle handle, uv_alloc_cb allocCallback, uv_rea return 0; } - unsafe private int UvWrite(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, uv_write_cb cb) + private unsafe int UvWrite(UvRequest req, UvStreamHandle handle, uv_buf_t* bufs, int nbufs, uv_write_cb cb) { return OnWrite(handle, nbufs, status => cb(req.InternalGetHandle(), status)); } diff --git a/src/Servers/Kestrel/perf/Microbenchmarks/IntegerDecoderBenchmark.cs b/src/Servers/Kestrel/perf/Microbenchmarks/IntegerDecoderBenchmark.cs index 7290f627df46..8f98f876c99c 100644 --- a/src/Servers/Kestrel/perf/Microbenchmarks/IntegerDecoderBenchmark.cs +++ b/src/Servers/Kestrel/perf/Microbenchmarks/IntegerDecoderBenchmark.cs @@ -10,9 +10,9 @@ public class IntegerDecoderBenchmark { private const int Iterations = 50_000; - private int _prefixLength = 5; // Arbitrary prefix length - private byte _singleByte = 0x1e; // 30 - private byte[] _multiByte = new byte[] { 0x1f, 0xe0, 0xff, 0xff, 0xff, 0x03}; // int32.MaxValue + private readonly int _prefixLength = 5; // Arbitrary prefix length + private readonly byte _singleByte = 0x1e; // 30 + private readonly byte[] _multiByte = new byte[] { 0x1f, 0xe0, 0xff, 0xff, 0xff, 0x03}; // int32.MaxValue [Benchmark(Baseline = true, OperationsPerInvoke = Iterations)] public void DecodeSingleByteInteger() diff --git a/src/Servers/Kestrel/perf/Microbenchmarks/KnownStringsBenchmark.cs b/src/Servers/Kestrel/perf/Microbenchmarks/KnownStringsBenchmark.cs index daa8bc37385e..4dd0cbef4cb4 100644 --- a/src/Servers/Kestrel/perf/Microbenchmarks/KnownStringsBenchmark.cs +++ b/src/Servers/Kestrel/perf/Microbenchmarks/KnownStringsBenchmark.cs @@ -11,17 +11,17 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Microbenchmarks { public class KnownStringsBenchmark { - static byte[] _methodConnect = Encoding.ASCII.GetBytes("CONNECT "); - static byte[] _methodDelete = Encoding.ASCII.GetBytes("DELETE \0"); - static byte[] _methodGet = Encoding.ASCII.GetBytes("GET "); - static byte[] _methodHead = Encoding.ASCII.GetBytes("HEAD \0\0\0"); - static byte[] _methodPatch = Encoding.ASCII.GetBytes("PATCH \0\0"); - static byte[] _methodPost = Encoding.ASCII.GetBytes("POST \0\0\0"); - static byte[] _methodPut = Encoding.ASCII.GetBytes("PUT \0\0\0\0"); - static byte[] _methodOptions = Encoding.ASCII.GetBytes("OPTIONS "); - static byte[] _methodTrace = Encoding.ASCII.GetBytes("TRACE \0\0"); - - static byte[] _version = Encoding.UTF8.GetBytes("HTTP/1.1\r\n"); + static readonly byte[] _methodConnect = Encoding.ASCII.GetBytes("CONNECT "); + static readonly byte[] _methodDelete = Encoding.ASCII.GetBytes("DELETE \0"); + static readonly byte[] _methodGet = Encoding.ASCII.GetBytes("GET "); + static readonly byte[] _methodHead = Encoding.ASCII.GetBytes("HEAD \0\0\0"); + static readonly byte[] _methodPatch = Encoding.ASCII.GetBytes("PATCH \0\0"); + static readonly byte[] _methodPost = Encoding.ASCII.GetBytes("POST \0\0\0"); + static readonly byte[] _methodPut = Encoding.ASCII.GetBytes("PUT \0\0\0\0"); + static readonly byte[] _methodOptions = Encoding.ASCII.GetBytes("OPTIONS "); + static readonly byte[] _methodTrace = Encoding.ASCII.GetBytes("TRACE \0\0"); + + static readonly byte[] _version = Encoding.UTF8.GetBytes("HTTP/1.1\r\n"); const int loops = 1000; [Benchmark(OperationsPerInvoke = loops * 10)] diff --git a/src/Servers/Kestrel/perf/Microbenchmarks/ResponseHeadersWritingBenchmark.cs b/src/Servers/Kestrel/perf/Microbenchmarks/ResponseHeadersWritingBenchmark.cs index 1c7282375aa2..7825628bc630 100644 --- a/src/Servers/Kestrel/perf/Microbenchmarks/ResponseHeadersWritingBenchmark.cs +++ b/src/Servers/Kestrel/perf/Microbenchmarks/ResponseHeadersWritingBenchmark.cs @@ -193,7 +193,7 @@ public void IterationSetup() public class Writer : PipeWriter { - private Memory _memory = new byte[4096 * 4]; + private readonly Memory _memory = new byte[4096 * 4]; public override Memory GetMemory(int sizeHint = 0) => _memory; diff --git a/src/Servers/Kestrel/perf/Microbenchmarks/SchedulerBenchmark.cs b/src/Servers/Kestrel/perf/Microbenchmarks/SchedulerBenchmark.cs index bed2e9211671..00e1bbd11e1b 100644 --- a/src/Servers/Kestrel/perf/Microbenchmarks/SchedulerBenchmark.cs +++ b/src/Servers/Kestrel/perf/Microbenchmarks/SchedulerBenchmark.cs @@ -17,15 +17,15 @@ public class SchedulerBenchmark private const int OuterLoopCount = 64; private const int OperationsPerInvoke = InnerLoopCount * OuterLoopCount; - private readonly static int IOQueueCount = Math.Min(Environment.ProcessorCount, 16); + private static readonly int IOQueueCount = Math.Min(Environment.ProcessorCount, 16); private PipeScheduler[] _ioQueueSchedulers; private PipeScheduler[] _threadPoolSchedulers; private PipeScheduler[] _inlineSchedulers; - private SemaphoreSlim _semaphore = new SemaphoreSlim(0); + private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0); private int _totalToReport; - private PaddedInteger[] _counters = new PaddedInteger[OuterLoopCount]; + private readonly PaddedInteger[] _counters = new PaddedInteger[OuterLoopCount]; private Func _parallelAction; private Action _action; diff --git a/src/Servers/Kestrel/samples/LargeResponseApp/Startup.cs b/src/Servers/Kestrel/samples/LargeResponseApp/Startup.cs index 55d2bf49e37c..3da117654e83 100644 --- a/src/Servers/Kestrel/samples/LargeResponseApp/Startup.cs +++ b/src/Servers/Kestrel/samples/LargeResponseApp/Startup.cs @@ -16,7 +16,7 @@ public class Startup { private const int _chunkSize = 4096; private const int _defaultNumChunks = 16; - private static byte[] _chunk = Encoding.UTF8.GetBytes(new string('a', _chunkSize)); + private static readonly byte[] _chunk = Encoding.UTF8.GetBytes(new string('a', _chunkSize)); public void Configure(IApplicationBuilder app) { diff --git a/src/Servers/Kestrel/samples/SampleApp/ClientCertBufferingFeature.cs b/src/Servers/Kestrel/samples/SampleApp/ClientCertBufferingFeature.cs index e14d20d1b684..c19dc9af883e 100644 --- a/src/Servers/Kestrel/samples/SampleApp/ClientCertBufferingFeature.cs +++ b/src/Servers/Kestrel/samples/SampleApp/ClientCertBufferingFeature.cs @@ -39,8 +39,8 @@ public static IApplicationBuilder UseClientCertBuffering(this IApplicationBuilde internal class ClientCertBufferingFeature : ITlsConnectionFeature { - private ITlsConnectionFeature _tlsFeature; - private HttpContext _context; + private readonly ITlsConnectionFeature _tlsFeature; + private readonly HttpContext _context; public ClientCertBufferingFeature(ITlsConnectionFeature tlsFeature, HttpContext context) { diff --git a/src/Servers/Kestrel/shared/KnownHeaders.cs b/src/Servers/Kestrel/shared/KnownHeaders.cs index 6c0d60d6b092..de949e005b52 100644 --- a/src/Servers/Kestrel/shared/KnownHeaders.cs +++ b/src/Servers/Kestrel/shared/KnownHeaders.cs @@ -15,10 +15,10 @@ namespace CodeGenerator { public class KnownHeaders { - public readonly static KnownHeader[] RequestHeaders; - public readonly static KnownHeader[] ResponseHeaders; - public readonly static KnownHeader[] ResponseTrailers; - public readonly static string[] InternalHeaderAccessors = new[] + public static readonly KnownHeader[] RequestHeaders; + public static readonly KnownHeader[] ResponseHeaders; + public static readonly KnownHeader[] ResponseTrailers; + public static readonly string[] InternalHeaderAccessors = new[] { HeaderNames.Allow, HeaderNames.AltSvc, @@ -34,12 +34,12 @@ public class KnownHeaders public static readonly string[] DefinedHeaderNames = typeof(HeaderNames).GetFields(BindingFlags.Static | BindingFlags.Public).Select(h => h.Name).ToArray(); - public readonly static string[] ObsoleteHeaderNames = new[] + public static readonly string[] ObsoleteHeaderNames = new[] { HeaderNames.DNT, }; - public readonly static string[] PsuedoHeaderNames = new[] + public static readonly string[] PsuedoHeaderNames = new[] { "Authority", // :authority "Method", // :method @@ -48,7 +48,7 @@ public class KnownHeaders "Status" // :status }; - public readonly static string[] NonApiHeaders = + public static readonly string[] NonApiHeaders = ObsoleteHeaderNames .Concat(PsuedoHeaderNames) .ToArray(); @@ -58,7 +58,7 @@ public class KnownHeaders .Except(NonApiHeaders) .ToArray(); - public readonly static long InvalidH2H3ResponseHeadersBits; + public static readonly long InvalidH2H3ResponseHeadersBits; static KnownHeaders() { diff --git a/src/Servers/Kestrel/shared/test/MockLogger.cs b/src/Servers/Kestrel/shared/test/MockLogger.cs index f5fd9008fec8..ac7d7f42b6fa 100644 --- a/src/Servers/Kestrel/shared/test/MockLogger.cs +++ b/src/Servers/Kestrel/shared/test/MockLogger.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Testing { public class MockLogger : ILogger { - private List _messages = new List(); + private readonly List _messages = new List(); public IDisposable BeginScope(TState state) => NullScope.Instance; diff --git a/src/Servers/Kestrel/shared/test/PassThroughConnectionMiddleware.cs b/src/Servers/Kestrel/shared/test/PassThroughConnectionMiddleware.cs index 73be085c3546..60b8a6c1ff05 100644 --- a/src/Servers/Kestrel/shared/test/PassThroughConnectionMiddleware.cs +++ b/src/Servers/Kestrel/shared/test/PassThroughConnectionMiddleware.cs @@ -38,7 +38,7 @@ public PassThroughDuplexPipe(IDuplexPipe duplexPipe) private class PassThroughPipeWriter : PipeWriter { - private PipeWriter _output; + private readonly PipeWriter _output; public PassThroughPipeWriter(PipeWriter output) { @@ -60,7 +60,7 @@ public PassThroughPipeWriter(PipeWriter output) private class PassThroughPipeReader : PipeReader { - private PipeReader _input; + private readonly PipeReader _input; public PassThroughPipeReader(PipeReader input) { diff --git a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs index 25025c4d8c4b..f743840e625b 100644 --- a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs +++ b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs @@ -29,7 +29,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests /// internal class TestServer : IAsyncDisposable, IStartup { - private IHost _host; + private readonly IHost _host; private ListenOptions _listenOptions; private readonly RequestDelegate _app; diff --git a/src/Servers/Kestrel/test/FunctionalTests/Http2/HandshakeTests.cs b/src/Servers/Kestrel/test/FunctionalTests/Http2/HandshakeTests.cs index 2c28ba950a76..d389ea0c575c 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/Http2/HandshakeTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/Http2/HandshakeTests.cs @@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests.Http2 { public class HandshakeTests : LoggedTest { - private static X509Certificate2 _x509Certificate2 = TestResources.GetTestCertificate(); + private static readonly X509Certificate2 _x509Certificate2 = TestResources.GetTestCertificate(); public HttpClient Client { get; set; } diff --git a/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs b/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs index 67c3ae4b6593..dbe923393d03 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs @@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests.Http2 [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)] public class ShutdownTests : TestApplicationErrorLoggerLoggedTest { - private static X509Certificate2 _x509Certificate2 = TestResources.GetTestCertificate(); + private static readonly X509Certificate2 _x509Certificate2 = TestResources.GetTestCertificate(); private HttpClient Client { get; set; } private List ReceivedFrames { get; } = new List(); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs index d56ed67df83e..dc15e6ccfad9 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs @@ -33,7 +33,7 @@ public class EventSourceTests : LoggedTest // To log all KestrelEventSource events, add `_listener = new TestEventListener(Logger);` to the start of the test method. // We could always construct TestEventListener with the test logger, but other concurrent tests could make this noisy. - private TestEventListener _listener = new TestEventListener(); + private readonly TestEventListener _listener = new TestEventListener(); [Fact] public async Task Http1_EmitsStartAndStopEventsWithActivityIds() diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/TlsTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/TlsTests.cs index fc6ef2eff1a4..015d1cc1dd1c 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/TlsTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/TlsTests.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.Http2 { public class TlsTests : LoggedTest { - private static X509Certificate2 _x509Certificate2 = TestResources.GetTestCertificate(); + private static readonly X509Certificate2 _x509Certificate2 = TestResources.GetTestCertificate(); [ConditionalFact] [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "Missing SslStream ALPN support: https://github.com/dotnet/runtime/issues/27727")] diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsTests.cs index d2a6ffd47de3..fbaf1d9d355c 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpsTests.cs @@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests { public class HttpsTests : LoggedTest { - private static X509Certificate2 _x509Certificate2 = TestResources.GetTestCertificate(); + private static readonly X509Certificate2 _x509Certificate2 = TestResources.GetTestCertificate(); private KestrelServerOptions CreateServerOptions() { @@ -653,7 +653,7 @@ public void Dispose() private class HttpsConnectionFilterLogger : ILogger { - private int? _expectedEventId; + private readonly int? _expectedEventId; public HttpsConnectionFilterLogger() { diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/InMemoryTransportFactory.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/InMemoryTransportFactory.cs index 6c5ff148821c..bf66f5a2d188 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/InMemoryTransportFactory.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/InMemoryTransportFactory.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTrans { internal class InMemoryTransportFactory : IConnectionListenerFactory, IConnectionListener { - private Channel _acceptQueue = Channel.CreateUnbounded(); + private readonly Channel _acceptQueue = Channel.CreateUnbounded(); public EndPoint EndPoint { get; set; } diff --git a/src/Servers/Kestrel/test/Interop.FunctionalTests/HttpClientHttp2InteropTests.cs b/src/Servers/Kestrel/test/Interop.FunctionalTests/HttpClientHttp2InteropTests.cs index 52f64df37c93..b249c5726744 100644 --- a/src/Servers/Kestrel/test/Interop.FunctionalTests/HttpClientHttp2InteropTests.cs +++ b/src/Servers/Kestrel/test/Interop.FunctionalTests/HttpClientHttp2InteropTests.cs @@ -450,7 +450,7 @@ public async Task ReverseEcho(string scheme) private class StreamingContent : HttpContent { - private TaskCompletionSource _sendStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _sendStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); private Func _sendContent; private TaskCompletionSource _sendComplete; diff --git a/src/Servers/Kestrel/tools/CodeGenerator/HttpUtilities/HttpUtilities.cs b/src/Servers/Kestrel/tools/CodeGenerator/HttpUtilities/HttpUtilities.cs index bb07d8713e5d..c613fd4c9e51 100644 --- a/src/Servers/Kestrel/tools/CodeGenerator/HttpUtilities/HttpUtilities.cs +++ b/src/Servers/Kestrel/tools/CodeGenerator/HttpUtilities/HttpUtilities.cs @@ -308,7 +308,7 @@ private static byte[] GetMaskArray(int n, int length = sizeof(ulong)) return maskArray; } - private unsafe static ulong GetAsciiStringAsLong(string str) + private static unsafe ulong GetAsciiStringAsLong(string str) { Debug.Assert(str.Length == sizeof(ulong), string.Format(CultureInfo.InvariantCulture, "String must be exactly {0} (ASCII) characters long.", sizeof(ulong))); diff --git a/src/Shared/Buffers.MemoryPool/DiagnosticPoolBlock.cs b/src/Shared/Buffers.MemoryPool/DiagnosticPoolBlock.cs index c2fef4a00b20..48aa0ee33d19 100644 --- a/src/Shared/Buffers.MemoryPool/DiagnosticPoolBlock.cs +++ b/src/Shared/Buffers.MemoryPool/DiagnosticPoolBlock.cs @@ -22,7 +22,7 @@ internal sealed class DiagnosticPoolBlock : MemoryManager private readonly IMemoryOwner _memoryOwner; private MemoryHandle? _memoryHandle; - private Memory _memory; + private readonly Memory _memory; private readonly object _syncObj = new object(); private bool _isDisposed; diff --git a/src/Shared/CommandLineUtils/CommandLine/AnsiConsole.cs b/src/Shared/CommandLineUtils/CommandLine/AnsiConsole.cs index 293874f9ba96..128aee1e7387 100644 --- a/src/Shared/CommandLineUtils/CommandLine/AnsiConsole.cs +++ b/src/Shared/CommandLineUtils/CommandLine/AnsiConsole.cs @@ -20,7 +20,7 @@ private AnsiConsole(TextWriter writer, bool useConsoleColor) } private int _boldRecursion; - private bool _useConsoleColor; + private readonly bool _useConsoleColor; public static AnsiConsole GetOutput(bool useConsoleColor) { diff --git a/src/Shared/E2ETesting/BrowserFixture.cs b/src/Shared/E2ETesting/BrowserFixture.cs index a8ca2c0507c9..3216f6fcb1ec 100644 --- a/src/Shared/E2ETesting/BrowserFixture.cs +++ b/src/Shared/E2ETesting/BrowserFixture.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.E2ETesting { public class BrowserFixture : IAsyncLifetime { - private ConcurrentDictionary> _browsers = new ConcurrentDictionary>(); + private readonly ConcurrentDictionary> _browsers = new ConcurrentDictionary>(); public BrowserFixture(IMessageSink diagnosticsMessageSink) { diff --git a/src/Shared/E2ETesting/SauceConnectServer.cs b/src/Shared/E2ETesting/SauceConnectServer.cs index 0aea4d7d9201..8c7101912ec9 100644 --- a/src/Shared/E2ETesting/SauceConnectServer.cs +++ b/src/Shared/E2ETesting/SauceConnectServer.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.E2ETesting { public class SauceConnectServer : IDisposable { - private static SemaphoreSlim _semaphore = new SemaphoreSlim(1); + private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); private Process _process; private string _sentinelPath; @@ -30,7 +30,7 @@ public class SauceConnectServer : IDisposable private static IMessageSink _diagnosticsMessageSink; // 2h - private static int SauceConnectProcessTimeout = 7200; + private const int SauceConnectProcessTimeout = 7200; public SauceConnectServer(IMessageSink diagnosticsMessageSink) { diff --git a/src/Shared/E2ETesting/SeleniumStandaloneServer.cs b/src/Shared/E2ETesting/SeleniumStandaloneServer.cs index c79a72e38574..b4223d30743b 100644 --- a/src/Shared/E2ETesting/SeleniumStandaloneServer.cs +++ b/src/Shared/E2ETesting/SeleniumStandaloneServer.cs @@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.E2ETesting { public class SeleniumStandaloneServer : IDisposable { - private static SemaphoreSlim _semaphore = new SemaphoreSlim(1); + private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); private Process _process; private string _sentinelPath; @@ -31,7 +31,7 @@ public class SeleniumStandaloneServer : IDisposable private static IMessageSink _diagnosticsMessageSink; // 1h 30 min - private static int SeleniumProcessTimeout = 3600; + private const int SeleniumProcessTimeout = 3600; public SeleniumStandaloneServer(IMessageSink diagnosticsMessageSink) { diff --git a/src/Shared/HttpSys/NativeInterop/HttpApiTypes.cs b/src/Shared/HttpSys/NativeInterop/HttpApiTypes.cs index 6388e46fe453..211dfc3d75da 100644 --- a/src/Shared/HttpSys/NativeInterop/HttpApiTypes.cs +++ b/src/Shared/HttpSys/NativeInterop/HttpApiTypes.cs @@ -573,7 +573,7 @@ internal struct HTTP_SERVER_AUTHENTICATION_INFO internal bool DisableNTLMCredentialCaching; internal ulong ExFlags; HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS DigestParams; - HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS BasicParams; + readonly HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS BasicParams; } [StructLayout(LayoutKind.Sequential)] @@ -588,8 +588,8 @@ internal struct HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS [StructLayout(LayoutKind.Sequential)] internal struct HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS { - ushort RealmLength; - char* Realm; + readonly ushort RealmLength; + readonly char* Realm; } [StructLayout(LayoutKind.Sequential)] @@ -680,7 +680,7 @@ internal enum HTTP_CREATE_REQUEST_QUEUE_FLAG : uint internal static class HTTP_RESPONSE_HEADER_ID { - private static string[] _strings = + private static readonly string[] _strings = { "Cache-Control", "Connection", @@ -716,7 +716,7 @@ internal static class HTTP_RESPONSE_HEADER_ID "WWW-Authenticate", }; - private static Dictionary _lookupTable = CreateLookupTable(); + private static readonly Dictionary _lookupTable = CreateLookupTable(); private static Dictionary CreateLookupTable() { diff --git a/src/Shared/HttpSys/NativeInterop/SafeNativeOverlapped.cs b/src/Shared/HttpSys/NativeInterop/SafeNativeOverlapped.cs index 8071ce1f5922..3c2fc95d9af6 100644 --- a/src/Shared/HttpSys/NativeInterop/SafeNativeOverlapped.cs +++ b/src/Shared/HttpSys/NativeInterop/SafeNativeOverlapped.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.HttpSys.Internal internal class SafeNativeOverlapped : SafeHandle { internal static readonly SafeNativeOverlapped Zero = new SafeNativeOverlapped(); - private ThreadPoolBoundHandle? _boundHandle; + private readonly ThreadPoolBoundHandle? _boundHandle; internal SafeNativeOverlapped() : base(IntPtr.Zero, true) diff --git a/src/Shared/HttpSys/NativeInterop/SocketAddress.cs b/src/Shared/HttpSys/NativeInterop/SocketAddress.cs index c8fa2a13ce02..c12bb42acd16 100644 --- a/src/Shared/HttpSys/NativeInterop/SocketAddress.cs +++ b/src/Shared/HttpSys/NativeInterop/SocketAddress.cs @@ -36,8 +36,8 @@ internal class SocketAddress private const int WriteableOffset = 2; - private int _size; - private byte[] _buffer; + private readonly int _size; + private readonly byte[] _buffer; private int _hash; /// diff --git a/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs b/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs index a2cecefb9a46..1d937efa6263 100644 --- a/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs +++ b/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs @@ -38,10 +38,10 @@ internal static class ErrorCodes } [DllImport(api_ms_win_core_io_LIB, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static unsafe extern uint CancelIoEx(SafeHandle handle, SafeNativeOverlapped overlapped); + internal static extern unsafe uint CancelIoEx(SafeHandle handle, SafeNativeOverlapped overlapped); [DllImport(api_ms_win_core_kernel32_legacy_LIB, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static unsafe extern bool SetFileCompletionNotificationModes(SafeHandle handle, FileCompletionNotificationModes modes); + internal static extern unsafe bool SetFileCompletionNotificationModes(SafeHandle handle, FileCompletionNotificationModes modes); [Flags] internal enum FileCompletionNotificationModes : byte diff --git a/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs b/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs index 13ce3ddd63e8..6be9d77b385a 100644 --- a/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs +++ b/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs @@ -21,12 +21,12 @@ internal unsafe class NativeRequestContext : IDisposable private const int AlignmentPadding = 8; private const int DefaultBufferSize = 4096 - AlignmentPadding; private IntPtr _originalBufferAddress; - private bool _useLatin1; + private readonly bool _useLatin1; private HttpApiTypes.HTTP_REQUEST* _nativeRequest; private readonly IMemoryOwner? _backingBuffer; private MemoryHandle _memoryHandle; - private int _bufferAlignment; - private bool _permanentlyPinned; + private readonly int _bufferAlignment; + private readonly bool _permanentlyPinned; private bool _disposed; [MemberNotNullWhen(false, nameof(_backingBuffer))] diff --git a/src/Shared/HttpSys/RequestProcessing/RequestHeaders.cs b/src/Shared/HttpSys/RequestProcessing/RequestHeaders.cs index af850388c901..2a4791d6d3f9 100644 --- a/src/Shared/HttpSys/RequestProcessing/RequestHeaders.cs +++ b/src/Shared/HttpSys/RequestProcessing/RequestHeaders.cs @@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.HttpSys.Internal internal partial class RequestHeaders : IHeaderDictionary { private IDictionary? _extra; - private NativeRequestContext _requestMemoryBlob; + private readonly NativeRequestContext _requestMemoryBlob; private long? _contentLength; private StringValues _contentLengthText; diff --git a/src/Shared/ObjectMethodExecutor/ObjectMethodExecutorFSharpSupport.cs b/src/Shared/ObjectMethodExecutor/ObjectMethodExecutorFSharpSupport.cs index 8c452ba16913..95a40c4e8aec 100644 --- a/src/Shared/ObjectMethodExecutor/ObjectMethodExecutorFSharpSupport.cs +++ b/src/Shared/ObjectMethodExecutor/ObjectMethodExecutorFSharpSupport.cs @@ -23,7 +23,7 @@ namespace Microsoft.Extensions.Internal /// internal static class ObjectMethodExecutorFSharpSupport { - private static object _fsharpValuesCacheLock = new object(); + private static readonly object _fsharpValuesCacheLock = new object(); private static Assembly _fsharpCoreAssembly; private static MethodInfo _fsharpAsyncStartAsTaskGenericMethod; private static PropertyInfo _fsharpOptionOfTaskCreationOptionsNoneProperty; diff --git a/src/Shared/Razor/CaseSensitiveBoundAttributeComparer.cs b/src/Shared/Razor/CaseSensitiveBoundAttributeComparer.cs index 4f7acca92ba4..f8bde3cd478b 100644 --- a/src/Shared/Razor/CaseSensitiveBoundAttributeComparer.cs +++ b/src/Shared/Razor/CaseSensitiveBoundAttributeComparer.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers.Testing { internal class CaseSensitiveTagHelperAttributeComparer : IEqualityComparer { - public readonly static CaseSensitiveTagHelperAttributeComparer Default = + public static readonly CaseSensitiveTagHelperAttributeComparer Default = new CaseSensitiveTagHelperAttributeComparer(); private CaseSensitiveTagHelperAttributeComparer() diff --git a/src/Shared/ServerInfrastructure/BufferWriter.cs b/src/Shared/ServerInfrastructure/BufferWriter.cs index 20529f92b075..c14eb43b80a6 100644 --- a/src/Shared/ServerInfrastructure/BufferWriter.cs +++ b/src/Shared/ServerInfrastructure/BufferWriter.cs @@ -14,7 +14,7 @@ namespace System.Buffers /// /// The underlying . /// - private T _output; + private readonly T _output; /// /// The result of the last call to , less any bytes already "consumed" with . diff --git a/src/SignalR/clients/csharp/Client/test/UnitTests/TestHttpMessageHandler.cs b/src/SignalR/clients/csharp/Client/test/UnitTests/TestHttpMessageHandler.cs index cd90702e29be..6f6bd62e3460 100644 --- a/src/SignalR/clients/csharp/Client/test/UnitTests/TestHttpMessageHandler.cs +++ b/src/SignalR/clients/csharp/Client/test/UnitTests/TestHttpMessageHandler.cs @@ -16,11 +16,11 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests public class TestHttpMessageHandler : HttpMessageHandler { - private List _receivedRequests = new List(); + private readonly List _receivedRequests = new List(); private RequestDelegate _app; private readonly ILogger _logger; - private List> _middleware = new List>(); + private readonly List> _middleware = new List>(); public bool Disposed { get; private set; } diff --git a/src/SignalR/clients/ts/FunctionalTests/EchoConnectionHandler.cs b/src/SignalR/clients/ts/FunctionalTests/EchoConnectionHandler.cs index 8dbdfd28f883..8582f408e5d1 100644 --- a/src/SignalR/clients/ts/FunctionalTests/EchoConnectionHandler.cs +++ b/src/SignalR/clients/ts/FunctionalTests/EchoConnectionHandler.cs @@ -10,7 +10,7 @@ namespace FunctionalTests { public class EchoConnectionHandler : ConnectionHandler { - public async override Task OnConnectedAsync(ConnectionContext connection) + public override async Task OnConnectedAsync(ConnectionContext connection) { var context = connection.GetHttpContext(); // The 'withCredentials' tests wont send a cookie for cross-site requests diff --git a/src/SignalR/common/Http.Connections/test/HttpConnectionDispatcherTests.cs b/src/SignalR/common/Http.Connections/test/HttpConnectionDispatcherTests.cs index 08ecfd8e3977..2d267aa36248 100644 --- a/src/SignalR/common/Http.Connections/test/HttpConnectionDispatcherTests.cs +++ b/src/SignalR/common/Http.Connections/test/HttpConnectionDispatcherTests.cs @@ -2405,7 +2405,7 @@ public class CustomHttpRequestLifetimeFeature : IHttpRequestLifetimeFeature { public CancellationToken RequestAborted { get; set; } - private CancellationTokenSource _cts; + private readonly CancellationTokenSource _cts; public CustomHttpRequestLifetimeFeature() { _cts = new CancellationTokenSource(); @@ -2813,7 +2813,7 @@ public override async Task OnConnectedAsync(ConnectionContext connection) public class TestConnectionHandler : ConnectionHandler { - private TaskCompletionSource _startedTcs = new TaskCompletionSource(); + private readonly TaskCompletionSource _startedTcs = new TaskCompletionSource(); public Task Started => _startedTcs.Task; diff --git a/src/SignalR/common/SignalR.Common/test/Internal/Protocol/MemoryBufferWriterTests.cs b/src/SignalR/common/SignalR.Common/test/Internal/Protocol/MemoryBufferWriterTests.cs index bf167c924ce2..ecc64eeeeb91 100644 --- a/src/SignalR/common/SignalR.Common/test/Internal/Protocol/MemoryBufferWriterTests.cs +++ b/src/SignalR/common/SignalR.Common/test/Internal/Protocol/MemoryBufferWriterTests.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.SignalR.Common.Tests.Internal.Protocol { public class MemoryBufferWriterTests { - private static int MinimumSegmentSize; + private static readonly int MinimumSegmentSize; static MemoryBufferWriterTests() { diff --git a/src/SignalR/common/testassets/Tests.Utils/TestClient.cs b/src/SignalR/common/testassets/Tests.Utils/TestClient.cs index 2f0c2926637d..f158e798d45d 100644 --- a/src/SignalR/common/testassets/Tests.Utils/TestClient.cs +++ b/src/SignalR/common/testassets/Tests.Utils/TestClient.cs @@ -31,7 +31,7 @@ class TestClient : ITransferFormatFeature, IConnectionHeartbeatFeature, IDisposa private List<(Action handler, object state)> _heartbeatHandlers; private static int _id; - private IHubProtocol _protocol; + private readonly IHubProtocol _protocol; private readonly IInvocationBinder _invocationBinder; private readonly CancellationTokenSource _cts; diff --git a/src/SignalR/samples/SocialWeather/Protobuf/WeatherReport.cs b/src/SignalR/samples/SocialWeather/Protobuf/WeatherReport.cs index 80e0726e1c61..9746740b6629 100644 --- a/src/SignalR/samples/SocialWeather/Protobuf/WeatherReport.cs +++ b/src/SignalR/samples/SocialWeather/Protobuf/WeatherReport.cs @@ -20,7 +20,7 @@ public static partial class WeatherReportReflection { public static pbr::FileDescriptor Descriptor { get { return descriptor; } } - private static pbr::FileDescriptor descriptor; + private static readonly pbr::FileDescriptor descriptor; static WeatherReportReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( diff --git a/src/SignalR/samples/SocialWeather/SocialWeatherConnectionHandler.cs b/src/SignalR/samples/SocialWeather/SocialWeatherConnectionHandler.cs index 62dbce825a1a..d190a0f67d0b 100644 --- a/src/SignalR/samples/SocialWeather/SocialWeatherConnectionHandler.cs +++ b/src/SignalR/samples/SocialWeather/SocialWeatherConnectionHandler.cs @@ -23,7 +23,7 @@ public SocialWeatherConnectionHandler(PersistentConnectionLifeTimeManager lifeti _logger = logger; } - public async override Task OnConnectedAsync(ConnectionContext connection) + public override async Task OnConnectedAsync(ConnectionContext connection) { _lifetimeManager.OnConnectedAsync(connection); await ProcessRequests(connection); diff --git a/src/SignalR/server/SignalR/test/HubConnectionHandlerTestUtils/Hubs.cs b/src/SignalR/server/SignalR/test/HubConnectionHandlerTestUtils/Hubs.cs index 089e80a37c61..b22d4cfcebaf 100644 --- a/src/SignalR/server/SignalR/test/HubConnectionHandlerTestUtils/Hubs.cs +++ b/src/SignalR/server/SignalR/test/HubConnectionHandlerTestUtils/Hubs.cs @@ -620,7 +620,7 @@ protected override void Dispose(bool dispose) public class HubWithAsyncDisposable : TestHub { - private AsyncDisposable _disposable; + private readonly AsyncDisposable _disposable; public HubWithAsyncDisposable(AsyncDisposable disposable) { @@ -784,7 +784,7 @@ public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToke public class AsyncEnumerableImplChannelThrows : ChannelReader, IAsyncEnumerable { - private ChannelReader _inner; + private readonly ChannelReader _inner; public AsyncEnumerableImplChannelThrows(ChannelReader inner) { @@ -922,7 +922,7 @@ public override async Task OnConnectedAsync() public class LongRunningHub : Hub { - private TcsService _tcsService; + private readonly TcsService _tcsService; public LongRunningHub(TcsService tcsService) { diff --git a/src/SignalR/server/SignalR/test/HubConnectionHandlerTests.cs b/src/SignalR/server/SignalR/test/HubConnectionHandlerTests.cs index e49decc04370..d70771d6ec5d 100644 --- a/src/SignalR/server/SignalR/test/HubConnectionHandlerTests.cs +++ b/src/SignalR/server/SignalR/test/HubConnectionHandlerTests.cs @@ -2847,7 +2847,7 @@ internal class PipeReaderWrapper : PipeReader { private readonly PipeReader _originalPipeReader; private TaskCompletionSource _waitForRead; - private object _lock = new object(); + private readonly object _lock = new object(); public PipeReaderWrapper(PipeReader pipeReader) { @@ -4557,7 +4557,7 @@ public async Task CanSendThroughIHubContextBaseHub() private class CustomHubActivator : IHubActivator where THub : Hub { public int ReleaseCount; - private IServiceProvider _serviceProvider; + private readonly IServiceProvider _serviceProvider; public TaskCompletionSource ReleaseTask = new TaskCompletionSource(); public TaskCompletionSource CreateTask = new TaskCompletionSource(); diff --git a/src/SignalR/server/SignalR/test/Internal/TypedClientBuilderTests.cs b/src/SignalR/server/SignalR/test/Internal/TypedClientBuilderTests.cs index 2ee9bb7aaaf0..11f723f8602b 100644 --- a/src/SignalR/server/SignalR/test/Internal/TypedClientBuilderTests.cs +++ b/src/SignalR/server/SignalR/test/Internal/TypedClientBuilderTests.cs @@ -275,7 +275,7 @@ public Task SendCoreAsync(string method, object[] args, CancellationToken cancel private struct SendContext { - private TaskCompletionSource _tcs; + private readonly TaskCompletionSource _tcs; public string Method { get; } public object[] Arguments { get; } diff --git a/src/SignalR/server/StackExchangeRedis/test/DefaultHubMessageSerializerTests.cs b/src/SignalR/server/StackExchangeRedis/test/DefaultHubMessageSerializerTests.cs index 0c1ac1f62daa..657c7afa5ab0 100644 --- a/src/SignalR/server/StackExchangeRedis/test/DefaultHubMessageSerializerTests.cs +++ b/src/SignalR/server/StackExchangeRedis/test/DefaultHubMessageSerializerTests.cs @@ -64,7 +64,7 @@ private IHubProtocolResolver CreateHubProtocolResolver(List hubPro return new DefaultHubProtocolResolver(hubProtocols, NullLogger.Instance); } - private static Dictionary _invocationTestData = new[] + private static readonly Dictionary _invocationTestData = new[] { new ProtocolTestData( "Single supported protocol", @@ -132,7 +132,7 @@ public ProtocolTestData(string name, List supportedHubProtocols, i } // The actual invocation message doesn't matter - private static InvocationMessage _testMessage = new InvocationMessage("target", Array.Empty()); + private static readonly InvocationMessage _testMessage = new InvocationMessage("target", Array.Empty()); internal class TestHubProtocol : IHubProtocol { diff --git a/src/SignalR/server/StackExchangeRedis/test/RedisProtocolTests.cs b/src/SignalR/server/StackExchangeRedis/test/RedisProtocolTests.cs index 1afca99c9488..5966157ab6f4 100644 --- a/src/SignalR/server/StackExchangeRedis/test/RedisProtocolTests.cs +++ b/src/SignalR/server/StackExchangeRedis/test/RedisProtocolTests.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests { public class RedisProtocolTests { - private static Dictionary> _ackTestData = new[] + private static readonly Dictionary> _ackTestData = new[] { CreateTestData("Zero", 0, 0x91, 0x00), CreateTestData("Fixnum", 42, 0x91, 0x2A), @@ -51,7 +51,7 @@ public void WriteAck(string testName) Assert.Equal(testData.Encoded, encoded); } - private static Dictionary> _groupCommandTestData = new[] + private static readonly Dictionary> _groupCommandTestData = new[] { CreateTestData("GroupAdd", new RedisGroupCommand(42, "S", GroupAction.Add, "G", "C" ), 0x95, 0x2A, 0xA1, (byte)'S', 0x01, 0xA1, (byte)'G', 0xA1, (byte)'C'), CreateTestData("GroupRemove", new RedisGroupCommand(42, "S", GroupAction.Remove, "G", "C" ), 0x95, 0x2A, 0xA1, (byte)'S', 0x02, 0xA1, (byte)'G', 0xA1, (byte)'C'), @@ -88,10 +88,10 @@ public void WriteGroupCommand(string testName) } // The actual invocation message doesn't matter - private static InvocationMessage _testMessage = new InvocationMessage("target", Array.Empty()); + private static readonly InvocationMessage _testMessage = new InvocationMessage("target", Array.Empty()); // We use a func so we are guaranteed to get a new SerializedHubMessage for each test - private static Dictionary>> _invocationTestData = new[] + private static readonly Dictionary>> _invocationTestData = new[] { CreateTestData>( "NoExcludedIds", diff --git a/src/Testing/src/AssemblyTestLog.cs b/src/Testing/src/AssemblyTestLog.cs index 5ffc577b5cf7..995b2f49d289 100644 --- a/src/Testing/src/AssemblyTestLog.cs +++ b/src/Testing/src/AssemblyTestLog.cs @@ -281,7 +281,7 @@ public void Dispose() private class AssemblyLogTimestampOffsetEnricher : ILogEventEnricher { - private DateTimeOffset? _logStart; + private readonly DateTimeOffset? _logStart; public AssemblyLogTimestampOffsetEnricher(DateTimeOffset? logStart) { @@ -299,7 +299,7 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) private class Disposable : IDisposable { - private Action _action; + private readonly Action _action; public Disposable(Action action) { diff --git a/src/Testing/src/Logging/XunitLoggerProvider.cs b/src/Testing/src/Logging/XunitLoggerProvider.cs index 6902109eff9c..fe311993a9ba 100644 --- a/src/Testing/src/Logging/XunitLoggerProvider.cs +++ b/src/Testing/src/Logging/XunitLoggerProvider.cs @@ -49,7 +49,7 @@ public class XunitLogger : ILogger private readonly string _category; private readonly LogLevel _minLogLevel; private readonly ITestOutputHelper _output; - private DateTimeOffset? _logStart; + private readonly DateTimeOffset? _logStart; public XunitLogger(ITestOutputHelper output, string category, LogLevel minLogLevel, DateTimeOffset? logStart) { diff --git a/src/Testing/src/RepeatContext.cs b/src/Testing/src/RepeatContext.cs index d76a0f177e2a..9c80646a68c1 100644 --- a/src/Testing/src/RepeatContext.cs +++ b/src/Testing/src/RepeatContext.cs @@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.Testing { public class RepeatContext { - private static AsyncLocal _current = new AsyncLocal(); + private static readonly AsyncLocal _current = new AsyncLocal(); public static RepeatContext Current { diff --git a/src/Testing/src/TestContext.cs b/src/Testing/src/TestContext.cs index a702d71ecf16..67c4b2f3a29f 100644 --- a/src/Testing/src/TestContext.cs +++ b/src/Testing/src/TestContext.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Testing /// public sealed class TestContext { - private Lazy _files; + private readonly Lazy _files; public TestContext( Type testClass, diff --git a/src/Testing/src/TestFileOutputContext.cs b/src/Testing/src/TestFileOutputContext.cs index 9ce1d58476cf..f252449948cb 100644 --- a/src/Testing/src/TestFileOutputContext.cs +++ b/src/Testing/src/TestFileOutputContext.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Testing /// public sealed class TestFileOutputContext { - private static char[] InvalidFileChars = new char[] + private static readonly char[] InvalidFileChars = new char[] { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, diff --git a/src/Testing/src/Tracing/CollectingEventListener.cs b/src/Testing/src/Tracing/CollectingEventListener.cs index d22a4996afbd..30c3d9824b5a 100644 --- a/src/Testing/src/Tracing/CollectingEventListener.cs +++ b/src/Testing/src/Tracing/CollectingEventListener.cs @@ -8,12 +8,12 @@ namespace Microsoft.AspNetCore.Testing.Tracing { public class CollectingEventListener : EventListener { - private ConcurrentQueue _events = new ConcurrentQueue(); + private readonly ConcurrentQueue _events = new ConcurrentQueue(); - private object _lock = new object(); + private readonly object _lock = new object(); - private Dictionary _existingSources = new Dictionary(StringComparer.OrdinalIgnoreCase); - private HashSet _requestedEventSources = new HashSet(); + private readonly Dictionary _existingSources = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _requestedEventSources = new HashSet(); public void CollectFrom(string eventSourceName) { diff --git a/src/Testing/src/xunit/MaximumOSVersionAttribute.cs b/src/Testing/src/xunit/MaximumOSVersionAttribute.cs index 19ee1098d2c2..a89f92952774 100644 --- a/src/Testing/src/xunit/MaximumOSVersionAttribute.cs +++ b/src/Testing/src/xunit/MaximumOSVersionAttribute.cs @@ -67,7 +67,7 @@ private static OperatingSystems GetCurrentOS() throw new PlatformNotSupportedException(); } - static private Version GetCurrentOSVersion() + private static Version GetCurrentOSVersion() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { diff --git a/src/Testing/src/xunit/MinimumOsVersionAttribute.cs b/src/Testing/src/xunit/MinimumOsVersionAttribute.cs index 4d016a07e784..e16f20854093 100644 --- a/src/Testing/src/xunit/MinimumOsVersionAttribute.cs +++ b/src/Testing/src/xunit/MinimumOsVersionAttribute.cs @@ -63,7 +63,7 @@ private static OperatingSystems GetCurrentOS() throw new PlatformNotSupportedException(); } - static private Version GetCurrentOSVersion() + private static Version GetCurrentOSVersion() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { diff --git a/src/Testing/src/xunit/OSSkipConditionAttribute.cs b/src/Testing/src/xunit/OSSkipConditionAttribute.cs index 50e3cae19217..82276835f574 100644 --- a/src/Testing/src/xunit/OSSkipConditionAttribute.cs +++ b/src/Testing/src/xunit/OSSkipConditionAttribute.cs @@ -42,7 +42,7 @@ public bool IsMet public string SkipReason { get; set; } = "Test cannot run on this operating system."; - static private OperatingSystems GetCurrentOS() + private static OperatingSystems GetCurrentOS() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { diff --git a/src/Tools/Microsoft.dotnet-openapi/src/HttpClientWrapper.cs b/src/Tools/Microsoft.dotnet-openapi/src/HttpClientWrapper.cs index 4ca5a9ae266a..d1d7dc626b6d 100644 --- a/src/Tools/Microsoft.dotnet-openapi/src/HttpClientWrapper.cs +++ b/src/Tools/Microsoft.dotnet-openapi/src/HttpClientWrapper.cs @@ -41,7 +41,7 @@ public Task GetStreamAsync(string url) public class HttpResponseMessageWrapper : IHttpResponseMessageWrapper { - private HttpResponseMessage _response; + private readonly HttpResponseMessage _response; public HttpResponseMessageWrapper(HttpResponseMessage response) { diff --git a/src/Tools/Shared/TestHelpers/TemporaryDirectory.cs b/src/Tools/Shared/TestHelpers/TemporaryDirectory.cs index fe73ce190226..b65c26912a3d 100644 --- a/src/Tools/Shared/TestHelpers/TemporaryDirectory.cs +++ b/src/Tools/Shared/TestHelpers/TemporaryDirectory.cs @@ -11,10 +11,10 @@ namespace Microsoft.Extensions.Tools.Internal { public class TemporaryDirectory : IDisposable { - private List _projects = new List(); - private List _subdirs = new List(); - private Dictionary _files = new Dictionary(); - private TemporaryDirectory? _parent; + private readonly List _projects = new List(); + private readonly List _subdirs = new List(); + private readonly Dictionary _files = new Dictionary(); + private readonly TemporaryDirectory? _parent; public TemporaryDirectory() { diff --git a/src/Tools/dotnet-user-secrets/src/Internal/SecretsStore.cs b/src/Tools/dotnet-user-secrets/src/Internal/SecretsStore.cs index b865f97248c2..a989b403fe9c 100644 --- a/src/Tools/dotnet-user-secrets/src/Internal/SecretsStore.cs +++ b/src/Tools/dotnet-user-secrets/src/Internal/SecretsStore.cs @@ -20,7 +20,7 @@ namespace Microsoft.Extensions.SecretManager.Tools.Internal public class SecretsStore { private readonly string _secretsFilePath; - private IDictionary _secrets; + private readonly IDictionary _secrets; public SecretsStore(string userSecretsId, IReporter reporter) {