Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify using statements #5043

Merged
merged 1 commit into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -109,7 +108,7 @@

[SYSLIB0012] 'Assembly.CodeBase' is obsolete
-->
<NoWarn>$(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>
<NoWarn>$(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>
<NoWarn>$(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</NoWarn>
</PropertyGroup>

Expand Down
10 changes: 4 additions & 6 deletions src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>).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
{
Expand Down
14 changes: 4 additions & 10 deletions src/NSwag.AspNetCore/Middlewares/SwaggerUiIndexMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
6 changes: 2 additions & 4 deletions src/NSwag.CodeGeneration/DefaultTemplateFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
58 changes: 28 additions & 30 deletions src/NSwag.Commands/Commands/Generation/AspNetCore/Exe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,43 +32,41 @@ public static async Task<int> RunAsync(
};

console?.WriteMessage($"Executing {executable} {arguments}{Environment.NewLine}");
using (var process = Process.Start(startInfo))
using var process = Process.Start(startInfo);
var tcs = new TaskCompletionSource<bool>();
process.EnableRaisingEvents = true;
process.Exited += (_, eventArgs) =>
{
var tcs = new TaskCompletionSource<bool>();
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;
}
}

Expand Down
8 changes: 3 additions & 5 deletions src/NSwag.Commands/HostApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,11 +164,9 @@ void OnEntryPointExit(Exception exception)
// in the IServiceProvider
var applicationLifetime = services.GetRequiredService<IHostApplicationLifetime>();

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)
{
Expand Down
117 changes: 57 additions & 60 deletions src/NSwag.Commands/HostFactoryResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<object>());
}
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<object>());
}
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()
Expand Down
Loading