From 63082aff94beda53458e2c66ac882687503db78f Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Fri, 22 Nov 2024 20:10:33 +0200 Subject: [PATCH] Simplify using statements (#5043) --- Directory.Build.props | 3 +- .../Middlewares/SwaggerUiIndexMiddleware.cs | 10 +- .../Middlewares/SwaggerUiIndexMiddleware.cs | 14 +-- .../DefaultTemplateFactory.cs | 6 +- .../Commands/Generation/AspNetCore/Exe.cs | 58 +++++---- src/NSwag.Commands/HostApplication.cs | 8 +- src/NSwag.Commands/HostFactoryResolver.cs | 117 +++++++++--------- 7 files changed, 99 insertions(+), 117 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 17352d6f83..f2e3db0aa2 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -68,7 +68,6 @@ [IDE0059] Unnecessary assignment of a value [IDE0060] Remove unused parameter [IDE0061] Use block body for local function - [IDE0063] 'using' statement can be simplified [IDE0074] Use compound assignment [IDE0078] Use pattern matching [IDE0083] Use pattern matching @@ -109,7 +108,7 @@ [SYSLIB0012] 'Assembly.CodeBase' is obsolete --> - $(NoWarn);IDE0005;IDE0008;IDE0011;IDE0017;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0061;IDE0063;IDE0074;IDE0078;IDE0083;IDE0090;IDE0130;IDE0160;IDE0200;IDE0260;IDE0270;IDE0290;IDE0300;IDE0305;IDE0301;IDE0330 + $(NoWarn);IDE0005;IDE0008;IDE0011;IDE0017;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0061;IDE0074;IDE0078;IDE0083;IDE0090;IDE0130;IDE0160;IDE0200;IDE0260;IDE0270;IDE0290;IDE0300;IDE0305;IDE0301;IDE0330 $(NoWarn);CA1200;CA1304;CA1305;CA1310;CA1311;CA1507;CA1510;CA1514;CA1710;CA1716;CA1720;CA1725;CA1805;CA1834;CA1845;CA1847;CA1861;CA1862;CA1865;CA1866;CA1870;CA2249;CA2263;SYSLIB0012 diff --git a/src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs b/src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs index bd21430d62..7a0b70ff25 100644 --- a/src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs +++ b/src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs @@ -23,12 +23,10 @@ public override async Task Invoke(IOwinContext context) if (context.Request.Path.HasValue && string.Equals(context.Request.Path.Value.Trim('/'), _indexPath.Trim('/'), StringComparison.OrdinalIgnoreCase)) { var stream = typeof(SwaggerUiIndexMiddleware).Assembly.GetManifestResourceStream(_resourcePath); - using (var reader = new StreamReader(stream)) - { - context.Response.Headers["Content-Type"] = "text/html; charset=utf-8"; - context.Response.StatusCode = 200; - context.Response.Write(await _settings.TransformHtmlAsync(reader.ReadToEnd(), context.Request, CancellationToken.None)); - } + using var reader = new StreamReader(stream); + context.Response.Headers["Content-Type"] = "text/html; charset=utf-8"; + context.Response.StatusCode = 200; + await context.Response.WriteAsync(await _settings.TransformHtmlAsync(reader.ReadToEnd(), context.Request, CancellationToken.None)); } else { diff --git a/src/NSwag.AspNetCore/Middlewares/SwaggerUiIndexMiddleware.cs b/src/NSwag.AspNetCore/Middlewares/SwaggerUiIndexMiddleware.cs index dd00e31771..2d0e057d46 100644 --- a/src/NSwag.AspNetCore/Middlewares/SwaggerUiIndexMiddleware.cs +++ b/src/NSwag.AspNetCore/Middlewares/SwaggerUiIndexMiddleware.cs @@ -23,16 +23,10 @@ public async Task Invoke(HttpContext context) if (context.Request.Path.HasValue && string.Equals(context.Request.Path.Value.Trim('/'), _indexPath.Trim('/'), StringComparison.OrdinalIgnoreCase)) { var stream = typeof(SwaggerUiIndexMiddleware).GetTypeInfo().Assembly.GetManifestResourceStream(_resourcePath); - using (var reader = new StreamReader(stream)) - { - context.Response.Headers["Content-Type"] = "text/html; charset=utf-8"; - context.Response.StatusCode = 200; - await context.Response.WriteAsync( - await _settings.TransformHtmlAsync( - await reader.ReadToEndAsync(), - context.Request, - context.RequestAborted)); - } + using var reader = new StreamReader(stream); + context.Response.Headers["Content-Type"] = "text/html; charset=utf-8"; + context.Response.StatusCode = 200; + await context.Response.WriteAsync(await _settings.TransformHtmlAsync(await reader.ReadToEndAsync(), context.Request, context.RequestAborted)); } else { diff --git a/src/NSwag.CodeGeneration/DefaultTemplateFactory.cs b/src/NSwag.CodeGeneration/DefaultTemplateFactory.cs index 3b66ae7625..f099760a77 100644 --- a/src/NSwag.CodeGeneration/DefaultTemplateFactory.cs +++ b/src/NSwag.CodeGeneration/DefaultTemplateFactory.cs @@ -48,10 +48,8 @@ protected override string GetEmbeddedLiquidTemplate(string language, string temp var resource = assembly.GetManifestResourceStream(resourceName); if (resource != null) { - using (var reader = new StreamReader(resource)) - { - return reader.ReadToEnd(); - } + using var reader = new StreamReader(resource); + return reader.ReadToEnd(); } return base.GetEmbeddedLiquidTemplate(language, template); diff --git a/src/NSwag.Commands/Commands/Generation/AspNetCore/Exe.cs b/src/NSwag.Commands/Commands/Generation/AspNetCore/Exe.cs index 61d16a9805..6255bb734d 100644 --- a/src/NSwag.Commands/Commands/Generation/AspNetCore/Exe.cs +++ b/src/NSwag.Commands/Commands/Generation/AspNetCore/Exe.cs @@ -32,43 +32,41 @@ public static async Task RunAsync( }; console?.WriteMessage($"Executing {executable} {arguments}{Environment.NewLine}"); - using (var process = Process.Start(startInfo)) + using var process = Process.Start(startInfo); + var tcs = new TaskCompletionSource(); + process.EnableRaisingEvents = true; + process.Exited += (_, eventArgs) => { - var tcs = new TaskCompletionSource(); - process.EnableRaisingEvents = true; - process.Exited += (_, eventArgs) => + if (process.ExitCode == 0) + { + tcs.TrySetResult(true); + } + else { - if (process.ExitCode == 0) - { - tcs.TrySetResult(true); - } - else - { #pragma warning disable CA2201 - tcs.TrySetException(new Exception($"Process failed with non-zero exit code '{process.ExitCode}'.")); + tcs.TrySetException(new Exception($"Process failed with non-zero exit code '{process.ExitCode}'.")); #pragma warning restore CA2201 - } - }; + } + }; - if (console != null) - { - process.OutputDataReceived += (_, eventArgs) => console.WriteMessage(eventArgs.Data + Environment.NewLine); - process.ErrorDataReceived += (_, eventArgs) => console.WriteError(eventArgs.Data + Environment.NewLine); + if (console != null) + { + process.OutputDataReceived += (_, eventArgs) => console.WriteMessage(eventArgs.Data + Environment.NewLine); + process.ErrorDataReceived += (_, eventArgs) => console.WriteError(eventArgs.Data + Environment.NewLine); - process.BeginErrorReadLine(); - process.BeginOutputReadLine(); - } + process.BeginErrorReadLine(); + process.BeginOutputReadLine(); + } - var result = await Task.WhenAny(tcs.Task, Task.Delay(timeout ?? TimeSpan.FromSeconds(60 * 5))).ConfigureAwait(false); - if (result != tcs.Task) - { - throw new InvalidOperationException($"Process {startInfo.FileName} timed out."); - } - else - { - console?.WriteMessage($"Done executing command. Exit Code: {process.ExitCode}.{Environment.NewLine}"); - return process.ExitCode; - } + var result = await Task.WhenAny(tcs.Task, Task.Delay(timeout ?? TimeSpan.FromSeconds(60 * 5))).ConfigureAwait(false); + if (result != tcs.Task) + { + throw new InvalidOperationException($"Process {startInfo.FileName} timed out."); + } + else + { + console?.WriteMessage($"Done executing command. Exit Code: {process.ExitCode}.{Environment.NewLine}"); + return process.ExitCode; } } diff --git a/src/NSwag.Commands/HostApplication.cs b/src/NSwag.Commands/HostApplication.cs index 591ce83692..13d0c28884 100644 --- a/src/NSwag.Commands/HostApplication.cs +++ b/src/NSwag.Commands/HostApplication.cs @@ -164,11 +164,9 @@ void OnEntryPointExit(Exception exception) // in the IServiceProvider var applicationLifetime = services.GetRequiredService(); - using (var registration = applicationLifetime.ApplicationStarted.Register(() => waitForStartTcs.TrySetResult(null))) - { - waitForStartTcs.Task.Wait(); - return services; - } + using var registration = applicationLifetime.ApplicationStarted.Register(() => waitForStartTcs.TrySetResult(null)); + waitForStartTcs.Task.Wait(); + return services; } catch (InvalidOperationException) { diff --git a/src/NSwag.Commands/HostFactoryResolver.cs b/src/NSwag.Commands/HostFactoryResolver.cs index 281e5340ab..b8bad0e1ec 100644 --- a/src/NSwag.Commands/HostFactoryResolver.cs +++ b/src/NSwag.Commands/HostFactoryResolver.cs @@ -188,84 +188,81 @@ public HostingListener(string[] args, MethodInfo entryPoint, TimeSpan waitTimeou public object CreateHost() { - using (var subscription = DiagnosticListener.AllListeners.Subscribe(this)) + using var subscription = DiagnosticListener.AllListeners.Subscribe(this); + // Kick off the entry point on a new thread so we don't block the current one + // in case we need to timeout the execution + var thread = new Thread(() => { + Exception exception = null; - // Kick off the entry point on a new thread so we don't block the current one - // in case we need to timeout the execution - var thread = new Thread(() => + try { - Exception exception = null; + // Set the async local to the instance of the HostingListener so we can filter events that + // aren't scoped to this execution of the entry point. + _currentListener.Value = this; - try + var parameters = _entryPoint.GetParameters(); + if (parameters.Length == 0) { - // Set the async local to the instance of the HostingListener so we can filter events that - // aren't scoped to this execution of the entry point. - _currentListener.Value = this; - - var parameters = _entryPoint.GetParameters(); - if (parameters.Length == 0) - { - _entryPoint.Invoke(null, Array.Empty()); - } - else - { - _entryPoint.Invoke(null, new object[] { _args }); - } - - // Try to set an exception if the entry point returns gracefully, this will force - // build to throw - _hostTcs.TrySetException(new InvalidOperationException("Unable to build IHost")); + _entryPoint.Invoke(null, Array.Empty()); } - catch (TargetInvocationException tie) when (tie.InnerException is StopTheHostException) + else { - // The host was stopped by our own logic + _entryPoint.Invoke(null, new object[] { _args }); } - catch (TargetInvocationException tie) - { - exception = tie.InnerException ?? tie; - // Another exception happened, propagate that to the caller - _hostTcs.TrySetException(exception); - } - catch (Exception ex) - { - exception = ex; - - // Another exception happened, propagate that to the caller - _hostTcs.TrySetException(ex); - } - finally - { - // Signal that the entry point is completed - _entrypointCompleted?.Invoke(exception); - } - }) + // Try to set an exception if the entry point returns gracefully, this will force + // build to throw + _hostTcs.TrySetException(new InvalidOperationException("Unable to build IHost")); + } + catch (TargetInvocationException tie) when (tie.InnerException is StopTheHostException) { - // Make sure this doesn't hang the process - IsBackground = true - }; - - // Start the thread - thread.Start(); + // The host was stopped by our own logic + } + catch (TargetInvocationException tie) + { + exception = tie.InnerException ?? tie; - try + // Another exception happened, propagate that to the caller + _hostTcs.TrySetException(exception); + } + catch (Exception ex) { - // Wait before throwing an exception - if (!_hostTcs.Task.Wait(_waitTimeout)) - { - throw new InvalidOperationException("Unable to build IHost"); - } + exception = ex; + + // Another exception happened, propagate that to the caller + _hostTcs.TrySetException(ex); } - catch (AggregateException) when (_hostTcs.Task.IsCompleted) + finally { - // Lets this propagate out of the call to GetAwaiter().GetResult() + // Signal that the entry point is completed + _entrypointCompleted?.Invoke(exception); } + }) + { + // Make sure this doesn't hang the process + IsBackground = true + }; - Debug.Assert(_hostTcs.Task.IsCompleted); + // Start the thread + thread.Start(); - return _hostTcs.Task.GetAwaiter().GetResult(); + try + { + // Wait before throwing an exception + if (!_hostTcs.Task.Wait(_waitTimeout)) + { + throw new InvalidOperationException("Unable to build IHost"); + } + } + catch (AggregateException) when (_hostTcs.Task.IsCompleted) + { + // Lets this propagate out of the call to GetAwaiter().GetResult() } + + Debug.Assert(_hostTcs.Task.IsCompleted); + + return _hostTcs.Task.GetAwaiter().GetResult(); } public void OnCompleted()