From 659521e43a4f917919c297b4eb6d9aff1bf4ce12 Mon Sep 17 00:00:00 2001 From: Brennan Conroy Date: Thu, 29 Sep 2022 11:01:26 -0700 Subject: [PATCH 1/2] Add IDE 20, 38, and 200 --- .editorconfig | 17 ++++++++++++++++- .../Authorization/src/AuthorizeRouteView.cs | 2 +- .../Server/src/Circuits/CircuitHost.cs | 2 +- .../Server/src/Circuits/RemoteRenderer.cs | 2 +- .../Web/src/JSComponents/JSComponentInterop.cs | 2 +- .../src/Hosting/WebAssemblyHostConfiguration.cs | 2 +- .../src/HotReload/WebAssemblyHotReload.cs | 3 +++ .../Manifest.MSBuildTask/src/Manifest.cs | 6 +++--- .../RemoteWindowsDeployer.cs | 2 +- .../src/Internal/ParsingHelpers.cs | 4 ++-- .../Routing/src/EndpointNameAddressScheme.cs | 2 +- .../Routing/src/Matching/DfaMatcherFactory.cs | 5 +---- .../Routing/src/Matching/HostMatcherPolicy.cs | 4 ++-- .../Routing/src/Matching/ILEmitTrieJumpTable.cs | 5 +---- .../UI/src/IdentityDefaultUIConfigureOptions.cs | 2 +- .../src/Routing/ActionEndpointDataSourceBase.cs | 2 +- .../DynamicControllerEndpointSelectorCache.cs | 2 +- .../src/DataAnnotationsMetadataProvider.cs | 6 +++--- .../RazorRuntimeCompilationHostingStartup.cs | 2 +- src/Mvc/Mvc.Razor/src/RazorPageActivator.cs | 2 +- .../DefaultPageFactoryProvider.cs | 2 +- .../DynamicPageEndpointSelectorCache.cs | 2 +- .../Mvc.ViewFeatures/src/RemoteAttributeBase.cs | 2 +- .../CommonResourceInvokerTest.cs | 6 +++--- .../src/ConnectionBuilderExtensions.cs | 2 +- .../IIS/IISIntegration/src/IISMiddleware.cs | 2 +- .../src/IISDeploymentParameters.cs | 3 +-- .../TransportConnectionManager.cs | 2 +- .../CertificateGeneration/CertificateManager.cs | 2 +- .../src/Internal/HttpConnectionManager.cs | 4 ++-- .../Core/src/Internal/HubReflectionHelper.cs | 2 +- .../Core/src/Internal/TypedClientBuilder.cs | 2 +- .../src/Commands/GetDocumentCommand.cs | 2 +- .../src/Internal/OpenapiDependencyAttribute.cs | 2 +- src/Tools/dotnet-dev-certs/src/Program.cs | 2 +- .../src/EncoderServiceCollectionExtensions.cs | 6 +++--- 36 files changed, 64 insertions(+), 53 deletions(-) diff --git a/.editorconfig b/.editorconfig index c532bc0d1f63..91fcda8b9777 100644 --- a/.editorconfig +++ b/.editorconfig @@ -229,6 +229,9 @@ dotnet_diagnostic.IDE0005.severity = warning # IDE0011: Curly braces to surround blocks of code dotnet_diagnostic.IDE0011.severity = warning +# IDE0020: Use pattern matching to avoid is check followed by a cast (with variable) +dotnet_diagnostic.IDE0020.severity = warning + # IDE0035: Remove unreachable code dotnet_diagnostic.IDE0035.severity = warning @@ -236,6 +239,9 @@ dotnet_diagnostic.IDE0035.severity = warning 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 +# IDE0038: Use pattern matching to avoid is check followed by a cast (without variable) +dotnet_diagnostic.IDE0038.severity = warning + # IDE0043: Format string contains invalid placeholder dotnet_diagnostic.IDE0043.severity = warning @@ -265,11 +271,14 @@ file_header_template = Licensed to the .NET Foundation under one or more agreeme # IDE0161: Convert to file-scoped namespace dotnet_diagnostic.IDE0161.severity = warning +# IDE0200: Lambda expression can be removed +dotnet_diagnostic.IDE0200.severity = warning + # IDE2000: Disallow multiple blank lines dotnet_style_allow_multiple_blank_lines_experimental = false dotnet_diagnostic.IDE2000.severity = warning -[{eng/tools/**.cs,**/{test,testassets,samples,Samples,perf,scripts}/**.cs}] +[{eng/tools/**.cs,**/{test,testassets,samples,Samples,perf,scripts,stress}/**.cs}] # CA1018: Mark attributes with AttributeUsageAttribute dotnet_diagnostic.CA1018.severity = suggestion # CA1507: Use nameof to express symbol names @@ -320,6 +329,10 @@ dotnet_diagnostic.CA2012.severity = suggestion dotnet_diagnostic.CA2249.severity = suggestion # IDE0005: Remove unnecessary usings dotnet_diagnostic.IDE0005.severity = suggestion +# IDE0020: Use pattern matching to avoid is check followed by a cast (with variable) +dotnet_diagnostic.IDE0020.severity = suggestion +# IDE0038: Use pattern matching to avoid is check followed by a cast (without variable) +dotnet_diagnostic.IDE0038.severity = suggestion # IDE0044: Make field readonly dotnet_diagnostic.IDE0044.severity = suggestion # IDE0051: Remove unused private members @@ -330,6 +343,8 @@ dotnet_diagnostic.IDE0059.severity = suggestion dotnet_diagnostic.IDE0060.severity = suggestion # IDE0062: Make local function static dotnet_diagnostic.IDE0062.severity = suggestion +# IDE0200: Lambda expression can be removed +dotnet_diagnostic.IDE0200.severity = suggestion # CA2016: Forward the 'CancellationToken' parameter to methods that take one dotnet_diagnostic.CA2016.severity = suggestion diff --git a/src/Components/Authorization/src/AuthorizeRouteView.cs b/src/Components/Authorization/src/AuthorizeRouteView.cs index 137b999e4dd3..0fc33a242c01 100644 --- a/src/Components/Authorization/src/AuthorizeRouteView.cs +++ b/src/Components/Authorization/src/AuthorizeRouteView.cs @@ -38,7 +38,7 @@ public AuthorizeRouteView() // Cache the rendering delegates so that we only construct new closure instances // when they are actually used (e.g., we never prepare a RenderFragment bound to // the NotAuthorized content except when you are displaying that particular state) - RenderFragment renderBaseRouteViewDelegate = builder => base.Render(builder); + RenderFragment renderBaseRouteViewDelegate = base.Render; _renderAuthorizedDelegate = authenticateState => renderBaseRouteViewDelegate; _renderNotAuthorizedDelegate = authenticationState => builder => RenderNotAuthorizedInDefaultLayout(builder, authenticationState); _renderAuthorizingDelegate = RenderAuthorizingInDefaultLayout; diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index 7611caf87498..6156b407a282 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -586,7 +586,7 @@ public void SendPendingBatches() // Dispatch any buffered renders we accumulated during a disconnect. // Note that while the rendering is async, we cannot await it here. The Task returned by ProcessBufferedRenderBatches relies on // OnRenderCompletedAsync to be invoked to complete, and SignalR does not allow concurrent hub method invocations. - _ = Renderer.Dispatcher.InvokeAsync(() => Renderer.ProcessBufferedRenderBatches()); + _ = Renderer.Dispatcher.InvokeAsync(Renderer.ProcessBufferedRenderBatches); } private void AssertInitialized() diff --git a/src/Components/Server/src/Circuits/RemoteRenderer.cs b/src/Components/Server/src/Circuits/RemoteRenderer.cs index dc8c705ede20..3799ebff3def 100644 --- a/src/Components/Server/src/Circuits/RemoteRenderer.cs +++ b/src/Components/Server/src/Circuits/RemoteRenderer.cs @@ -175,7 +175,7 @@ public Task ProcessBufferedRenderBatches() // All the batches are sent in order based on the fact that SignalR // provides ordering for the underlying messages and that the batches // are always in order. - return Task.WhenAll(_unacknowledgedRenderBatches.Select(b => WriteBatchBytesAsync(b))); + return Task.WhenAll(_unacknowledgedRenderBatches.Select(WriteBatchBytesAsync)); } private async Task WriteBatchBytesAsync(UnacknowledgedRenderBatch pending) diff --git a/src/Components/Web/src/JSComponents/JSComponentInterop.cs b/src/Components/Web/src/JSComponents/JSComponentInterop.cs index 43132bd1e7b3..5596a8c4bc7a 100644 --- a/src/Components/Web/src/JSComponents/JSComponentInterop.cs +++ b/src/Components/Web/src/JSComponents/JSComponentInterop.cs @@ -29,7 +29,7 @@ static JSComponentInterop() { if (HotReloadManager.Default.MetadataUpdateSupported) { - HotReloadManager.Default.OnDeltaApplied += () => ParameterTypeCaches.Clear(); + HotReloadManager.Default.OnDeltaApplied += ParameterTypeCaches.Clear; } } diff --git a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostConfiguration.cs b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostConfiguration.cs index 64d2d57d9576..3144587d8d85 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostConfiguration.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostConfiguration.cs @@ -158,7 +158,7 @@ public IConfigurationBuilder Add(IConfigurationSource source) // provider has reloaded data. This will invoke the RaiseChanged // method which maps changes in individual providers to the change // token on the WebAssemblyHostConfiguration object. - _changeTokenRegistrations.Add(ChangeToken.OnChange(() => provider.GetReloadToken(), () => RaiseChanged())); + _changeTokenRegistrations.Add(ChangeToken.OnChange(provider.GetReloadToken, RaiseChanged)); // We keep a list of providers in this class so that we can map // set and get methods on this class to the set and get methods diff --git a/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs b/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs index 3ea5c30f6929..af79ebff2daf 100644 --- a/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs +++ b/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs @@ -26,7 +26,10 @@ public static class WebAssemblyHotReload internal static async Task InitializeAsync() { + // Analyzer has a bug where it doesn't handle ConditionalAttribute: https://github.com/dotnet/roslyn/issues/63464 +#pragma warning disable IDE0200 // Remove unnecessary lambda expression _hotReloadAgent = new HotReloadAgent(m => Debug.WriteLine(m)); +#pragma warning restore IDE0200 // Remove unnecessary lambda expression if (Environment.GetEnvironmentVariable("__ASPNETCORE_BROWSER_TOOLS") == "true") { diff --git a/src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs b/src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs index 1a71e041b28b..c6abccae2a4b 100644 --- a/src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs +++ b/src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; @@ -46,7 +46,7 @@ public XDocument ToXmlDocument() var root = new XElement(ElementNames.Root, new XElement(ElementNames.ManifestVersion, "1.0"), new XElement(ElementNames.FileSystem, - Root.Children.Select(e => BuildNode(e)))); + Root.Children.Select(BuildNode))); document.Add(root); @@ -64,7 +64,7 @@ private XElement BuildNode(Entry entry) else { var directory = new XElement(ElementNames.Directory, new XAttribute(ElementNames.Name, entry.Name)); - directory.Add(entry.Children.Select(c => BuildNode(c))); + directory.Add(entry.Children.Select(BuildNode)); return directory; } } diff --git a/src/Hosting/Server.IntegrationTesting/src/Deployers/RemoteWindowsDeployer/RemoteWindowsDeployer.cs b/src/Hosting/Server.IntegrationTesting/src/Deployers/RemoteWindowsDeployer/RemoteWindowsDeployer.cs index c82011801ff4..3140eb4c1f6b 100644 --- a/src/Hosting/Server.IntegrationTesting/src/Deployers/RemoteWindowsDeployer/RemoteWindowsDeployer.cs +++ b/src/Hosting/Server.IntegrationTesting/src/Deployers/RemoteWindowsDeployer/RemoteWindowsDeployer.cs @@ -19,7 +19,7 @@ public class RemoteWindowsDeployer : ApplicationDeployer private string _deployedFolderPathInFileShare; private readonly RemoteWindowsDeploymentParameters _deploymentParameters; private bool _isDisposed; - private static readonly Lazy _scripts = new Lazy(() => CopyEmbeddedScriptFilesToDisk()); + private static readonly Lazy _scripts = new Lazy(CopyEmbeddedScriptFilesToDisk); public RemoteWindowsDeployer(RemoteWindowsDeploymentParameters deploymentParameters, ILoggerFactory loggerFactory) : base(deploymentParameters, loggerFactory) diff --git a/src/Http/Http.Abstractions/src/Internal/ParsingHelpers.cs b/src/Http/Http.Abstractions/src/Internal/ParsingHelpers.cs index 9fc8467362f5..e8e7b59f3f6b 100644 --- a/src/Http/Http.Abstractions/src/Internal/ParsingHelpers.cs +++ b/src/Http/Http.Abstractions/src/Internal/ParsingHelpers.cs @@ -63,7 +63,7 @@ public static void SetHeaderJoined(IHeaderDictionary headers, string key, String } else { - headers[key] = string.Join(",", value.Select((s) => QuoteIfNeeded(s))); + headers[key] = string.Join(",", value.Select(QuoteIfNeeded)); } } @@ -135,7 +135,7 @@ public static void AppendHeaderJoined(IHeaderDictionary headers, string key, par } else { - headers[key] = existing + "," + string.Join(",", values.Select(value => QuoteIfNeeded(value))); + headers[key] = existing + "," + string.Join(",", values.Select(QuoteIfNeeded)); } } diff --git a/src/Http/Routing/src/EndpointNameAddressScheme.cs b/src/Http/Routing/src/EndpointNameAddressScheme.cs index 6cfa2fa40f8e..1bf2b769ec80 100644 --- a/src/Http/Routing/src/EndpointNameAddressScheme.cs +++ b/src/Http/Routing/src/EndpointNameAddressScheme.cs @@ -70,7 +70,7 @@ public IEnumerable FindEndpoints(string address) // OK we need to report some duplicates. var duplicates = endpoints - .GroupBy(e => GetEndpointName(e)) + .GroupBy(GetEndpointName) .Where(g => g.Key != null && g.Count() > 1); var builder = new StringBuilder(); diff --git a/src/Http/Routing/src/Matching/DfaMatcherFactory.cs b/src/Http/Routing/src/Matching/DfaMatcherFactory.cs index 026ee659798c..a544cdd5787a 100644 --- a/src/Http/Routing/src/Matching/DfaMatcherFactory.cs +++ b/src/Http/Routing/src/Matching/DfaMatcherFactory.cs @@ -32,9 +32,6 @@ public override Matcher CreateMatcher(EndpointDataSource dataSource) // when the services are disposed. var lifetime = _services.GetRequiredService(); - return new DataSourceDependentMatcher(dataSource, lifetime, () => - { - return _services.GetRequiredService(); - }); + return new DataSourceDependentMatcher(dataSource, lifetime, _services.GetRequiredService); } } diff --git a/src/Http/Routing/src/Matching/HostMatcherPolicy.cs b/src/Http/Routing/src/Matching/HostMatcherPolicy.cs index 0680b343d0d6..77da6e222652 100644 --- a/src/Http/Routing/src/Matching/HostMatcherPolicy.cs +++ b/src/Http/Routing/src/Matching/HostMatcherPolicy.cs @@ -210,7 +210,7 @@ public IReadOnlyList GetEdges(IReadOnlyList endpoints) for (var i = 0; i < endpoints.Count; i++) { var endpoint = endpoints[i]; - var hosts = endpoint.Metadata.GetMetadata()?.Hosts.Select(h => CreateEdgeKey(h)).ToArray(); + var hosts = endpoint.Metadata.GetMetadata()?.Hosts.Select(CreateEdgeKey).ToArray(); if (hosts == null || hosts.Length == 0) { hosts = new[] { EdgeKey.WildcardEdgeKey }; @@ -232,7 +232,7 @@ public IReadOnlyList GetEdges(IReadOnlyList endpoints) { var endpoint = endpoints[i]; - var endpointKeys = endpoint.Metadata.GetMetadata()?.Hosts.Select(h => CreateEdgeKey(h)).ToArray() ?? Array.Empty(); + var endpointKeys = endpoint.Metadata.GetMetadata()?.Hosts.Select(CreateEdgeKey).ToArray() ?? Array.Empty(); if (endpointKeys.Length == 0) { // OK this means that this endpoint matches *all* hosts. diff --git a/src/Http/Routing/src/Matching/ILEmitTrieJumpTable.cs b/src/Http/Routing/src/Matching/ILEmitTrieJumpTable.cs index 6a541a99b390..f382c2d562b7 100644 --- a/src/Http/Routing/src/Matching/ILEmitTrieJumpTable.cs +++ b/src/Http/Routing/src/Matching/ILEmitTrieJumpTable.cs @@ -68,10 +68,7 @@ private int FallbackGetDestination(string path, PathSegment segment) internal async Task InitializeILDelegateAsync() { // Offload the creation of the IL delegate to the thread pool. - await Task.Run(() => - { - InitializeILDelegate(); - }); + await Task.Run(InitializeILDelegate); } // Internal for testing diff --git a/src/Identity/UI/src/IdentityDefaultUIConfigureOptions.cs b/src/Identity/UI/src/IdentityDefaultUIConfigureOptions.cs index b917222a04d9..d7f2f45dc8a4 100644 --- a/src/Identity/UI/src/IdentityDefaultUIConfigureOptions.cs +++ b/src/Identity/UI/src/IdentityDefaultUIConfigureOptions.cs @@ -34,7 +34,7 @@ public void PostConfigure(string? name, RazorPagesOptions options) options.Conventions.AddAreaFolderApplicationModelConvention( IdentityUIDefaultAreaName, "/", - pam => convention.Apply(pam)); + convention.Apply); options.Conventions.AddAreaFolderApplicationModelConvention( IdentityUIDefaultAreaName, "/Account/Manage", diff --git a/src/Mvc/Mvc.Core/src/Routing/ActionEndpointDataSourceBase.cs b/src/Mvc/Mvc.Core/src/Routing/ActionEndpointDataSourceBase.cs index d141b85ad8f0..9b921b1a49a6 100644 --- a/src/Mvc/Mvc.Core/src/Routing/ActionEndpointDataSourceBase.cs +++ b/src/Mvc/Mvc.Core/src/Routing/ActionEndpointDataSourceBase.cs @@ -79,7 +79,7 @@ protected void Subscribe() if (_actions is ActionDescriptorCollectionProvider collectionProviderWithChangeToken) { _disposable = ChangeToken.OnChange( - () => collectionProviderWithChangeToken.GetChangeToken(), + collectionProviderWithChangeToken.GetChangeToken, UpdateEndpoints); } } diff --git a/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointSelectorCache.cs b/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointSelectorCache.cs index aee4b811cbf3..49c32d8a3855 100644 --- a/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointSelectorCache.cs +++ b/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointSelectorCache.cs @@ -26,7 +26,7 @@ public void AddDataSource(ControllerActionEndpointDataSource dataSource) public DynamicControllerEndpointSelector GetEndpointSelector(Endpoint endpoint) { var dataSourceId = endpoint.Metadata.GetMetadata()!; - return _endpointSelectorCache.GetOrAdd(dataSourceId.Id, key => EnsureDataSource(key)); + return _endpointSelectorCache.GetOrAdd(dataSourceId.Id, EnsureDataSource); } private DynamicControllerEndpointSelector EnsureDataSource(int key) diff --git a/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsMetadataProvider.cs b/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsMetadataProvider.cs index 2cd4722677e5..60a197a7ac95 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsMetadataProvider.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsMetadataProvider.cs @@ -124,7 +124,7 @@ public void CreateDisplayMetadata(DisplayMetadataProviderContext context) } else { - displayMetadata.Description = () => displayAttribute.GetDescription(); + displayMetadata.Description = displayAttribute.GetDescription; } } @@ -146,7 +146,7 @@ public void CreateDisplayMetadata(DisplayMetadataProviderContext context) } else { - displayMetadata.DisplayName = () => displayAttribute.GetName(); + displayMetadata.DisplayName = displayAttribute.GetName; } } else if (displayNameAttribute != null) @@ -274,7 +274,7 @@ public void CreateDisplayMetadata(DisplayMetadataProviderContext context) } else { - displayMetadata.Placeholder = () => displayAttribute.GetPrompt(); + displayMetadata.Placeholder = displayAttribute.GetPrompt; } } diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RazorRuntimeCompilationHostingStartup.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RazorRuntimeCompilationHostingStartup.cs index c5ce34d31470..51f5959709cc 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RazorRuntimeCompilationHostingStartup.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RazorRuntimeCompilationHostingStartup.cs @@ -11,6 +11,6 @@ internal sealed class RazorRuntimeCompilationHostingStartup : IHostingStartup public void Configure(IWebHostBuilder builder) { // Add Razor services - builder.ConfigureServices(services => RazorRuntimeCompilationMvcCoreBuilderExtensions.AddServices(services)); + builder.ConfigureServices(RazorRuntimeCompilationMvcCoreBuilderExtensions.AddServices); } } diff --git a/src/Mvc/Mvc.Razor/src/RazorPageActivator.cs b/src/Mvc/Mvc.Razor/src/RazorPageActivator.cs index bc2eaeb9e8b0..9e28ac1aa412 100644 --- a/src/Mvc/Mvc.Razor/src/RazorPageActivator.cs +++ b/src/Mvc/Mvc.Razor/src/RazorPageActivator.cs @@ -39,7 +39,7 @@ public class RazorPageActivator : IRazorPageActivator _propertyAccessors = new RazorPagePropertyActivator.PropertyValueAccessors { - UrlHelperAccessor = context => urlHelperFactory.GetUrlHelper(context), + UrlHelperAccessor = urlHelperFactory.GetUrlHelper, JsonHelperAccessor = context => jsonHelper, DiagnosticSourceAccessor = context => diagnosticSource, HtmlEncoderAccessor = context => htmlEncoder, diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageFactoryProvider.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageFactoryProvider.cs index 6ed1fbec4b5d..2a6a2dc3231c 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageFactoryProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageFactoryProvider.cs @@ -31,7 +31,7 @@ internal sealed class DefaultPageFactoryProvider : IPageFactoryProvider _modelMetadataProvider = metadataProvider; _propertyAccessors = new RazorPagePropertyActivator.PropertyValueAccessors { - UrlHelperAccessor = context => urlHelperFactory.GetUrlHelper(context), + UrlHelperAccessor = urlHelperFactory.GetUrlHelper, JsonHelperAccessor = context => jsonHelper, DiagnosticSourceAccessor = context => diagnosticListener, HtmlEncoderAccessor = context => htmlEncoder, diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointSelectorCache.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointSelectorCache.cs index 0bc8079449dc..527a8e7d7b3c 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointSelectorCache.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointSelectorCache.cs @@ -33,7 +33,7 @@ public void AddDataSource(PageActionEndpointDataSource dataSource) var dataSourceId = endpoint.Metadata.GetMetadata(); Debug.Assert(dataSourceId is not null); - return _endpointSelectorCache.GetOrAdd(dataSourceId.Id, key => EnsureDataSource(key)); + return _endpointSelectorCache.GetOrAdd(dataSourceId.Id, EnsureDataSource); } private DynamicPageEndpointSelector EnsureDataSource(int key) diff --git a/src/Mvc/Mvc.ViewFeatures/src/RemoteAttributeBase.cs b/src/Mvc/Mvc.ViewFeatures/src/RemoteAttributeBase.cs index 84519e2514c0..04af5a9120ce 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/RemoteAttributeBase.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/RemoteAttributeBase.cs @@ -62,7 +62,7 @@ public string AdditionalFields { _additionalFields = value ?? string.Empty; _additionalFieldsSplit = SplitAndTrimPropertyNames(value) - .Select(field => FormatPropertyForClientValidation(field)) + .Select(FormatPropertyForClientValidation) .ToArray(); } } diff --git a/src/Mvc/shared/Mvc.Core.TestCommon/CommonResourceInvokerTest.cs b/src/Mvc/shared/Mvc.Core.TestCommon/CommonResourceInvokerTest.cs index 653dab157cda..ddfae5b3fb5c 100644 --- a/src/Mvc/shared/Mvc.Core.TestCommon/CommonResourceInvokerTest.cs +++ b/src/Mvc/shared/Mvc.Core.TestCommon/CommonResourceInvokerTest.cs @@ -482,7 +482,7 @@ public async Task InvokeAction_InvokesExceptionFilter_UnhandledExceptionIsThrown var invoker = CreateInvoker(filter.Object, exception: Exception); // Act - await Assert.ThrowsAsync(Exception.GetType(), async () => await invoker.InvokeAsync()); + await Assert.ThrowsAsync(Exception.GetType(), invoker.InvokeAsync); // Assert filter.Verify(f => f.OnException(It.IsAny()), Times.Once()); @@ -945,7 +945,7 @@ public async Task InvokeAction_InvokesAsyncResultFilter_ShortCircuit_WithoutCanc // Act & Assert await ExceptionAssert.ThrowsAsync( - async () => await invoker.InvokeAsync(), + invoker.InvokeAsync, message); } @@ -972,7 +972,7 @@ public async Task InvokeAction_InvokesResultFilter_ExceptionGoesUnhandled() var invoker = CreateInvoker(filter.Object); // Act - await Assert.ThrowsAsync(exception.GetType(), async () => await invoker.InvokeAsync()); + await Assert.ThrowsAsync(exception.GetType(), invoker.InvokeAsync); // Assert result.Verify(r => r.ExecuteResultAsync(It.IsAny()), Times.Once()); diff --git a/src/Servers/Connections.Abstractions/src/ConnectionBuilderExtensions.cs b/src/Servers/Connections.Abstractions/src/ConnectionBuilderExtensions.cs index 717c20059297..65dd0f91d706 100644 --- a/src/Servers/Connections.Abstractions/src/ConnectionBuilderExtensions.cs +++ b/src/Servers/Connections.Abstractions/src/ConnectionBuilderExtensions.cs @@ -24,7 +24,7 @@ public static class ConnectionBuilderExtensions var handler = ActivatorUtilities.GetServiceOrCreateInstance(connectionBuilder.ApplicationServices); // This is a terminal middleware, so there's no need to use the 'next' parameter - return connectionBuilder.Run(connection => handler.OnConnectedAsync(connection)); + return connectionBuilder.Run(handler.OnConnectedAsync); } /// diff --git a/src/Servers/IIS/IISIntegration/src/IISMiddleware.cs b/src/Servers/IIS/IISIntegration/src/IISMiddleware.cs index 65a5b601b3f6..699ce3e4d3a9 100644 --- a/src/Servers/IIS/IISIntegration/src/IISMiddleware.cs +++ b/src/Servers/IIS/IISIntegration/src/IISMiddleware.cs @@ -116,7 +116,7 @@ public Task Invoke(HttpContext httpContext) string.Equals(ANCMShutdownEventHeaderValue, httpContext.Request.Headers[MSAspNetCoreEvent], StringComparison.OrdinalIgnoreCase)) { // Execute shutdown task on background thread without waiting for completion - var shutdownTask = Task.Run(() => _applicationLifetime.StopApplication()); + var shutdownTask = Task.Run(_applicationLifetime.StopApplication); httpContext.Response.StatusCode = StatusCodes.Status202Accepted; return Task.CompletedTask; } diff --git a/src/Servers/IIS/IntegrationTesting.IIS/src/IISDeploymentParameters.cs b/src/Servers/IIS/IntegrationTesting.IIS/src/IISDeploymentParameters.cs index f323b2e63c18..da816ebd8992 100644 --- a/src/Servers/IIS/IntegrationTesting.IIS/src/IISDeploymentParameters.cs +++ b/src/Servers/IIS/IntegrationTesting.IIS/src/IISDeploymentParameters.cs @@ -28,9 +28,8 @@ public IISDeploymentParameters(TestVariant variant) public IISDeploymentParameters(DeploymentParameters parameters) : base(parameters) { - if (parameters is IISDeploymentParameters) + if (parameters is IISDeploymentParameters tempParameters) { - var tempParameters = (IISDeploymentParameters)parameters; WebConfigActionList = tempParameters.WebConfigActionList; ServerConfigActionList = tempParameters.ServerConfigActionList; WebConfigBasedEnvironmentVariables = tempParameters.WebConfigBasedEnvironmentVariables; diff --git a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/TransportConnectionManager.cs b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/TransportConnectionManager.cs index 63d7a48da8d1..3ff915a8909e 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/TransportConnectionManager.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/TransportConnectionManager.cs @@ -94,7 +94,7 @@ private static Task CancellationTokenAsTask(CancellationToken token) } var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - token.Register(() => tcs.SetResult()); + token.Register(tcs.SetResult); return tcs.Task; } } diff --git a/src/Shared/CertificateGeneration/CertificateManager.cs b/src/Shared/CertificateGeneration/CertificateManager.cs index 0bd57f57de22..aad1462eb1c1 100644 --- a/src/Shared/CertificateGeneration/CertificateManager.cs +++ b/src/Shared/CertificateGeneration/CertificateManager.cs @@ -95,7 +95,7 @@ internal CertificateManager(string subject, int version) var now = DateTimeOffset.Now; var validCertificates = matchingCertificates .Where(c => IsValidCertificate(c, now, requireExportable)) - .OrderByDescending(c => GetCertificateVersion(c)) + .OrderByDescending(GetCertificateVersion) .ToArray(); if (Log.IsEnabled()) diff --git a/src/SignalR/common/Http.Connections/src/Internal/HttpConnectionManager.cs b/src/SignalR/common/Http.Connections/src/Internal/HttpConnectionManager.cs index e52e2bc5ef72..39b56cf4e5eb 100644 --- a/src/SignalR/common/Http.Connections/src/Internal/HttpConnectionManager.cs +++ b/src/SignalR/common/Http.Connections/src/Internal/HttpConnectionManager.cs @@ -34,8 +34,8 @@ public HttpConnectionManager(ILoggerFactory loggerFactory, IHostApplicationLifet _disconnectTimeoutTicks = (long)(connectionOptions.Value.DisconnectTimeout ?? ConnectionOptionsSetup.DefaultDisconectTimeout).TotalMilliseconds; // Register these last as the callbacks could run immediately - appLifetime.ApplicationStarted.Register(() => Start()); - appLifetime.ApplicationStopping.Register(() => CloseConnections()); + appLifetime.ApplicationStarted.Register(Start); + appLifetime.ApplicationStopping.Register(CloseConnections); } public void Start() diff --git a/src/SignalR/server/Core/src/Internal/HubReflectionHelper.cs b/src/SignalR/server/Core/src/Internal/HubReflectionHelper.cs index 329078a24c6d..d54fb6cfe779 100644 --- a/src/SignalR/server/Core/src/Internal/HubReflectionHelper.cs +++ b/src/SignalR/server/Core/src/Internal/HubReflectionHelper.cs @@ -15,7 +15,7 @@ public static IEnumerable GetHubMethods(Type hubType) var methods = hubType.GetMethods(BindingFlags.Public | BindingFlags.Instance); var allInterfaceMethods = _excludeInterfaces.SelectMany(i => GetInterfaceMethods(hubType, i)); - return methods.Except(allInterfaceMethods).Where(m => IsHubMethod(m)); + return methods.Except(allInterfaceMethods).Where(IsHubMethod); } private static IEnumerable GetInterfaceMethods(Type type, Type iface) diff --git a/src/SignalR/server/Core/src/Internal/TypedClientBuilder.cs b/src/SignalR/server/Core/src/Internal/TypedClientBuilder.cs index 69be30e9c761..985dc14e96bf 100644 --- a/src/SignalR/server/Core/src/Internal/TypedClientBuilder.cs +++ b/src/SignalR/server/Core/src/Internal/TypedClientBuilder.cs @@ -12,7 +12,7 @@ internal static class TypedClientBuilder private const string ClientModuleName = "Microsoft.AspNetCore.SignalR.TypedClientBuilder"; // There is one static instance of _builder per T - private static readonly Lazy> _builder = new Lazy>(() => GenerateClientBuilder()); + private static readonly Lazy> _builder = new Lazy>(GenerateClientBuilder); private static readonly PropertyInfo CancellationTokenNoneProperty = typeof(CancellationToken).GetProperty("None", BindingFlags.Public | BindingFlags.Static)!; diff --git a/src/Tools/GetDocumentInsider/src/Commands/GetDocumentCommand.cs b/src/Tools/GetDocumentInsider/src/Commands/GetDocumentCommand.cs index 26ef4958c37f..81159c11d8ba 100644 --- a/src/Tools/GetDocumentInsider/src/Commands/GetDocumentCommand.cs +++ b/src/Tools/GetDocumentInsider/src/Commands/GetDocumentCommand.cs @@ -53,7 +53,7 @@ protected override int Execute() var packagedAssemblies = Directory .EnumerateFiles(toolsDirectory, "*.dll") .Except(new[] { Path.GetFullPath(thisAssembly.Location) }) - .ToDictionary(path => Path.GetFileNameWithoutExtension(path), path => new AssemblyInfo(path)); + .ToDictionary(Path.GetFileNameWithoutExtension, path => new AssemblyInfo(path)); // Explicitly load all assemblies we need first to preserve target project as much as possible. This // executable is always run in the target project's context (either through location or .deps.json file). diff --git a/src/Tools/Microsoft.dotnet-openapi/src/Internal/OpenapiDependencyAttribute.cs b/src/Tools/Microsoft.dotnet-openapi/src/Internal/OpenapiDependencyAttribute.cs index 74813f41976b..4b26d31d4db1 100644 --- a/src/Tools/Microsoft.dotnet-openapi/src/Internal/OpenapiDependencyAttribute.cs +++ b/src/Tools/Microsoft.dotnet-openapi/src/Internal/OpenapiDependencyAttribute.cs @@ -15,7 +15,7 @@ public OpenApiDependencyAttribute(string name, string version, string codeGenera { Name = name; Version = version; - CodeGenerators = codeGenerators.Split(';', StringSplitOptions.RemoveEmptyEntries).Select(c => Enum.Parse(c)).ToArray(); + CodeGenerators = codeGenerators.Split(';', StringSplitOptions.RemoveEmptyEntries).Select(Enum.Parse).ToArray(); } public string Name { get; set; } diff --git a/src/Tools/dotnet-dev-certs/src/Program.cs b/src/Tools/dotnet-dev-certs/src/Program.cs index 642bdc3e5559..82e49d4d355a 100644 --- a/src/Tools/dotnet-dev-certs/src/Program.cs +++ b/src/Tools/dotnet-dev-certs/src/Program.cs @@ -297,7 +297,7 @@ private static int CheckHttpsCertificate(CommandOption trust, IReporter reporter { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - var trustedCertificates = certificates.Where(c => certificateManager.IsTrusted(c)).ToList(); + var trustedCertificates = certificates.Where(certificateManager.IsTrusted).ToList(); if (!trustedCertificates.Any()) { reporter.Output($@"The following certificates were found, but none of them is trusted: {CertificateManager.ToCertificateDescription(certificates)}"); diff --git a/src/WebEncoders/src/EncoderServiceCollectionExtensions.cs b/src/WebEncoders/src/EncoderServiceCollectionExtensions.cs index e45d55082c06..186a7b548e3d 100644 --- a/src/WebEncoders/src/EncoderServiceCollectionExtensions.cs +++ b/src/WebEncoders/src/EncoderServiceCollectionExtensions.cs @@ -32,11 +32,11 @@ public static IServiceCollection AddWebEncoders(this IServiceCollection services // Register the default encoders // We want to call the 'Default' property getters lazily since they perform static caching services.TryAddSingleton( - CreateFactory(() => HtmlEncoder.Default, settings => HtmlEncoder.Create(settings))); + CreateFactory(() => HtmlEncoder.Default, HtmlEncoder.Create)); services.TryAddSingleton( - CreateFactory(() => JavaScriptEncoder.Default, settings => JavaScriptEncoder.Create(settings))); + CreateFactory(() => JavaScriptEncoder.Default, JavaScriptEncoder.Create)); services.TryAddSingleton( - CreateFactory(() => UrlEncoder.Default, settings => UrlEncoder.Create(settings))); + CreateFactory(() => UrlEncoder.Default, UrlEncoder.Create)); return services; } From 4fe72b19c1b40f9a2afef889f317f351632dcaab Mon Sep 17 00:00:00 2001 From: Brennan Conroy Date: Thu, 29 Sep 2022 15:01:12 -0700 Subject: [PATCH 2/2] IDE 29, 30, 31 null! --- .editorconfig | 15 +++++++++++++++ .../src/DotNetObjectReferenceOfT.cs | 5 +---- .../src/Infrastructure/ControllerActionInvoker.cs | 5 +---- .../src/Infrastructure/ResourceInvoker.cs | 15 +++------------ .../src/Infrastructure/PageActionInvoker.cs | 5 +---- .../src/Infrastructure/PageResultExecutor.cs | 5 +---- .../Mvc.ViewFeatures/src/AttributeDictionary.cs | 5 +---- src/Mvc/Mvc.ViewFeatures/src/ExpressionHelper.cs | 5 +---- .../Mvc.ViewFeatures/src/Rendering/TagBuilder.cs | 5 +---- .../src/ViewComponentResultExecutor.cs | 5 +---- src/Mvc/Mvc.ViewFeatures/src/ViewExecutor.cs | 5 +---- .../src/CertificateAuthenticationHandler.cs | 5 +---- src/Servers/HttpSys/src/HttpSysOptions.cs | 10 ++-------- .../HttpSys/src/RequestProcessing/Request.cs | 5 +---- .../RequestProcessing/RequestStreamAsyncResult.cs | 5 +---- .../ResponseStreamAsyncResult.cs | 10 ++-------- src/Servers/HttpSys/src/UrlPrefixCollection.cs | 10 ++-------- .../Core/src/Internal/Http/Http1OutputProducer.cs | 5 +---- .../Dictionary/AdaptiveCapacityDictionary.cs | 5 +---- src/Shared/Process/ProcessEx.cs | 5 +---- src/Shared/PropertyAsParameterInfo.cs | 8 ++++---- .../server/Core/src/HubConnectionContext.cs | 5 +---- .../Core/src/Internal/DefaultHubDispatcherLog.cs | 4 ++-- .../EnvironmentVariableSkipConditionAttribute.cs | 2 +- 24 files changed, 47 insertions(+), 107 deletions(-) diff --git a/.editorconfig b/.editorconfig index 91fcda8b9777..71d44b9daffa 100644 --- a/.editorconfig +++ b/.editorconfig @@ -232,6 +232,15 @@ dotnet_diagnostic.IDE0011.severity = warning # IDE0020: Use pattern matching to avoid is check followed by a cast (with variable) dotnet_diagnostic.IDE0020.severity = warning +# IDE0029: Use coalesce expression (non-nullable types) +dotnet_diagnostic.IDE0029.severity = warning + +# IDE0030: Use coalesce expression (nullable types) +dotnet_diagnostic.IDE0030.severity = warning + +# IDE0031: Use null propagation +dotnet_diagnostic.IDE0031.severity = warning + # IDE0035: Remove unreachable code dotnet_diagnostic.IDE0035.severity = warning @@ -331,6 +340,12 @@ dotnet_diagnostic.CA2249.severity = suggestion dotnet_diagnostic.IDE0005.severity = suggestion # IDE0020: Use pattern matching to avoid is check followed by a cast (with variable) dotnet_diagnostic.IDE0020.severity = suggestion +# IDE0029: Use coalesce expression (non-nullable types) +dotnet_diagnostic.IDE0029.severity = suggestion +# IDE0030: Use coalesce expression (nullable types) +dotnet_diagnostic.IDE0030.severity = suggestion +# IDE0031: Use null propagation +dotnet_diagnostic.IDE0031.severity = suggestion # IDE0038: Use pattern matching to avoid is check followed by a cast (without variable) dotnet_diagnostic.IDE0038.severity = suggestion # IDE0044: Make field readonly diff --git a/src/JSInterop/Microsoft.JSInterop/src/DotNetObjectReferenceOfT.cs b/src/JSInterop/Microsoft.JSInterop/src/DotNetObjectReferenceOfT.cs index 8e2c9a3b085d..70a61ec212b3 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/DotNetObjectReferenceOfT.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/DotNetObjectReferenceOfT.cs @@ -88,10 +88,7 @@ public void Dispose() { Disposed = true; - if (_jsRuntime != null) - { - _jsRuntime.ReleaseObjectReference(_objectId); - } + _jsRuntime?.ReleaseObjectReference(_objectId); } } diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvoker.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvoker.cs index 85926ea101e7..4341070894c2 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvoker.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvoker.cs @@ -504,10 +504,7 @@ private static void Rethrow(ActionExecutedContextSealed? context) return; } - if (context.ExceptionDispatchInfo != null) - { - context.ExceptionDispatchInfo.Throw(); - } + context.ExceptionDispatchInfo?.Throw(); if (context.Exception != null) { diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ResourceInvoker.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ResourceInvoker.cs index 6a1299b883ce..beeb0215988b 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ResourceInvoker.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ResourceInvoker.cs @@ -1447,10 +1447,7 @@ private static void Rethrow(ResourceExecutedContextSealed context) return; } - if (context.ExceptionDispatchInfo != null) - { - context.ExceptionDispatchInfo.Throw(); - } + context.ExceptionDispatchInfo?.Throw(); if (context.Exception != null) { @@ -1470,10 +1467,7 @@ private static void Rethrow(ExceptionContextSealed context) return; } - if (context.ExceptionDispatchInfo != null) - { - context.ExceptionDispatchInfo.Throw(); - } + context.ExceptionDispatchInfo?.Throw(); if (context.Exception != null) { @@ -1493,10 +1487,7 @@ private static void Rethrow(ResultExecutedContextSealed context) return; } - if (context.ExceptionDispatchInfo != null) - { - context.ExceptionDispatchInfo.Throw(); - } + context.ExceptionDispatchInfo?.Throw(); if (context.Exception != null) { diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageActionInvoker.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageActionInvoker.cs index 4d011f46ae44..6ad0d6faa2b4 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageActionInvoker.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageActionInvoker.cs @@ -703,10 +703,7 @@ private static void Rethrow(PageHandlerExecutedContext? context) return; } - if (context.ExceptionDispatchInfo != null) - { - context.ExceptionDispatchInfo.Throw(); - } + context.ExceptionDispatchInfo?.Throw(); if (context.Exception != null) { diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageResultExecutor.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageResultExecutor.cs index 600e9ecb929d..36cabd9e824f 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageResultExecutor.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageResultExecutor.cs @@ -104,9 +104,6 @@ public virtual Task ExecuteAsync(PageContext pageContext, PageResult result) private static void OnExecuting(PageContext pageContext) { var viewDataValuesProvider = pageContext.HttpContext.Features.Get(); - if (viewDataValuesProvider != null) - { - viewDataValuesProvider.ProvideViewDataValues(pageContext.ViewData); - } + viewDataValuesProvider?.ProvideViewDataValues(pageContext.ViewData); } } diff --git a/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs b/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs index 738135119007..eb0eb0bdff5f 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs @@ -154,10 +154,7 @@ private int Find(string key) /// public void Clear() { - if (_items != null) - { - _items.Clear(); - } + _items?.Clear(); } /// diff --git a/src/Mvc/Mvc.ViewFeatures/src/ExpressionHelper.cs b/src/Mvc/Mvc.ViewFeatures/src/ExpressionHelper.cs index 7cd2020cb8ef..976581d90d7e 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ExpressionHelper.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ExpressionHelper.cs @@ -135,10 +135,7 @@ public static string GetExpressionText(LambdaExpression expression, ConcurrentDi if (segmentCount == 0) { Debug.Assert(!doNotCache); - if (expressionTextCache != null) - { - expressionTextCache.TryAdd(expression, string.Empty); - } + expressionTextCache?.TryAdd(expression, string.Empty); return string.Empty; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/TagBuilder.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/TagBuilder.cs index 8312366c09b3..46b3ac5d5b1e 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/TagBuilder.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/TagBuilder.cs @@ -404,10 +404,7 @@ public void WriteTo(TextWriter writer, HtmlEncoder encoder) writer.Write(tagBuilder.TagName); tagBuilder.AppendAttributes(writer, encoder); writer.Write(">"); - if (tagBuilder._innerHtml != null) - { - tagBuilder._innerHtml.WriteTo(writer, encoder); - } + tagBuilder._innerHtml?.WriteTo(writer, encoder); writer.Write(""); diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResultExecutor.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResultExecutor.cs index dc2a2fd4fdae..d56b66ff3aff 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResultExecutor.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResultExecutor.cs @@ -162,10 +162,7 @@ await using (var intermediateWriter = _writerFactory.CreateWriter(bufferingStrea private static void OnExecuting(ViewContext viewContext) { var viewDataValuesProvider = viewContext.HttpContext.Features.Get(); - if (viewDataValuesProvider != null) - { - viewDataValuesProvider.ProvideViewDataValues(viewContext.ViewData); - } + viewDataValuesProvider?.ProvideViewDataValues(viewContext.ViewData); } private static Task GetViewComponentResult(IViewComponentHelper viewComponentHelper, ILogger logger, ViewComponentResult result) diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewExecutor.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewExecutor.cs index fc984f16d81f..9eeecd8abee4 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewExecutor.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewExecutor.cs @@ -265,9 +265,6 @@ await using (var writer = WriterFactory.CreateWriter(response.Body, resolvedCont private static void OnExecuting(ViewContext viewContext) { var viewDataValuesProvider = viewContext.HttpContext.Features.Get(); - if (viewDataValuesProvider != null) - { - viewDataValuesProvider.ProvideViewDataValues(viewContext.ViewData); - } + viewDataValuesProvider?.ProvideViewDataValues(viewContext.ViewData); } } diff --git a/src/Security/Authentication/Certificate/src/CertificateAuthenticationHandler.cs b/src/Security/Authentication/Certificate/src/CertificateAuthenticationHandler.cs index 44ed2a9ff193..9b7112ba021d 100644 --- a/src/Security/Authentication/Certificate/src/CertificateAuthenticationHandler.cs +++ b/src/Security/Authentication/Certificate/src/CertificateAuthenticationHandler.cs @@ -87,10 +87,7 @@ protected override async Task HandleAuthenticateAsync() } } - if (_cache != null) - { - _cache.Put(Context, clientCertificate, result); - } + _cache?.Put(Context, clientCertificate, result); return result; } catch (Exception ex) diff --git a/src/Servers/HttpSys/src/HttpSysOptions.cs b/src/Servers/HttpSys/src/HttpSysOptions.cs index f5eded3da02b..977efccd3c67 100644 --- a/src/Servers/HttpSys/src/HttpSysOptions.cs +++ b/src/Servers/HttpSys/src/HttpSysOptions.cs @@ -149,10 +149,7 @@ public long RequestQueueLimit throw new ArgumentOutOfRangeException(nameof(value), value, "The value must be greater than zero."); } - if (_requestQueue != null) - { - _requestQueue.SetLengthLimit(_requestQueueLength); - } + _requestQueue?.SetLengthLimit(_requestQueueLength); // Only store it if it succeeds or hasn't started yet _requestQueueLength = value; } @@ -210,10 +207,7 @@ public Http503VerbosityLevel Http503Verbosity throw new ArgumentOutOfRangeException(nameof(value), value, message); } - if (_requestQueue != null) - { - _requestQueue.SetRejectionVerbosity(value); - } + _requestQueue?.SetRejectionVerbosity(value); // Only store it if it succeeds or hasn't started yet _rejectionVebosityLevel = value; } diff --git a/src/Servers/HttpSys/src/RequestProcessing/Request.cs b/src/Servers/HttpSys/src/RequestProcessing/Request.cs index d0fb349f324f..292e29d11f8e 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/Request.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/Request.cs @@ -382,10 +382,7 @@ private void GetTlsHandshakeResults() } catch (Exception) { - if (certLoader != null) - { - certLoader.Dispose(); - } + certLoader?.Dispose(); throw; } return _clientCert; diff --git a/src/Servers/HttpSys/src/RequestProcessing/RequestStreamAsyncResult.cs b/src/Servers/HttpSys/src/RequestProcessing/RequestStreamAsyncResult.cs index 63871580b480..e34111ba08c3 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/RequestStreamAsyncResult.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/RequestStreamAsyncResult.cs @@ -150,10 +150,7 @@ private void Dispose(bool disposing) { if (disposing) { - if (_overlapped != null) - { - _overlapped.Dispose(); - } + _overlapped?.Dispose(); _cancellationRegistration.Dispose(); } } diff --git a/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.cs b/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.cs index 63f1de475cac..f91f110b0d96 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.cs @@ -316,14 +316,8 @@ public bool IsCompleted public void Dispose() { - if (_overlapped != null) - { - _overlapped.Dispose(); - } - if (_fileStream != null) - { - _fileStream.Dispose(); - } + _overlapped?.Dispose(); + _fileStream?.Dispose(); _cancellationRegistration.Dispose(); } } diff --git a/src/Servers/HttpSys/src/UrlPrefixCollection.cs b/src/Servers/HttpSys/src/UrlPrefixCollection.cs index e952868c6a5b..217a2fa49fd7 100644 --- a/src/Servers/HttpSys/src/UrlPrefixCollection.cs +++ b/src/Servers/HttpSys/src/UrlPrefixCollection.cs @@ -67,10 +67,7 @@ public void Add(UrlPrefix item) lock (_prefixes) { var id = _nextId++; - if (_urlGroup != null) - { - _urlGroup.RegisterPrefix(item.FullPrefix, id); - } + _urlGroup?.RegisterPrefix(item.FullPrefix, id); _prefixes.Add(id, item); } } @@ -157,10 +154,7 @@ public bool Remove(UrlPrefix item) if (pair.Value.Equals(item)) { id = pair.Key; - if (_urlGroup != null) - { - _urlGroup.UnregisterPrefix(pair.Value.FullPrefix); - } + _urlGroup?.UnregisterPrefix(pair.Value.FullPrefix); } } if (id.HasValue) diff --git a/src/Servers/Kestrel/Core/src/Internal/Http/Http1OutputProducer.cs b/src/Servers/Kestrel/Core/src/Internal/Http/Http1OutputProducer.cs index b4a2f71d5f30..150b62496bc8 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http/Http1OutputProducer.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http/Http1OutputProducer.cs @@ -787,10 +787,7 @@ public CompletedBuffer(IMemoryOwner? owner, Memory buffer, int lengt public void Return() { - if (_memoryOwner != null) - { - _memoryOwner.Dispose(); - } + _memoryOwner?.Dispose(); } } } diff --git a/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs b/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs index ebc70fd3bbcd..829941c76be1 100644 --- a/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs +++ b/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs @@ -244,10 +244,7 @@ public void Add(TKey key, TValue value) /// public void Clear() { - if (_dictionaryStorage != null) - { - _dictionaryStorage.Clear(); - } + _dictionaryStorage?.Clear(); if (_count == 0) { diff --git a/src/Shared/Process/ProcessEx.cs b/src/Shared/Process/ProcessEx.cs index 76ed1f4f34ba..c1a8d613f5a5 100644 --- a/src/Shared/Process/ProcessEx.cs +++ b/src/Shared/Process/ProcessEx.cs @@ -167,10 +167,7 @@ private void OnOutputData(object sender, DataReceivedEventArgs e) } } - if (_stdoutLines != null) - { - _stdoutLines.Add(e.Data); - } + _stdoutLines?.Add(e.Data); } private void OnProcessExited(object sender, EventArgs e) diff --git a/src/Shared/PropertyAsParameterInfo.cs b/src/Shared/PropertyAsParameterInfo.cs index da184a729032..04b6d379ec5b 100644 --- a/src/Shared/PropertyAsParameterInfo.cs +++ b/src/Shared/PropertyAsParameterInfo.cs @@ -45,10 +45,10 @@ public PropertyAsParameterInfo(PropertyInfo property, ParameterInfo parameterInf public override bool HasDefaultValue => _constructionParameterInfo is not null && _constructionParameterInfo.HasDefaultValue; public override object? DefaultValue - => _constructionParameterInfo is not null ? _constructionParameterInfo.DefaultValue : null; + => _constructionParameterInfo?.DefaultValue; public override int MetadataToken => _underlyingProperty.MetadataToken; public override object? RawDefaultValue - => _constructionParameterInfo is not null ? _constructionParameterInfo.RawDefaultValue : null; + => _constructionParameterInfo?.RawDefaultValue; /// /// Unwraps all parameters that contains and @@ -120,9 +120,9 @@ public static ReadOnlySpan Flatten(ParameterInfo[] parameters, Pa } } } - else if (flattenedParameters is not null) + else { - flattenedParameters.Add(parameters[i]); + flattenedParameters?.Add(parameters[i]); } } diff --git a/src/SignalR/server/Core/src/HubConnectionContext.cs b/src/SignalR/server/Core/src/HubConnectionContext.cs index 5ac7769617ce..185fb1b4f52e 100644 --- a/src/SignalR/server/Core/src/HubConnectionContext.cs +++ b/src/SignalR/server/Core/src/HubConnectionContext.cs @@ -729,9 +729,6 @@ internal void Cleanup() _closedRequestedRegistration?.Dispose(); // Use _streamTracker to avoid lazy init from StreamTracker getter if it doesn't exist - if (_streamTracker != null) - { - _streamTracker.CompleteAll(new OperationCanceledException("The underlying connection was closed.")); - } + _streamTracker?.CompleteAll(new OperationCanceledException("The underlying connection was closed.")); } } diff --git a/src/SignalR/server/Core/src/Internal/DefaultHubDispatcherLog.cs b/src/SignalR/server/Core/src/Internal/DefaultHubDispatcherLog.cs index 6394c478458e..24d6ee8b7fca 100644 --- a/src/SignalR/server/Core/src/Internal/DefaultHubDispatcherLog.cs +++ b/src/SignalR/server/Core/src/Internal/DefaultHubDispatcherLog.cs @@ -27,7 +27,7 @@ public static void StreamingResult(ILogger logger, string invocationId, ObjectMe { if (logger.IsEnabled(LogLevel.Trace)) { - var resultType = objectMethodExecutor.AsyncResultType == null ? objectMethodExecutor.MethodReturnType : objectMethodExecutor.AsyncResultType; + var resultType = objectMethodExecutor.AsyncResultType ?? objectMethodExecutor.MethodReturnType; StreamingResult(logger, invocationId, resultType.FullName); } } @@ -39,7 +39,7 @@ public static void SendingResult(ILogger logger, string? invocationId, ObjectMet { if (logger.IsEnabled(LogLevel.Trace)) { - var resultType = objectMethodExecutor.AsyncResultType == null ? objectMethodExecutor.MethodReturnType : objectMethodExecutor.AsyncResultType; + var resultType = objectMethodExecutor.AsyncResultType ?? objectMethodExecutor.MethodReturnType; SendingResult(logger, invocationId, resultType.FullName); } } diff --git a/src/Testing/src/xunit/EnvironmentVariableSkipConditionAttribute.cs b/src/Testing/src/xunit/EnvironmentVariableSkipConditionAttribute.cs index 632baeba7881..5786c5c5b713 100644 --- a/src/Testing/src/xunit/EnvironmentVariableSkipConditionAttribute.cs +++ b/src/Testing/src/xunit/EnvironmentVariableSkipConditionAttribute.cs @@ -78,7 +78,7 @@ public string SkipReason { get { - var value = _currentValue == null ? "(null)" : _currentValue; + var value = _currentValue ?? "(null)"; return $"Test skipped on environment variable with name '{_variableName}' and value '{value}' " + $"for the '{nameof(RunOnMatch)}' value of '{RunOnMatch}'."; }