diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000..60a0f1e967 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,28 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** + +A clear and concise description of what the bug is. + +**Version used** + +With which version did you encounter this behavior. + +**To Reproduce** + +Ideally code samples or event unit test. + +**Expected behavior** + +A clear and concise description of what you expected to happen. + +**Additional context** + +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000..f0291e0597 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,24 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** + +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** + +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** + +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** + +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 37dead028a..ef4ff325e8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -44,7 +44,8 @@ jobs: with: dotnet-version: | 6.0 - - uses: actions/checkout@v3 + 9.0 + - uses: actions/checkout@v4 - name: 'Run: Compile, Test, Pack, Publish' run: ./build.cmd Compile Test Pack Publish env: @@ -53,22 +54,22 @@ jobs: CHOCO_API_KEY: ${{ secrets.CHOCO_API_KEY }} NPM_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }} - name: 'Publish: NSwag.zip' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: NSwag.zip path: artifacts/NSwag.zip - name: 'Publish: NSwag.Npm.zip' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: NSwag.Npm.zip path: artifacts/NSwag.Npm.zip - name: 'Publish: NSwagStudio.msi' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: NSwagStudio.msi path: artifacts/NSwagStudio.msi - name: 'Publish: NuGet Packages' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: NuGet Packages path: artifacts/*.nupkg @@ -80,7 +81,8 @@ jobs: with: dotnet-version: | 6.0 - - uses: actions/checkout@v3 + 9.0 + - uses: actions/checkout@v4 - name: 'Run: Compile, Test, Pack, Publish' run: ./build.cmd Compile Test Pack Publish env: @@ -96,7 +98,8 @@ jobs: with: dotnet-version: | 6.0 - - uses: actions/checkout@v3 + 9.0 + - uses: actions/checkout@v4 - name: 'Run: Compile, Test, Pack, Publish' run: ./build.cmd Compile Test Pack Publish env: diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index e0c1805f53..4d49e1d5b2 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -25,6 +25,10 @@ on: - '**/*.*' - '!**/*.md' +concurrency: + group: ${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.run_id }} + cancel-in-progress: true + jobs: windows-latest: name: windows-latest @@ -42,26 +46,27 @@ jobs: with: dotnet-version: | 6.0 - - uses: actions/checkout@v3 + 9.0 + - uses: actions/checkout@v4 - name: 'Run: Compile, Test, Pack' run: ./build.cmd Compile Test Pack - name: 'Publish: NSwag.zip' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: NSwag.zip path: artifacts/NSwag.zip - name: 'Publish: NSwag.Npm.zip' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: NSwag.Npm.zip path: artifacts/NSwag.Npm.zip - name: 'Publish: NSwagStudio.msi' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: NSwagStudio.msi path: artifacts/NSwagStudio.msi - name: 'Publish: NuGet Packages' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: NuGet Packages path: artifacts/*.nupkg @@ -73,7 +78,8 @@ jobs: with: dotnet-version: | 6.0 - - uses: actions/checkout@v3 + 9.0 + - uses: actions/checkout@v4 - name: 'Run: Compile, Test, Pack' run: ./build.cmd Compile Test Pack macos-latest: @@ -84,6 +90,7 @@ jobs: with: dotnet-version: | 6.0 - - uses: actions/checkout@v3 + 9.0 + - uses: actions/checkout@v4 - name: 'Run: Compile, Test, Pack' run: ./build.cmd Compile Test Pack diff --git a/.gitignore b/.gitignore index fe508bd541..ae82a3cb09 100644 --- a/.gitignore +++ b/.gitignore @@ -82,3 +82,4 @@ _ReSharper.Caches/ /artifacts *.binlog +*.gen diff --git a/.nuke/build.schema.json b/.nuke/build.schema.json index 57501ad2b6..4aecb4ebff 100644 --- a/.nuke/build.schema.json +++ b/.nuke/build.schema.json @@ -1,23 +1,50 @@ { "$schema": "http://json-schema.org/draft-04/schema#", - "$ref": "#/definitions/build", - "title": "Build Schema", "definitions": { - "build": { - "type": "object", + "Host": { + "type": "string", + "enum": [ + "AppVeyor", + "AzurePipelines", + "Bamboo", + "Bitbucket", + "Bitrise", + "GitHubActions", + "GitLab", + "Jenkins", + "Rider", + "SpaceAutomation", + "TeamCity", + "Terminal", + "TravisCI", + "VisualStudio", + "VSCode" + ] + }, + "ExecutableTarget": { + "type": "string", + "enum": [ + "Clean", + "Compile", + "InstallDependencies", + "Pack", + "Publish", + "Restore", + "Test" + ] + }, + "Verbosity": { + "type": "string", + "description": "", + "enum": [ + "Verbose", + "Normal", + "Minimal", + "Quiet" + ] + }, + "NukeBuild": { "properties": { - "ChocoApiKey": { - "type": "string", - "default": "Secrets must be entered via 'nuke :secrets [profile]'" - }, - "Configuration": { - "type": "string", - "description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)", - "enum": [ - "Debug", - "Release" - ] - }, "Continue": { "type": "boolean", "description": "Indicates to continue a previously failed build attempt" @@ -27,42 +54,13 @@ "description": "Shows the help text for this build assembly" }, "Host": { - "type": "string", "description": "Host for execution. Default is 'automatic'", - "enum": [ - "AppVeyor", - "AzurePipelines", - "Bamboo", - "Bitbucket", - "Bitrise", - "GitHubActions", - "GitLab", - "Jenkins", - "Rider", - "SpaceAutomation", - "TeamCity", - "Terminal", - "TravisCI", - "VisualStudio", - "VSCode" - ] - }, - "MyGetApiKey": { - "type": "string", - "default": "Secrets must be entered via 'nuke :secrets [profile]'" + "$ref": "#/definitions/Host" }, "NoLogo": { "type": "boolean", "description": "Disables displaying the NUKE logo" }, - "NpmAuthToken": { - "type": "string", - "default": "Secrets must be entered via 'nuke :secrets [profile]'" - }, - "NuGetApiKey": { - "type": "string", - "default": "Secrets must be entered via 'nuke :secrets [profile]'" - }, "Partition": { "type": "string", "description": "Partition to use on CI" @@ -86,49 +84,58 @@ "type": "array", "description": "List of targets to be skipped. Empty list skips all dependencies", "items": { - "type": "string", - "enum": [ - "Clean", - "Compile", - "InstallDependencies", - "Pack", - "Publish", - "Restore", - "Test" - ] + "$ref": "#/definitions/ExecutableTarget" } }, - "Solution": { - "type": "string", - "description": "Path to a solution file that is automatically loaded" - }, "Target": { "type": "array", "description": "List of targets to be invoked. Default is '{default_target}'", "items": { - "type": "string", - "enum": [ - "Clean", - "Compile", - "InstallDependencies", - "Pack", - "Publish", - "Restore", - "Test" - ] + "$ref": "#/definitions/ExecutableTarget" } }, "Verbosity": { - "type": "string", "description": "Logging verbosity during build execution. Default is 'Normal'", + "$ref": "#/definitions/Verbosity" + } + } + } + }, + "allOf": [ + { + "properties": { + "ChocoApiKey": { + "type": "string", + "default": "Secrets must be entered via 'nuke :secrets [profile]'" + }, + "Configuration": { + "type": "string", + "description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)", "enum": [ - "Minimal", - "Normal", - "Quiet", - "Verbose" + "Debug", + "Release" ] + }, + "MyGetApiKey": { + "type": "string", + "default": "Secrets must be entered via 'nuke :secrets [profile]'" + }, + "NpmAuthToken": { + "type": "string", + "default": "Secrets must be entered via 'nuke :secrets [profile]'" + }, + "NuGetApiKey": { + "type": "string", + "default": "Secrets must be entered via 'nuke :secrets [profile]'" + }, + "Solution": { + "type": "string", + "description": "Path to a solution file that is automatically loaded" } } + }, + { + "$ref": "#/definitions/NukeBuild" } - } + ] } diff --git a/Directory.Build.props b/Directory.Build.props index 96d26cefcc..2d97971095 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 14.1.0 + 14.2.0 Rico Suter Copyright © Rico Suter, 2023 @@ -19,8 +19,11 @@ https://github.com/RicoSuter/NSwag.git latest - - false + enable + + true + + NU1901,NU1902,NU1903,NU1904 true true @@ -35,11 +38,50 @@ - - - - + + + true + latest-Recommended + true + + $(NoWarn);IDE0005;IDE0008;IDE0017;IDE0021;IDE0022;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0056;IDE0057;IDE0060;IDE0090;IDE0130;IDE0160;IDE0200;IDE0270;IDE0290;IDE0330 + $(NoWarn);CA1200;CA1510;CA1514;CA1710;CA1716;CA1720;CA1725;CA1845;CA1870;CA2263;SYSLIB0012 + + diff --git a/build/Build.CI.GitHubActions.cs b/build/Build.CI.GitHubActions.cs index bbf5ea69d1..aa87ae10d8 100644 --- a/build/Build.CI.GitHubActions.cs +++ b/build/Build.CI.GitHubActions.cs @@ -15,8 +15,8 @@ OnPullRequestExcludePaths = ["**/*.md"], PublishArtifacts = true, InvokedTargets = [nameof(Compile), nameof(Test), nameof(Pack)], - CacheKeyFiles = new string[0], - JobConcurrencyCancelInProgress = false), + CacheKeyFiles = [], + ConcurrencyCancelInProgress = true), ] [CustomGitHubActions( "build", @@ -30,11 +30,9 @@ PublishArtifacts = true, InvokedTargets = [nameof(Compile), nameof(Test), nameof(Pack), nameof(Publish)], ImportSecrets = ["NUGET_API_KEY", "MYGET_API_KEY", "CHOCO_API_KEY", "NPM_AUTH_TOKEN"], - CacheKeyFiles = new string[0]) + CacheKeyFiles = []) ] -public partial class Build -{ -} +public partial class Build; class CustomGitHubActionsAttribute : GitHubActionsAttribute { @@ -49,7 +47,7 @@ protected override GitHubActionsJob GetJobs(GitHubActionsImage image, IReadOnlyC var newSteps = new List(job.Steps); // only need to list the ones that are missing from default image - newSteps.Insert(0, new GitHubActionsSetupDotNetStep(["6.0"])); + newSteps.Insert(0, new GitHubActionsSetupDotNetStep(["6.0", "9.0"])); var onWindows = image.ToString().StartsWith("windows", StringComparison.OrdinalIgnoreCase); if (onWindows) diff --git a/build/Build.Pack.cs b/build/Build.Pack.cs index 7a0b4e0d76..4c1a971553 100644 --- a/build/Build.Pack.cs +++ b/build/Build.Pack.cs @@ -10,7 +10,6 @@ using Nuke.Common.Tools.MSBuild; using Nuke.Common.Tools.NuGet; -using static Nuke.Common.IO.FileSystemTasks; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Common.Tools.MSBuild.MSBuildTasks; using static Nuke.Common.Tools.NuGet.NuGetTasks; @@ -115,7 +114,7 @@ public partial class Build foreach (var artifact in artifacts) { - CopyFileToDirectory(artifact, ArtifactsDirectory); + artifact.CopyToDirectory(ArtifactsDirectory); } // patch npm version @@ -129,7 +128,7 @@ public partial class Build ZipFile.CreateFromDirectory(NSwagStudioBinaries, ArtifactsDirectory / "NSwag.zip"); // NSwagStudio.msi - CopyFileToDirectory(ArtifactsDirectory / "bin" / "NSwagStudio.Installer" / Configuration / "NSwagStudio.msi", ArtifactsDirectory); + (ArtifactsDirectory / "bin" / "NSwagStudio.Installer" / Configuration / "NSwagStudio.msi").CopyToDirectory(ArtifactsDirectory); }); } diff --git a/build/Build.Publish.cs b/build/Build.Publish.cs index d297dc22f9..925680c8f1 100644 --- a/build/Build.Publish.cs +++ b/build/Build.Publish.cs @@ -8,7 +8,7 @@ using Nuke.Common.Tooling; using Nuke.Common.Tools.Chocolatey; using Nuke.Common.Tools.DotNet; - +using Nuke.Common.Tools.GitHub; using static Nuke.Common.Tools.Chocolatey.ChocolateyTasks; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Common.Tools.Npm.NpmTasks; @@ -29,7 +29,7 @@ public partial class Build string SourceToUse => IsTaggedBuild ? NuGetSource : MyGetGetSource; Target Publish => _ => _ - .OnlyWhenDynamic(() => IsRunningOnWindows && (GitRepository.IsOnMainOrMasterBranch() || IsTaggedBuild)) + .OnlyWhenDynamic(() => IsRunningOnWindows && (GitRepository.IsOnMainOrMasterBranch() || IsTaggedBuild) && GitRepository.GetGitHubOwner() == "RicoSuter") .DependsOn(Pack) .Requires(() => NuGetApiKey, () => MyGetApiKey, () => ChocoApiKey, () => NpmAuthToken) .Executes(() => diff --git a/build/Build.cs b/build/Build.cs index 7e42cbdb7c..337583af7a 100644 --- a/build/Build.cs +++ b/build/Build.cs @@ -5,6 +5,7 @@ using Microsoft.Build.Evaluation; using Microsoft.Build.Locator; using Nuke.Common; +using Nuke.Common.CI.GitHubActions; using Nuke.Common.Git; using Nuke.Common.IO; using Nuke.Common.ProjectModel; @@ -14,7 +15,6 @@ using Nuke.Common.Tools.Npm; using Nuke.Common.Utilities.Collections; -using static Nuke.Common.IO.FileSystemTasks; using static Nuke.Common.Tools.Chocolatey.ChocolateyTasks; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Common.Tools.MSBuild.MSBuildTasks; @@ -230,6 +230,7 @@ protected override void OnBuildInitialized() .EnableNoRestore() .EnableNoBuild() .SetConfiguration(Configuration) + .When(GitHubActions.Instance is not null, x => x.SetLoggers("GitHubActions")) ); } }); @@ -268,7 +269,7 @@ void PublishConsoleProject(Project project, string[] targetFrameworks) PublishConsoleProject(consoleX86Project, ["net462"]); PublishConsoleProject(consoleProject, ["net462"]); } - PublishConsoleProject(consoleCoreProject, ["net6.0", "net8.0"]); + PublishConsoleProject(consoleCoreProject, ["net8.0", "net9.0"]); void CopyConsoleBinaries(AbsolutePath target) { @@ -278,14 +279,14 @@ void CopyConsoleBinaries(AbsolutePath target) if (IsRunningOnWindows) { var consoleX86Directory = ArtifactsDirectory / "publish" / consoleX86Project.Name / configuration; - CopyFileToDirectory(consoleX86Directory / "NSwag.x86.exe", target / "Win"); - CopyFileToDirectory(consoleX86Directory / "NSwag.x86.exe.config", target / "Win"); + (consoleX86Directory / "NSwag.x86.exe").CopyToDirectory(target / "Win"); + (consoleX86Directory / "NSwag.x86.exe.config").CopyToDirectory(target / "Win"); - CopyDirectoryRecursively(ArtifactsDirectory / "publish" / consoleProject.Name / configuration, target / "Win", DirectoryExistsPolicy.Merge); + (ArtifactsDirectory / "publish" / consoleProject.Name / configuration).Copy(target / "Win", ExistsPolicy.DirectoryMerge); } - CopyDirectoryRecursively(ArtifactsDirectory / "publish" / consoleCoreProject.Name / (configuration + "_net6.0"), target / "Net60"); - CopyDirectoryRecursively(ArtifactsDirectory / "publish" / consoleCoreProject.Name / (configuration + "_net8.0"), target / "Net80"); + (ArtifactsDirectory / "publish" / consoleCoreProject.Name / (configuration + "_net8.0")).Copy(target / "Net80"); + (ArtifactsDirectory / "publish" / consoleCoreProject.Name / (configuration + "_net9.0")).Copy(target / "Net90"); } if (IsRunningOnWindows) diff --git a/build/_build.csproj b/build/_build.csproj index feca84c4f1..09e0acf10b 100644 --- a/build/_build.csproj +++ b/build/_build.csproj @@ -16,12 +16,13 @@ - + + - - + + diff --git a/global.json b/global.json index 989a69cafb..f15a959283 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "8.0.100", + "version": "9.0.100", "rollForward": "latestMinor" } } \ No newline at end of file diff --git a/src/NSwag.Annotations/OpenApiBodyParameterAttribute.cs b/src/NSwag.Annotations/OpenApiBodyParameterAttribute.cs index 60fd9d91fb..1e442b00cf 100644 --- a/src/NSwag.Annotations/OpenApiBodyParameterAttribute.cs +++ b/src/NSwag.Annotations/OpenApiBodyParameterAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Specifies that the operation consumes the POST body. @@ -17,7 +15,7 @@ public class OpenApiBodyParameterAttribute : Attribute /// Initializes a new instance of the class with the 'application/json' mime type. public OpenApiBodyParameterAttribute() { - MimeTypes = new[] { "application/json" }; + MimeTypes = ["application/json"]; } /// Initializes a new instance of the class. diff --git a/src/NSwag.Annotations/OpenApiControllerAttribute.cs b/src/NSwag.Annotations/OpenApiControllerAttribute.cs index b59760c26e..cf572ddef1 100644 --- a/src/NSwag.Annotations/OpenApiControllerAttribute.cs +++ b/src/NSwag.Annotations/OpenApiControllerAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Describes the controller. diff --git a/src/NSwag.Annotations/OpenApiExtensionDataAttribute.cs b/src/NSwag.Annotations/OpenApiExtensionDataAttribute.cs index ee40a48958..56fde78339 100644 --- a/src/NSwag.Annotations/OpenApiExtensionDataAttribute.cs +++ b/src/NSwag.Annotations/OpenApiExtensionDataAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Indicates extension data to be added to the Swagger definition. diff --git a/src/NSwag.Annotations/OpenApiFileAttribute.cs b/src/NSwag.Annotations/OpenApiFileAttribute.cs index ec169cafa1..e328564647 100644 --- a/src/NSwag.Annotations/OpenApiFileAttribute.cs +++ b/src/NSwag.Annotations/OpenApiFileAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Specifies a parameter or class to be handled as file. diff --git a/src/NSwag.Annotations/OpenApiIgnoreAttribute.cs b/src/NSwag.Annotations/OpenApiIgnoreAttribute.cs index a981885c6d..1096a56ccf 100644 --- a/src/NSwag.Annotations/OpenApiIgnoreAttribute.cs +++ b/src/NSwag.Annotations/OpenApiIgnoreAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Excludes an action method from the generated Swagger specification. diff --git a/src/NSwag.Annotations/OpenApiOperationAttribute.cs b/src/NSwag.Annotations/OpenApiOperationAttribute.cs index d93c89d361..5e57880bf6 100644 --- a/src/NSwag.Annotations/OpenApiOperationAttribute.cs +++ b/src/NSwag.Annotations/OpenApiOperationAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Specifies the operation id, summary and description diff --git a/src/NSwag.Annotations/OpenApiOperationProcessorAttribute.cs b/src/NSwag.Annotations/OpenApiOperationProcessorAttribute.cs index 71276b3b3c..1d238bd710 100644 --- a/src/NSwag.Annotations/OpenApiOperationProcessorAttribute.cs +++ b/src/NSwag.Annotations/OpenApiOperationProcessorAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Registers an operation processor for the given method or class. diff --git a/src/NSwag.Annotations/OpenApiTagAttribute.cs b/src/NSwag.Annotations/OpenApiTagAttribute.cs index ab2e12ac44..926aae385d 100644 --- a/src/NSwag.Annotations/OpenApiTagAttribute.cs +++ b/src/NSwag.Annotations/OpenApiTagAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Specifies the tags for an operation. diff --git a/src/NSwag.Annotations/OpenApiTagsAttribute.cs b/src/NSwag.Annotations/OpenApiTagsAttribute.cs index 7fda9434f7..2b385f71e4 100644 --- a/src/NSwag.Annotations/OpenApiTagsAttribute.cs +++ b/src/NSwag.Annotations/OpenApiTagsAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Specifies the tags for an operation or a document. diff --git a/src/NSwag.Annotations/ResponseTypeAttribute.cs b/src/NSwag.Annotations/ResponseTypeAttribute.cs index 8e5b0abb70..5b50ae192e 100644 --- a/src/NSwag.Annotations/ResponseTypeAttribute.cs +++ b/src/NSwag.Annotations/ResponseTypeAttribute.cs @@ -6,7 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; +using System.Globalization; using System.Net; namespace NSwag.Annotations @@ -38,7 +38,7 @@ public ResponseTypeAttribute(string httpStatusCode, Type responseType) /// The JSON result type of the MVC or Web API action method. public ResponseTypeAttribute(int httpStatusCode, Type responseType) { - HttpStatusCode = httpStatusCode.ToString(); + HttpStatusCode = httpStatusCode.ToString(CultureInfo.InvariantCulture); ResponseType = responseType; } @@ -47,7 +47,7 @@ public ResponseTypeAttribute(int httpStatusCode, Type responseType) /// The JSON result type of the MVC or Web API action method. public ResponseTypeAttribute(HttpStatusCode httpStatusCode, Type responseType) { - HttpStatusCode = ((int)httpStatusCode).ToString(); + HttpStatusCode = ((int)httpStatusCode).ToString(CultureInfo.InvariantCulture); ResponseType = responseType; } diff --git a/src/NSwag.Annotations/SwaggerDefaultResponseAttribute.cs b/src/NSwag.Annotations/SwaggerDefaultResponseAttribute.cs index b6d82bb875..49c5709532 100644 --- a/src/NSwag.Annotations/SwaggerDefaultResponseAttribute.cs +++ b/src/NSwag.Annotations/SwaggerDefaultResponseAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Specifies that a default response (HTTP 200/204) should be generated from the return type of the operation method diff --git a/src/NSwag.Annotations/SwaggerResponseAttribute.cs b/src/NSwag.Annotations/SwaggerResponseAttribute.cs index 6be1bafb89..f498a1de65 100644 --- a/src/NSwag.Annotations/SwaggerResponseAttribute.cs +++ b/src/NSwag.Annotations/SwaggerResponseAttribute.cs @@ -6,7 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; +using System.Globalization; using System.Net; namespace NSwag.Annotations @@ -38,7 +38,7 @@ public SwaggerResponseAttribute(string httpStatusCode, Type responseType) /// The JSON result type of the MVC or Web API action method. public SwaggerResponseAttribute(int httpStatusCode, Type responseType) { - StatusCode = httpStatusCode.ToString(); + StatusCode = httpStatusCode.ToString(CultureInfo.InvariantCulture); Type = responseType; } @@ -47,7 +47,7 @@ public SwaggerResponseAttribute(int httpStatusCode, Type responseType) /// The JSON result type of the MVC or Web API action method. public SwaggerResponseAttribute(HttpStatusCode httpStatusCode, Type responseType) { - StatusCode = ((int)httpStatusCode).ToString(); + StatusCode = ((int)httpStatusCode).ToString(CultureInfo.InvariantCulture); Type = responseType; } diff --git a/src/NSwag.Annotations/WillReadBodyAttribute.cs b/src/NSwag.Annotations/WillReadBodyAttribute.cs index 07ac08eae9..15c02d4938 100644 --- a/src/NSwag.Annotations/WillReadBodyAttribute.cs +++ b/src/NSwag.Annotations/WillReadBodyAttribute.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Annotations { /// Specifies whether the parameter or class reads the body. diff --git a/src/NSwag.ApiDescription.Client/NSwag.ApiDescription.Client.targets b/src/NSwag.ApiDescription.Client/NSwag.ApiDescription.Client.targets index 662b846518..46996343e5 100644 --- a/src/NSwag.ApiDescription.Client/NSwag.ApiDescription.Client.targets +++ b/src/NSwag.ApiDescription.Client/NSwag.ApiDescription.Client.targets @@ -3,9 +3,11 @@ <_NSwagCommand>$(NSwagExe) <_NSwagCommand - Condition="'$(MSBuildRuntimeType)' == 'Core'">dotnet --roll-forward-on-no-candidate-fx 2 "$(NSwagDir_Net60)/dotnet-nswag.dll" + Condition="'$(MSBuildRuntimeType)' == 'Core'">dotnet --roll-forward-on-no-candidate-fx 2 "$(NSwagDir_Net80)/dotnet-nswag.dll" <_NSwagCommand Condition="'$(TargetFramework)' == 'net8.0'">dotnet --roll-forward-on-no-candidate-fx 2 "$(NSwagDir_Net80)/dotnet-nswag.dll" + <_NSwagCommand + Condition="'$(TargetFramework)' == 'net9.0'">dotnet --roll-forward-on-no-candidate-fx 2 "$(NSwagDir_Net90)/dotnet-nswag.dll" diff --git a/src/NSwag.AspNet.Owin/Middlewares/OpenApiDocumentMiddleware.cs b/src/NSwag.AspNet.Owin/Middlewares/OpenApiDocumentMiddleware.cs index 9a69a9d5bf..9bcb3f416d 100644 --- a/src/NSwag.AspNet.Owin/Middlewares/OpenApiDocumentMiddleware.cs +++ b/src/NSwag.AspNet.Owin/Middlewares/OpenApiDocumentMiddleware.cs @@ -6,10 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; using System.Runtime.ExceptionServices; -using System.Threading.Tasks; using Microsoft.Owin; using NSwag.Generation.WebApi; @@ -34,7 +31,7 @@ public class OpenApiDocumentMiddleware : OwinMiddleware public OpenApiDocumentMiddleware(OwinMiddleware next, string path, IEnumerable controllerTypes, SwaggerSettings settings) : base(next) { - _path = path.StartsWith("/") ? path : '/' + path; + _path = path.StartsWith('/') ? path : '/' + path; _controllerTypes = controllerTypes; _settings = settings; } diff --git a/src/NSwag.AspNet.Owin/Middlewares/RedirectToIndexMiddleware.cs b/src/NSwag.AspNet.Owin/Middlewares/RedirectToIndexMiddleware.cs index 128ad39f69..e2d2ef8490 100644 --- a/src/NSwag.AspNet.Owin/Middlewares/RedirectToIndexMiddleware.cs +++ b/src/NSwag.AspNet.Owin/Middlewares/RedirectToIndexMiddleware.cs @@ -6,13 +6,11 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Threading.Tasks; using Microsoft.Owin; namespace NSwag.AspNet.Owin.Middlewares { - internal class RedirectToIndexMiddleware : OwinMiddleware + internal sealed class RedirectToIndexMiddleware : OwinMiddleware { private readonly string _internalUiRoute; private readonly string _internalSwaggerRoute; diff --git a/src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs b/src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs index c4b8c9d2b5..7a0b70ff25 100644 --- a/src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs +++ b/src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs @@ -1,13 +1,9 @@ -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Owin; using NSwag.Generation; namespace NSwag.AspNet.Owin.Middlewares { - internal class SwaggerUiIndexMiddleware : OwinMiddleware + internal sealed class SwaggerUiIndexMiddleware : OwinMiddleware where T : OpenApiDocumentGeneratorSettings, new() { private readonly string _indexPath; @@ -27,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.AspNet.Owin/NSwag.AspNet.Owin.csproj b/src/NSwag.AspNet.Owin/NSwag.AspNet.Owin.csproj index c137a8b05f..944d488bd8 100644 --- a/src/NSwag.AspNet.Owin/NSwag.AspNet.Owin.csproj +++ b/src/NSwag.AspNet.Owin/NSwag.AspNet.Owin.csproj @@ -17,6 +17,7 @@ + diff --git a/src/NSwag.AspNet.Owin/SwaggerExtensions.cs b/src/NSwag.AspNet.Owin/SwaggerExtensions.cs index da4551b11e..592b0ebb73 100644 --- a/src/NSwag.AspNet.Owin/SwaggerExtensions.cs +++ b/src/NSwag.AspNet.Owin/SwaggerExtensions.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; using Microsoft.Owin; using Microsoft.Owin.Extensions; @@ -35,7 +32,7 @@ public static IAppBuilder UseOpenApi( Assembly webApiAssembly, Action> configure = null) { - return app.UseOpenApi(new[] { webApiAssembly }, configure); + return app.UseOpenApi([webApiAssembly], configure); } /// Adds the OpenAPI/Swagger generator to the OWIN pipeline. @@ -84,7 +81,7 @@ public static IAppBuilder UseSwaggerUi( Assembly webApiAssembly, Action> configure = null) { - return app.UseSwaggerUi(new[] { webApiAssembly }, configure); + return app.UseSwaggerUi([webApiAssembly], configure); } /// Adds the Swagger generator and Swagger UI to the OWIN pipeline. @@ -155,7 +152,7 @@ public static IAppBuilder UseSwaggerReDoc( Assembly webApiAssembly, Action> configure = null) { - return app.UseSwaggerReDoc(new[] { webApiAssembly }, configure); + return app.UseSwaggerReDoc([webApiAssembly], configure); } /// Adds the Swagger generator and Swagger UI to the OWIN pipeline. diff --git a/src/NSwag.AspNet.Owin/SwaggerUi/index.html b/src/NSwag.AspNet.Owin/SwaggerUi/index.html index 1e23b0e15a..ff9a97267d 100644 --- a/src/NSwag.AspNet.Owin/SwaggerUi/index.html +++ b/src/NSwag.AspNet.Owin/SwaggerUi/index.html @@ -27,26 +27,10 @@ } var urls = {Urls}; - const disableTryItOutPlugin = function() { - return { - statePlugins: { - spec: { - wrapSelectors: { - allowTryItOutFor: function() { - return function() { - return {EnableTryItOut}; - } - } - } - } - } - } - } - // Build a system var ui = SwaggerUIBundle({ url: url, - urls: urls, + urls: urls, validatorUrl: {ValidatorUrl}, oauth2RedirectUrl: {RedirectUrl}, @@ -58,8 +42,7 @@ SwaggerUIStandalonePreset ], plugins: [ - SwaggerUIBundle.plugins.DownloadUrl, - disableTryItOutPlugin + SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout" }); diff --git a/src/NSwag.AspNet.WebApi/JsonExceptionFilterAttribute.cs b/src/NSwag.AspNet.WebApi/JsonExceptionFilterAttribute.cs index dee6534b24..aeb7ecaf86 100644 --- a/src/NSwag.AspNet.WebApi/JsonExceptionFilterAttribute.cs +++ b/src/NSwag.AspNet.WebApi/JsonExceptionFilterAttribute.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; @@ -26,7 +23,7 @@ public class JsonExceptionFilterAttribute : ActionFilterAttribute { private readonly bool _hideStackTrace; private readonly IDictionary _searchedNamespaces; - private readonly List _exceptionTypes = new List(); + private readonly List _exceptionTypes = []; /// Initializes a new instance of the class. /// The serialized exception types. @@ -79,7 +76,7 @@ public override void OnActionExecuted(HttpActionExecutedContext context) } } - private int GetStatusCode(Exception exception, HttpActionExecutedContext context) + private static int GetStatusCode(Exception exception, HttpActionExecutedContext context) { if (context.ActionContext.ActionDescriptor is ReflectedHttpActionDescriptor actionDescriptor) { @@ -105,7 +102,7 @@ private int GetStatusCode(Exception exception, HttpActionExecutedContext context return 500; } - private JsonSerializerSettings CopySettings(JsonSerializerSettings settings) + private static JsonSerializerSettings CopySettings(JsonSerializerSettings settings) { var settingsCopy = new JsonSerializerSettings(); diff --git a/src/NSwag.AspNet.WebApi/NSwag.AspNet.WebApi.csproj b/src/NSwag.AspNet.WebApi/NSwag.AspNet.WebApi.csproj index a3620df7ad..43eb6983a7 100644 --- a/src/NSwag.AspNet.WebApi/NSwag.AspNet.WebApi.csproj +++ b/src/NSwag.AspNet.WebApi/NSwag.AspNet.WebApi.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/NSwag.AspNetCore.Launcher/NSwag.AspNetCore.Launcher.csproj b/src/NSwag.AspNetCore.Launcher/NSwag.AspNetCore.Launcher.csproj index e0cf5ce4e2..d44def6312 100644 --- a/src/NSwag.AspNetCore.Launcher/NSwag.AspNetCore.Launcher.csproj +++ b/src/NSwag.AspNetCore.Launcher/NSwag.AspNetCore.Launcher.csproj @@ -1,12 +1,12 @@  - net6.0;net462 + net8.0;net462 x64 Exe false - + \ No newline at end of file diff --git a/src/NSwag.AspNetCore.Launcher/Program.cs b/src/NSwag.AspNetCore.Launcher/Program.cs index e2c61b6b99..2e40c0177a 100644 --- a/src/NSwag.AspNetCore.Launcher/Program.cs +++ b/src/NSwag.AspNetCore.Launcher/Program.cs @@ -1,11 +1,8 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; +using System.Reflection; namespace NSwag.AspNetCore.Launcher { - internal class Program + internal sealed class Program { // Used to load NSwag.Commands into a process running with the app's dependency context private const string EntryPointType = "NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint"; @@ -60,7 +57,7 @@ internal class Program ["System.Text.Encodings.Web"] = new AssemblyLoadInfo(new Version(4, 0, 0)), }; - static int Main(string[] args) + private static int Main(string[] args) { // Usage: NSwag.Console.AspNetCore [settingsFile] [toolsDirectory] if (args.Length < 2) @@ -129,7 +126,7 @@ static int Main(string[] args) try { - method.Invoke(null, new[] { commandContent, outputFile, applicationName }); + method.Invoke(null, [commandContent, outputFile, applicationName]); } catch (Exception ex) { @@ -169,7 +166,7 @@ private static bool TryLoadReferencedAssemblies() return true; } - private class AssemblyLoadInfo + private sealed class AssemblyLoadInfo { public AssemblyLoadInfo(Version minimumRequiredVersion) { diff --git a/src/NSwag.AspNetCore/ApiverseUiSettings.cs b/src/NSwag.AspNetCore/ApiverseUiSettings.cs index 548efafbeb..99b730f1b7 100644 --- a/src/NSwag.AspNetCore/ApiverseUiSettings.cs +++ b/src/NSwag.AspNetCore/ApiverseUiSettings.cs @@ -7,8 +7,6 @@ //----------------------------------------------------------------------- using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; namespace NSwag.AspNetCore { diff --git a/src/NSwag.AspNetCore/Extensions/NSwagApplicationBuilderExtensions.cs b/src/NSwag.AspNetCore/Extensions/NSwagApplicationBuilderExtensions.cs index 83d503bb53..51c4df58a7 100644 --- a/src/NSwag.AspNetCore/Extensions/NSwagApplicationBuilderExtensions.cs +++ b/src/NSwag.AspNetCore/Extensions/NSwagApplicationBuilderExtensions.cs @@ -4,9 +4,6 @@ using Microsoft.Extensions.Options; using NSwag.AspNetCore; using NSwag.AspNetCore.Middlewares; -using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; namespace Microsoft.AspNetCore.Builder diff --git a/src/NSwag.AspNetCore/Extensions/NSwagServiceCollectionExtensions.cs b/src/NSwag.AspNetCore/Extensions/NSwagServiceCollectionExtensions.cs index f827cff744..5e0bb0ceb9 100644 --- a/src/NSwag.AspNetCore/Extensions/NSwagServiceCollectionExtensions.cs +++ b/src/NSwag.AspNetCore/Extensions/NSwagServiceCollectionExtensions.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.ApiDescriptions; using Microsoft.Extensions.Options; @@ -84,7 +81,7 @@ public static IServiceCollection AddSwaggerDocument(this IServiceCollection serv if (newtonsoftSettings != null && !hasSystemTextJsonOutputFormatter) { settings.ApplySettings(new NewtonsoftJsonSchemaGeneratorSettings { SerializerSettings = newtonsoftSettings }, mvcOptions.Value); - } + } else if (systemTextJsonOptions != null) { settings.ApplySettings(new SystemTextJsonSchemaGeneratorSettings { SerializerOptions = systemTextJsonOptions }, mvcOptions.Value); diff --git a/src/NSwag.AspNetCore/Extensions/NSwagSwaggerGeneratorSettingsExtensions.cs b/src/NSwag.AspNetCore/Extensions/NSwagSwaggerGeneratorSettingsExtensions.cs index 1d0f66717d..415be0f656 100644 --- a/src/NSwag.AspNetCore/Extensions/NSwagSwaggerGeneratorSettingsExtensions.cs +++ b/src/NSwag.AspNetCore/Extensions/NSwagSwaggerGeneratorSettingsExtensions.cs @@ -9,7 +9,6 @@ using NSwag; using NSwag.Generation; using NSwag.Generation.Processors.Security; -using System.Collections.Generic; namespace Microsoft.Extensions.DependencyInjection { diff --git a/src/NSwag.AspNetCore/HttpRequestExtension.cs b/src/NSwag.AspNetCore/HttpRequestExtension.cs index 684a3bc40c..7099430f5c 100644 --- a/src/NSwag.AspNetCore/HttpRequestExtension.cs +++ b/src/NSwag.AspNetCore/HttpRequestExtension.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Linq; #if AspNetOwin using Microsoft.Owin; diff --git a/src/NSwag.AspNetCore/IDocumentProvider.cs b/src/NSwag.AspNetCore/IDocumentProvider.cs index 145b807b5d..07bf6ff02c 100644 --- a/src/NSwag.AspNetCore/IDocumentProvider.cs +++ b/src/NSwag.AspNetCore/IDocumentProvider.cs @@ -6,10 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; - namespace Microsoft.Extensions.ApiDescriptions { // This service will be looked up by name from the service collection when using diff --git a/src/NSwag.AspNetCore/JsonExceptionFilterAttribute.cs b/src/NSwag.AspNetCore/JsonExceptionFilterAttribute.cs index 27ac4355ca..c6e959b54d 100644 --- a/src/NSwag.AspNetCore/JsonExceptionFilterAttribute.cs +++ b/src/NSwag.AspNetCore/JsonExceptionFilterAttribute.cs @@ -6,15 +6,11 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Filters; using Newtonsoft.Json; -using NJsonSchema.Converters; using NJsonSchema.NewtonsoftJson.Converters; using NSwag.Annotations; using NSwag.Generation.AspNetCore; @@ -26,7 +22,7 @@ public class JsonExceptionFilterAttribute : ActionFilterAttribute { private readonly bool _hideStackTrace; private readonly IDictionary _searchedNamespaces; - private readonly List _exceptionTypes = new List(); + private readonly List _exceptionTypes = []; /// Initializes a new instance of the class. /// The serialized exception types. @@ -82,7 +78,7 @@ public override void OnActionExecuted(ActionExecutedContext context) } } - private int GetStatusCode(Exception exception, ActionExecutedContext context) + private static int GetStatusCode(Exception exception, ActionExecutedContext context) { if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor) { @@ -116,7 +112,7 @@ private int GetStatusCode(Exception exception, ActionExecutedContext context) return 500; } - private JsonSerializerSettings CopySettings(JsonSerializerSettings settings) + private static JsonSerializerSettings CopySettings(JsonSerializerSettings settings) { var settingsCopy = new JsonSerializerSettings(); diff --git a/src/NSwag.AspNetCore/Middlewares/OpenApiDocumentMiddleware.cs b/src/NSwag.AspNetCore/Middlewares/OpenApiDocumentMiddleware.cs index 4f1f837f75..875fa0788e 100644 --- a/src/NSwag.AspNetCore/Middlewares/OpenApiDocumentMiddleware.cs +++ b/src/NSwag.AspNetCore/Middlewares/OpenApiDocumentMiddleware.cs @@ -10,11 +10,7 @@ using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.Extensions.DependencyInjection; using Namotion.Reflection; -using System; -using System.Collections.Generic; using System.Runtime.ExceptionServices; -using System.Threading; -using System.Threading.Tasks; namespace NSwag.AspNetCore.Middlewares { @@ -30,8 +26,7 @@ public class OpenApiDocumentMiddleware private int _version; private readonly object _documentsCacheLock = new object(); - private readonly Dictionary> _documentsCache - = new Dictionary>(); + private readonly Dictionary> _documentsCache = []; /// Initializes a new instance of the class. /// The next delegate. @@ -44,7 +39,7 @@ public OpenApiDocumentMiddleware(RequestDelegate nextDelegate, IServiceProvider _nextDelegate = nextDelegate; _documentName = documentName; - _path = path.StartsWith("/") ? path : '/' + path; + _path = path.StartsWith('/') ? path : '/' + path; _apiDescriptionGroupCollectionProvider = serviceProvider.GetService() ?? throw new InvalidOperationException("API Explorer not registered in DI."); @@ -63,7 +58,7 @@ public async Task Invoke(HttpContext context) { var schemaJson = await GetDocumentAsync(context); context.Response.StatusCode = 200; - context.Response.Headers["Content-Type"] = _path.IndexOf(".yaml", StringComparison.OrdinalIgnoreCase) >= 0 ? + context.Response.Headers["Content-Type"] = _path.Contains(".yaml", StringComparison.OrdinalIgnoreCase) ? "application/yaml; charset=utf-8" : "application/json; charset=utf-8"; @@ -104,7 +99,7 @@ protected virtual async Task GetDocumentAsync(HttpContext context) try { var openApiDocument = await GenerateDocumentAsync(context); - var data = _path.IndexOf(".yaml", StringComparison.OrdinalIgnoreCase) >= 0 ? + var data = _path.Contains(".yaml", StringComparison.OrdinalIgnoreCase) ? OpenApiYamlDocument.ToYaml(openApiDocument) : openApiDocument.ToJson(); diff --git a/src/NSwag.AspNetCore/Middlewares/RedirectToIndexMiddleware.cs b/src/NSwag.AspNetCore/Middlewares/RedirectToIndexMiddleware.cs index 28136dbc6c..182c9b6e40 100644 --- a/src/NSwag.AspNetCore/Middlewares/RedirectToIndexMiddleware.cs +++ b/src/NSwag.AspNetCore/Middlewares/RedirectToIndexMiddleware.cs @@ -6,13 +6,11 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace NSwag.AspNetCore.Middlewares { - internal class RedirectToIndexMiddleware + internal sealed class RedirectToIndexMiddleware { private readonly RequestDelegate _nextDelegate; diff --git a/src/NSwag.AspNetCore/Middlewares/SwaggerUiIndexMiddleware.cs b/src/NSwag.AspNetCore/Middlewares/SwaggerUiIndexMiddleware.cs index 2889168a43..2d0e057d46 100644 --- a/src/NSwag.AspNetCore/Middlewares/SwaggerUiIndexMiddleware.cs +++ b/src/NSwag.AspNetCore/Middlewares/SwaggerUiIndexMiddleware.cs @@ -1,12 +1,9 @@ -using System; -using System.IO; using System.Reflection; -using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace NSwag.AspNetCore.Middlewares { - internal class SwaggerUiIndexMiddleware + internal sealed class SwaggerUiIndexMiddleware { private readonly RequestDelegate _nextDelegate; private readonly string _indexPath; @@ -26,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.AspNetCore/NSwag.AspNetCore.csproj b/src/NSwag.AspNetCore/NSwag.AspNetCore.csproj index b89c21a616..9958b22194 100644 --- a/src/NSwag.AspNetCore/NSwag.AspNetCore.csproj +++ b/src/NSwag.AspNetCore/NSwag.AspNetCore.csproj @@ -1,6 +1,6 @@  - net462;netstandard2.0;net6.0;net8.0 + net462;netstandard2.0;net8.0;net9.0 Swagger Documentation AspNetCore NetCore TypeScript CodeGen $(MSBuildProjectName).nuspec symbols.nupkg @@ -14,12 +14,8 @@ 1.0.4 6.0.3 1.0.1 - 3.1.0 - 5.0.0 - 6.0.0 - 7.0.0 8.0.0 - 1.6.1 + 9.0.0 4.3.0 4.0.1 @@ -42,22 +38,26 @@ - - - - - + + + + + + + + + @@ -72,12 +72,8 @@ microsoftAspNetCoreStaticFilesPackageVersion=$(MicrosoftAspNetCoreStaticFilesPackageVersion); microsoftExtensionsApiDescriptionServerPackageVersion=$(MicrosoftExtensionsApiDescriptionServerPackageVersion); microsoftExtensionsFileProvidersEmbeddedPackageVersion=$(MicrosoftExtensionsFileProvidersEmbeddedPackageVersion); - microsoftExtensionsFileProvidersEmbeddedPackageVersionCore31=$(MicrosoftExtensionsFileProvidersEmbeddedPackageVersionCore31); - microsoftExtensionsFileProvidersEmbeddedPackageVersionNet5=$(MicrosoftExtensionsFileProvidersEmbeddedPackageVersionNet5); - microsoftExtensionsFileProvidersEmbeddedPackageVersionNet6=$(MicrosoftExtensionsFileProvidersEmbeddedPackageVersionNet6); - microsoftExtensionsFileProvidersEmbeddedPackageVersionNet7=$(MicrosoftExtensionsFileProvidersEmbeddedPackageVersionNet7); microsoftExtensionsFileProvidersEmbeddedPackageVersionNet8=$(MicrosoftExtensionsFileProvidersEmbeddedPackageVersionNet8); - netStandardLibraryPackageVersion=$(NETStandardLibraryPackageVersion); + microsoftExtensionsFileProvidersEmbeddedPackageVersionNet9=$(MicrosoftExtensionsFileProvidersEmbeddedPackageVersionNet9); systemIOFileSystemPackageVersion=$(SystemIOFileSystemPackageVersion); systemXmlXPathXDocumentPackageVersion=$(SystemXmlXPathXDocumentPackageVersion); diff --git a/src/NSwag.AspNetCore/NSwag.AspNetCore.nuspec b/src/NSwag.AspNetCore/NSwag.AspNetCore.nuspec index e43c66929c..da5b8d625f 100644 --- a/src/NSwag.AspNetCore/NSwag.AspNetCore.nuspec +++ b/src/NSwag.AspNetCore/NSwag.AspNetCore.nuspec @@ -37,23 +37,23 @@ - + - + - + - + @@ -65,9 +65,9 @@ - - + + diff --git a/src/NSwag.AspNetCore/OAuth2ClientSettings.cs b/src/NSwag.AspNetCore/OAuth2ClientSettings.cs index 9057534757..95dc59da24 100644 --- a/src/NSwag.AspNetCore/OAuth2ClientSettings.cs +++ b/src/NSwag.AspNetCore/OAuth2ClientSettings.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; - #if AspNetOwin namespace NSwag.AspNet.Owin #else @@ -33,7 +31,7 @@ public class OAuth2ClientSettings public string ScopeSeparator { get; set; } = " "; /// Gets or sets initially selected scopes. - public ICollection Scopes { get; } = new List(); + public ICollection Scopes { get; } = []; /// Gets or sets the additional query string parameters. public IDictionary AdditionalQueryStringParameters { get; } = new Dictionary(); diff --git a/src/NSwag.AspNetCore/OpenApiConfigureMvcOptions.cs b/src/NSwag.AspNetCore/OpenApiConfigureMvcOptions.cs index 76c8f17940..fc8ab7c231 100644 --- a/src/NSwag.AspNetCore/OpenApiConfigureMvcOptions.cs +++ b/src/NSwag.AspNetCore/OpenApiConfigureMvcOptions.cs @@ -11,7 +11,7 @@ namespace NSwag.AspNetCore { - internal class OpenApiConfigureMvcOptions : ConfigureOptions + internal sealed class OpenApiConfigureMvcOptions : ConfigureOptions { public OpenApiConfigureMvcOptions() : base(options => options.Conventions.Add(new OpenApiMvcApplicationModelConvention())) diff --git a/src/NSwag.AspNetCore/OpenApiDocumentMiddlewareSettings.cs b/src/NSwag.AspNetCore/OpenApiDocumentMiddlewareSettings.cs index 024774fc06..0a79ab593c 100644 --- a/src/NSwag.AspNetCore/OpenApiDocumentMiddlewareSettings.cs +++ b/src/NSwag.AspNetCore/OpenApiDocumentMiddlewareSettings.cs @@ -7,7 +7,6 @@ //----------------------------------------------------------------------- using Microsoft.AspNetCore.Http; -using System; namespace NSwag.AspNetCore { diff --git a/src/NSwag.AspNetCore/OpenApiDocumentProvider.cs b/src/NSwag.AspNetCore/OpenApiDocumentProvider.cs index 2c2585a579..07465a28a2 100644 --- a/src/NSwag.AspNetCore/OpenApiDocumentProvider.cs +++ b/src/NSwag.AspNetCore/OpenApiDocumentProvider.cs @@ -6,11 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; using Microsoft.Extensions.ApiDescriptions; using Microsoft.Extensions.DependencyInjection; using NSwag.Generation; @@ -18,7 +13,7 @@ namespace NSwag.AspNetCore { - internal class OpenApiDocumentProvider : IDocumentProvider, IOpenApiDocumentGenerator + internal sealed class OpenApiDocumentProvider : IDocumentProvider, IOpenApiDocumentGenerator { private readonly IServiceProvider _serviceProvider; private readonly IEnumerable _documents; diff --git a/src/NSwag.AspNetCore/OpenApiMvcApplicationModelConvention.cs b/src/NSwag.AspNetCore/OpenApiMvcApplicationModelConvention.cs index 2b131b5dce..8176f86089 100644 --- a/src/NSwag.AspNetCore/OpenApiMvcApplicationModelConvention.cs +++ b/src/NSwag.AspNetCore/OpenApiMvcApplicationModelConvention.cs @@ -2,7 +2,7 @@ namespace NSwag.AspNetCore { - internal class OpenApiMvcApplicationModelConvention : IApplicationModelConvention + internal sealed class OpenApiMvcApplicationModelConvention : IApplicationModelConvention { public void Apply(ApplicationModel application) { diff --git a/src/NSwag.AspNetCore/ReDocSettings.cs b/src/NSwag.AspNetCore/ReDocSettings.cs index 78d541c162..cf3da91d8d 100644 --- a/src/NSwag.AspNetCore/ReDocSettings.cs +++ b/src/NSwag.AspNetCore/ReDocSettings.cs @@ -6,10 +6,10 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- +#pragma warning disable IDE0005 + using NSwag.Generation; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Threading; + #if AspNetOwin using Microsoft.Owin; diff --git a/src/NSwag.AspNetCore/SwaggerSettings.cs b/src/NSwag.AspNetCore/SwaggerSettings.cs index f3d41a7b2e..a21513ee3e 100644 --- a/src/NSwag.AspNetCore/SwaggerSettings.cs +++ b/src/NSwag.AspNetCore/SwaggerSettings.cs @@ -6,14 +6,11 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using Newtonsoft.Json; +#pragma warning disable IDE0005 + using NSwag.Generation; #if AspNetOwin -using NSwag.Generation.WebApi; -using Microsoft.Owin; - namespace NSwag.AspNet.Owin #else namespace NSwag.AspNetCore diff --git a/src/NSwag.AspNetCore/SwaggerUi/index.html b/src/NSwag.AspNetCore/SwaggerUi/index.html index 1e23b0e15a..ff9a97267d 100644 --- a/src/NSwag.AspNetCore/SwaggerUi/index.html +++ b/src/NSwag.AspNetCore/SwaggerUi/index.html @@ -27,26 +27,10 @@ } var urls = {Urls}; - const disableTryItOutPlugin = function() { - return { - statePlugins: { - spec: { - wrapSelectors: { - allowTryItOutFor: function() { - return function() { - return {EnableTryItOut}; - } - } - } - } - } - } - } - // Build a system var ui = SwaggerUIBundle({ url: url, - urls: urls, + urls: urls, validatorUrl: {ValidatorUrl}, oauth2RedirectUrl: {RedirectUrl}, @@ -58,8 +42,7 @@ SwaggerUIStandalonePreset ], plugins: [ - SwaggerUIBundle.plugins.DownloadUrl, - disableTryItOutPlugin + SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout" }); diff --git a/src/NSwag.AspNetCore/SwaggerUiSettings.cs b/src/NSwag.AspNetCore/SwaggerUiSettings.cs index ee51dbaad5..663ff302db 100644 --- a/src/NSwag.AspNetCore/SwaggerUiSettings.cs +++ b/src/NSwag.AspNetCore/SwaggerUiSettings.cs @@ -6,17 +6,13 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; +#pragma warning disable IDE0005 + using System.Collections; -using System.Collections.Generic; -using System.Linq; using System.Reflection; using System.Text; using Newtonsoft.Json; using NSwag.Generation; -using NJsonSchema; -using System.Threading; -using System.Threading.Tasks; #if AspNetOwin using Microsoft.Owin; @@ -53,7 +49,11 @@ public SwaggerUiSettings() public string ServerUrl { get; set; } = ""; /// Specifies whether the "Try it out" option is enabled in Swagger UI 3. - public bool EnableTryItOut { get; set; } = true; + public bool EnableTryItOut + { + get => (bool)AdditionalSettings["tryItOutEnabled"]; + set => AdditionalSettings["tryItOutEnabled"] = value; + } /// /// Gets or sets a title for the Swagger UI page. @@ -66,7 +66,7 @@ public SwaggerUiSettings() public string CustomHeadContent { get; set; } = ""; /// Gets or sets a value indicating whether the Swagger specification should be validated. - public bool ValidateSpecification { get; set; } = false; + public bool ValidateSpecification { get; set; } /// Gets the additional Swagger UI 3 settings. public IDictionary AdditionalSettings { get; } = new Dictionary(); @@ -121,7 +121,7 @@ public bool WithCredentials } /// Gets or sets the Swagger URL routes (must start with '/', hides SwaggerRoute). - public ICollection SwaggerRoutes { get; } = new List(); + public ICollection SwaggerRoutes { get; } = []; /// Gets or sets the Swagger URL routes factory (SwaggerRoutes is ignored when set). #if AspNetOwin @@ -130,7 +130,7 @@ public bool WithCredentials public Func>> SwaggerRoutesFactory { get; set; } #endif - internal override string ActualSwaggerDocumentPath => SwaggerRoutes.Any() ? "" : base.ActualSwaggerDocumentPath; + internal override string ActualSwaggerDocumentPath => SwaggerRoutes.Count > 0 ? "" : base.ActualSwaggerDocumentPath; #if AspNetOwin internal override async Task TransformHtmlAsync(string html, IOwinRequest request, CancellationToken cancellationToken) @@ -157,11 +157,11 @@ internal override async Task TransformHtmlAsync(string html, HttpRequest } } - var swaggerRoutes = SwaggerRoutesFactory != null ? - (await SwaggerRoutesFactory(request, cancellationToken)).ToList() : + var swaggerRoutes = SwaggerRoutesFactory != null ? + (await SwaggerRoutesFactory(request, cancellationToken)).ToList() : SwaggerRoutes; - htmlBuilder.Replace("{Urls}", !swaggerRoutes.Any() + htmlBuilder.Replace("{Urls}", swaggerRoutes.Count == 0 ? "undefined" : JsonConvert.SerializeObject( #pragma warning disable 618 @@ -172,7 +172,6 @@ internal override async Task TransformHtmlAsync(string html, HttpRequest htmlBuilder.Replace("{ValidatorUrl}", ValidateSpecification ? "undefined" : "null") .Replace("{AdditionalSettings}", GenerateAdditionalSettings(AdditionalSettings)) - .Replace("{EnableTryItOut}", EnableTryItOut.ToString().ToLower()) .Replace("{RedirectUrl}", string.IsNullOrEmpty(ServerUrl) ? "window.location.origin + \"" + TransformToExternalPath(Path, request) + diff --git a/src/NSwag.AspNetCore/SwaggerUiSettingsBase.cs b/src/NSwag.AspNetCore/SwaggerUiSettingsBase.cs index ee5df125bd..721ab22cf0 100644 --- a/src/NSwag.AspNetCore/SwaggerUiSettingsBase.cs +++ b/src/NSwag.AspNetCore/SwaggerUiSettingsBase.cs @@ -6,16 +6,13 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- +#pragma warning disable IDE0005 +#pragma warning disable CA1305 + using NSwag.Generation; -using System; -using System.Collections.Generic; -using NJsonSchema; -using System.Globalization; using Newtonsoft.Json; -using System.Linq; using System.Text; -using System.Threading.Tasks; -using System.Threading; + #if AspNetOwin using Microsoft.Owin; @@ -122,7 +119,7 @@ protected string GetCustomScriptHtml(HttpRequest request) /// Generates the additional objects JavaScript code. /// The additional settings. /// The code. - protected string GenerateAdditionalSettings(IDictionary additionalSettings) + protected static string GenerateAdditionalSettings(IDictionary additionalSettings) { var code = ""; foreach (var pair in additionalSettings) diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/AllowNullableBodyParametersTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/AllowNullableBodyParametersTests.cs index 8ca3104191..107c951414 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/AllowNullableBodyParametersTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/AllowNullableBodyParametersTests.cs @@ -1,10 +1,8 @@ using Microsoft.AspNetCore.Mvc; -using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.CodeGeneration.OperationNameGenerators; using NSwag.Generation.WebApi; using System.ComponentModel.DataAnnotations; -using System.Threading.Tasks; using Xunit; namespace NSwag.CodeGeneration.CSharp.Tests diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/ArrayParameterTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/ArrayParameterTests.cs index 551ed0b71e..50fef82b6b 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/ArrayParameterTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/ArrayParameterTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.CodeGeneration.CSharp.Tests { @@ -68,7 +67,7 @@ public async Task When_parameter_is_array_then_CSharp_is_correct() // Assert Assert.Contains(@"foreach (var item_ in elementId) { urlBuilder_.Append(System.Uri.EscapeDataString(""elementId"")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(item_, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); }", code); } - + [Fact] public async Task when_content_is_formdata_with_property_array_then_content_should_be_added_in_foreach_in_csharp() { diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/BinaryTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/BinaryTests.cs index 1f5a83cc33..38082ce849 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/BinaryTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/BinaryTests.cs @@ -1,5 +1,4 @@ using NSwag.CodeGeneration.CSharp.Models; -using System.Threading.Tasks; using Xunit; namespace NSwag.CodeGeneration.CSharp.Tests diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/CSharpClientSettingsTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/CSharpClientSettingsTests.cs index 05350c01f2..20cb289665 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/CSharpClientSettingsTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/CSharpClientSettingsTests.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; -using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.WebApi; using Xunit; @@ -49,7 +47,7 @@ public async Task When_UseHttpRequestMessageCreationMethod_is_set_then_CreateReq { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings() }); - + var document = await swaggerGenerator.GenerateForControllerAsync(); var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings { @@ -97,7 +95,7 @@ public async Task When_parameter_name_is_reserved_keyword_then_it_is_appended_wi { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings() }); - + var document = await swaggerGenerator.GenerateForControllerAsync(); var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings()); @@ -116,7 +114,7 @@ public async Task When_code_is_generated_then_by_default_the_system_httpclient_i { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings() }); - + var document = await swaggerGenerator.GenerateForControllerAsync(); var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings { @@ -214,7 +212,7 @@ public async Task When_client_class_generation_is_enabled_and_suppressed_then_cl SuppressClientClassesOutput = true, GenerateClientInterfaces = true, // SuppressClientInterfacesOutput = false, // default - }); + }); // Act var code = generator.GenerateFile(); @@ -240,7 +238,7 @@ public async Task When_client_interface_generation_is_enabled_and_suppressed_the // SuppressClientClassesOutput = false, // default GenerateClientInterfaces = true, SuppressClientInterfacesOutput = true, - }); + }); // Act var code = generator.GenerateFile(); diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/ControllerGenerationFormatTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/ControllerGenerationFormatTests.cs index 9e59d42f77..f4f5fb396f 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/ControllerGenerationFormatTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/ControllerGenerationFormatTests.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using System.Text.RegularExpressions; +using System.Text.RegularExpressions; using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.CodeGeneration.CSharp.Models; @@ -252,7 +251,7 @@ public void When_the_generation_of_dto_classes_are_disabled_then_file_is_generat Assert.DoesNotContain("public partial class ComplexTypeResponse", code); } - private OpenApiDocument GetOpenApiDocument() + private static OpenApiDocument GetOpenApiDocument() { JsonSchema complexTypeSchema = new JsonSchema(); complexTypeSchema.Title = "ComplexType"; @@ -374,7 +373,7 @@ private OpenApiDocument GetOpenApiDocument() Type = JsonObjectType.String } }, - Tags = new List { "Secondary" } + Tags = ["Secondary"] } } }; diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/Controllers/ControllerGenerationBasePathTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/Controllers/ControllerGenerationBasePathTests.cs index 773f2dc142..ab1eae526e 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/Controllers/ControllerGenerationBasePathTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/Controllers/ControllerGenerationBasePathTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.CodeGeneration.CSharp.Tests { diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/Controllers/ControllerGenerationDefaultParameterTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/Controllers/ControllerGenerationDefaultParameterTests.cs index da87de9850..dca494a010 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/Controllers/ControllerGenerationDefaultParameterTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/Controllers/ControllerGenerationDefaultParameterTests.cs @@ -82,6 +82,7 @@ public void When_parameter_has_default_then_set_in_partial_controller() Assert.Contains("BarAsync(int abc, bool booldef, int intdef, double doubledef, decimal decdef, string strdef, int? bar = null);", code); var trimmedCode = RemoveExternalReferences(code); + Assert.NotNull(trimmedCode); //CompilerParameters parameters = new CompilerParameters { GenerateInMemory = true }; diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/FileDownloadTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/FileDownloadTests.cs index 324b269fd9..270623e999 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/FileDownloadTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/FileDownloadTests.cs @@ -1,8 +1,4 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using NJsonSchema.Generation; +using Microsoft.AspNetCore.Mvc; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.WebApi; using Xunit; diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/FileTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/FileTests.cs index 995ccbaf09..b23402c688 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/FileTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/FileTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.WebApi; using Xunit; diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/FileUploadTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/FileUploadTests.cs index 3f3984439e..036991f4ce 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/FileUploadTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/FileUploadTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using Xunit; namespace NSwag.CodeGeneration.CSharp.Tests diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/FormParameterTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/FormParameterTests.cs index 8371e7d897..7214b376bc 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/FormParameterTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/FormParameterTests.cs @@ -1,7 +1,5 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using NJsonSchema; -using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.WebApi; using Xunit; @@ -97,7 +95,7 @@ public void When_form_parameters_are_defined_then_FormUrlEncodedContent_is_gener OpenApiOperationMethod.Post, new OpenApiOperation { - Consumes = new System.Collections.Generic.List { "application/x-www-form-urlencoded" }, + Consumes = ["application/x-www-form-urlencoded"], Parameters = { new OpenApiParameter diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/HeadRequestTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/HeadRequestTests.cs index d379acd004..abbd90576f 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/HeadRequestTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/HeadRequestTests.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using NJsonSchema.Generation; +using Microsoft.AspNetCore.Mvc; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.WebApi; using Xunit; diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/InheritanceTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/InheritanceTests.cs index 565dead490..979b5cab6a 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/InheritanceTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/InheritanceTests.cs @@ -1,5 +1,4 @@ using NSwag.CodeGeneration.CSharp; -using System.Threading.Tasks; using Xunit; namespace NSwag.CodeGeneration.TypeScript.Tests diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/NSwag.CodeGeneration.CSharp.Tests.csproj b/src/NSwag.CodeGeneration.CSharp.Tests/NSwag.CodeGeneration.CSharp.Tests.csproj index 49929d0cfa..370fc24056 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/NSwag.CodeGeneration.CSharp.Tests.csproj +++ b/src/NSwag.CodeGeneration.CSharp.Tests/NSwag.CodeGeneration.CSharp.Tests.csproj @@ -2,12 +2,17 @@ net8.0 true + $(NoWarn);CA1707;IDE1006 + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/ObjectParameterTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/ObjectParameterTests.cs index fab28efccd..6b2edcdd2d 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/ObjectParameterTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/ObjectParameterTests.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using Xunit; namespace NSwag.CodeGeneration.CSharp.Tests diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/OptionalParameterTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/OptionalParameterTests.cs index ad61258823..99386876d3 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/OptionalParameterTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/OptionalParameterTests.cs @@ -1,9 +1,5 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using NJsonSchema; -using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.WebApi; using Xunit; @@ -30,9 +26,12 @@ public void TestWithEnum([FromUri] MyEnum? myEnum = null) } } - public class FromUriAttribute : Attribute { } + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter)] + public class FromUriAttribute : Attribute; +#pragma warning disable CA1711 public enum MyEnum +#pragma warning restore CA1711 { One, Two, @@ -42,7 +41,9 @@ public enum MyEnum } public class MyClass { +#pragma warning disable IDE0051 private string MyString { get; set; } +#pragma warning restore IDE0051 public MyEnum? MyEnum { get; set; } public int MyInt { get; set; } } @@ -133,6 +134,7 @@ public async Task When_setting_is_enabled_then_parameters_are_reordered() operation.Parameters.Remove(lastParameter); operation.Parameters.Insert(0, lastParameter); var json = document.ToJson(); + Assert.NotNull(json); var codeGenerator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings { diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/ParameterTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/ParameterTests.cs index e6796f5b74..229f303aef 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/ParameterTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/ParameterTests.cs @@ -1,5 +1,4 @@ -using System; -using NJsonSchema; +using NJsonSchema; using Xunit; namespace NSwag.CodeGeneration.CSharp.Tests @@ -77,7 +76,7 @@ public void When_parameters_names_have_differences_only_in_case_of_the_first_let } [Fact] - public void When_parent_parameters_have_same_kind_then_they_are_included() + public async Task When_parent_parameters_have_same_kind_then_they_are_included() { // Arrange var swagger = @"{ @@ -140,7 +139,7 @@ public void When_parent_parameters_have_same_kind_then_they_are_included() ""definitions"" : { } } "; - var document = OpenApiDocument.FromJsonAsync(swagger).Result; + var document = await OpenApiDocument.FromJsonAsync(swagger); // Act var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings()); @@ -151,7 +150,7 @@ public void When_parent_parameters_have_same_kind_then_they_are_included() } [Fact] - public void When_swagger_contains_optional_parameters_then_they_are_rendered_in_CSharp() + public async Task When_swagger_contains_optional_parameters_then_they_are_rendered_in_CSharp() { // Arrange var swagger = @"{ @@ -222,7 +221,7 @@ public void When_swagger_contains_optional_parameters_then_they_are_rendered_in_ } }"; - var document = OpenApiDocument.FromJsonAsync(swagger).Result; + var document = await OpenApiDocument.FromJsonAsync(swagger); // Act var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings()); @@ -234,7 +233,7 @@ public void When_swagger_contains_optional_parameters_then_they_are_rendered_in_ } [Fact] - public void Deep_object_properties_are_correctly_named() + public async Task Deep_object_properties_are_correctly_named() { // Arrange var swagger = @"{ @@ -298,7 +297,7 @@ public void Deep_object_properties_are_correctly_named() } }"; - var document = OpenApiDocument.FromJsonAsync(swagger, "", SchemaType.OpenApi3).Result; + var document = await OpenApiDocument.FromJsonAsync(swagger, "", SchemaType.OpenApi3); // Act var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings()); @@ -310,7 +309,7 @@ public void Deep_object_properties_are_correctly_named() } [Fact] - public void Date_and_DateTimeFormat_Parameters_are_correctly_applied() + public async Task Date_and_DateTimeFormat_Parameters_are_correctly_applied() { // Arrange var swagger = @"{ @@ -356,7 +355,7 @@ public void Date_and_DateTimeFormat_Parameters_are_correctly_applied() } }"; - var document = OpenApiDocument.FromJsonAsync(swagger, "", SchemaType.OpenApi3).Result; + var document = await OpenApiDocument.FromJsonAsync(swagger, "", SchemaType.OpenApi3); // Act once with defaults and once with custom values var generatorDefault = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings()); diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/PlainResponseTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/PlainResponseTests.cs index d73b3c6c71..2e997f979b 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/PlainResponseTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/PlainResponseTests.cs @@ -1,9 +1,4 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using NSwag.Generation.WebApi; -using Xunit; +using Xunit; namespace NSwag.CodeGeneration.CSharp.Tests { diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/PlainTextBodyTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/PlainTextBodyTests.cs index 7c489c6bdb..bb5ff04312 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/PlainTextBodyTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/PlainTextBodyTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.CodeGeneration.CSharp.Tests { diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/QueryParameterTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/QueryParameterTests.cs index d516ce4d1a..50d3ec5d11 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/QueryParameterTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/QueryParameterTests.cs @@ -5,7 +5,7 @@ namespace NSwag.CodeGeneration.CSharp.Tests public class QueryParameterTests { [Fact] - public void When_query_parameter_is_set_to_explode_and_style_is_form_object_parameters_are_expanded() + public async Task When_query_parameter_is_set_to_explode_and_style_is_form_object_parameters_are_expanded() { var spec = @"{ ""openapi"": ""3.0.0"", @@ -64,7 +64,7 @@ public void When_query_parameter_is_set_to_explode_and_style_is_form_object_para } "; - var document = OpenApiDocument.FromJsonAsync(spec).Result; + var document = await OpenApiDocument.FromJsonAsync(spec); // Act var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings()); @@ -80,7 +80,7 @@ public void When_query_parameter_is_set_to_explode_and_style_is_form_object_para } [Fact] - public void When_query_parameter_is_untyped_free_form_object_parameters_are_expanded() + public async Task When_query_parameter_is_untyped_free_form_object_parameters_are_expanded() { var spec = @"{ ""openapi"": ""3.0.0"", @@ -130,7 +130,7 @@ public void When_query_parameter_is_untyped_free_form_object_parameters_are_expa } "; - var document = OpenApiDocument.FromJsonAsync(spec).Result; + var document = await OpenApiDocument.FromJsonAsync(spec); // Act var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings()); @@ -146,7 +146,7 @@ public void When_query_parameter_is_untyped_free_form_object_parameters_are_expa } [Fact] - public void When_query_parameter_is_typed_free_form_object_parameters_are_expanded() + public async Task When_query_parameter_is_typed_free_form_object_parameters_are_expanded() { var spec = @"{ ""openapi"": ""3.0.0"", @@ -198,7 +198,7 @@ public void When_query_parameter_is_typed_free_form_object_parameters_are_expand } "; - var document = OpenApiDocument.FromJsonAsync(spec).Result; + var document = await OpenApiDocument.FromJsonAsync(spec); // Act var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings()); @@ -214,7 +214,7 @@ public void When_query_parameter_is_typed_free_form_object_parameters_are_expand } [Fact] - public void When_query_parameter_is_mixed_free_form_object_parameters_are_expanded() + public async Task When_query_parameter_is_mixed_free_form_object_parameters_are_expanded() { var spec = @"{ ""openapi"": ""3.0.0"", @@ -281,7 +281,7 @@ public void When_query_parameter_is_mixed_free_form_object_parameters_are_expand } "; - var document = OpenApiDocument.FromJsonAsync(spec).Result; + var document = await OpenApiDocument.FromJsonAsync(spec); // Act var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings()); diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/ResponseTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/ResponseTests.cs index b460c002bb..b6c9eeba56 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/ResponseTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/ResponseTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.CodeGeneration.CSharp.Tests { diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/UseCancellationTokenTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/UseCancellationTokenTests.cs index 43b334a792..4ee370e2e7 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/UseCancellationTokenTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/UseCancellationTokenTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using NJsonSchema.Generation; +using Microsoft.AspNetCore.Mvc; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.CodeGeneration.CSharp.Models; using NSwag.Generation.WebApi; diff --git a/src/NSwag.CodeGeneration.CSharp.Tests/WrapResponsesTests.cs b/src/NSwag.CodeGeneration.CSharp.Tests/WrapResponsesTests.cs index f2fe7a81ce..28feb6d709 100644 --- a/src/NSwag.CodeGeneration.CSharp.Tests/WrapResponsesTests.cs +++ b/src/NSwag.CodeGeneration.CSharp.Tests/WrapResponsesTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; -using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.WebApi; using Xunit; @@ -63,7 +60,7 @@ public async Task When_success_responses_are_wrapped_then_SwaggerResponse_is_ret WrapResponses = true }); var code = codeGen.GenerateFile(); - + // Assert Assert.Contains("Task>", code); Assert.Contains("Task", code); @@ -84,7 +81,6 @@ public async Task When_success_responses_are_wrapped_then_SwaggerResponse_is_ret var codeGen = new CSharpControllerGenerator(document, new CSharpControllerGeneratorSettings { WrapResponses = true, - }); var code = codeGen.GenerateFile(); diff --git a/src/NSwag.CodeGeneration.CSharp/CSharpClientGenerator.cs b/src/NSwag.CodeGeneration.CSharp/CSharpClientGenerator.cs index 0c505dc79e..58f421018c 100644 --- a/src/NSwag.CodeGeneration.CSharp/CSharpClientGenerator.cs +++ b/src/NSwag.CodeGeneration.CSharp/CSharpClientGenerator.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; using NJsonSchema.CodeGeneration; using NJsonSchema.CodeGeneration.CSharp; using NSwag.CodeGeneration.CSharp.Models; diff --git a/src/NSwag.CodeGeneration.CSharp/CSharpClientGeneratorSettings.cs b/src/NSwag.CodeGeneration.CSharp/CSharpClientGeneratorSettings.cs index efe684aa93..0123694caf 100644 --- a/src/NSwag.CodeGeneration.CSharp/CSharpClientGeneratorSettings.cs +++ b/src/NSwag.CodeGeneration.CSharp/CSharpClientGeneratorSettings.cs @@ -31,7 +31,7 @@ public CSharpClientGeneratorSettings() GenerateBaseUrlProperty = true; ExposeJsonSerializerSettings = false; InjectHttpClient = true; - ProtectedMethods = new string[0]; + ProtectedMethods = []; } /// Gets or sets the full name of the base class. diff --git a/src/NSwag.CodeGeneration.CSharp/CSharpControllerGenerator.cs b/src/NSwag.CodeGeneration.CSharp/CSharpControllerGenerator.cs index 7074ba084a..8d965ca59e 100644 --- a/src/NSwag.CodeGeneration.CSharp/CSharpControllerGenerator.cs +++ b/src/NSwag.CodeGeneration.CSharp/CSharpControllerGenerator.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using NJsonSchema.CodeGeneration; using NJsonSchema.CodeGeneration.CSharp; using NSwag.CodeGeneration.CSharp.Models; @@ -54,7 +51,7 @@ protected override IEnumerable GenerateAllClientTypes() var artifacts = base.GenerateAllClientTypes().ToList(); if (Settings.ControllerTarget == CSharpControllerTarget.AspNet && - _document.Operations.Count(operation => operation.Operation.ActualParameters.Any(p => p.Kind == OpenApiParameterKind.Header)) > 0) + _document.Operations.Any(operation => operation.Operation.ActualParameters.Any(p => p.Kind == OpenApiParameterKind.Header))) { var template = Settings.CodeGeneratorSettings.TemplateFactory.CreateTemplate("CSharp", "Controller.AspNet.FromHeaderAttribute", new object()); artifacts.Add(new CodeArtifact("FromHeaderAttribute", CodeArtifactType.Class, CodeArtifactLanguage.CSharp, CodeArtifactCategory.Utility, template)); diff --git a/src/NSwag.CodeGeneration.CSharp/CSharpGeneratorBase.cs b/src/NSwag.CodeGeneration.CSharp/CSharpGeneratorBase.cs index ce0936007a..54c8431ced 100644 --- a/src/NSwag.CodeGeneration.CSharp/CSharpGeneratorBase.cs +++ b/src/NSwag.CodeGeneration.CSharp/CSharpGeneratorBase.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NJsonSchema.CodeGeneration; using NJsonSchema.CodeGeneration.CSharp; @@ -62,7 +60,7 @@ public override string GetTypeName(JsonSchema schema, bool isNullable, string ty /// FileResponse by default, FileResult if ControllerTarger parameter is AspNetCore public override string GetBinaryResponseTypeName() { - if (_settings is CSharpControllerGeneratorSettings controllerSettings + if (_settings is CSharpControllerGeneratorSettings controllerSettings && controllerSettings.ControllerTarget == CSharpControllerTarget.AspNetCore) { return "FileResult"; @@ -76,7 +74,7 @@ public override string GetBinaryResponseTypeName() /// The document public static CSharpTypeResolver CreateResolverWithExceptionSchema(CSharpGeneratorSettings settings, OpenApiDocument document) { - var exceptionSchema = document.Definitions.ContainsKey("Exception") ? document.Definitions["Exception"] : null; + var exceptionSchema = document.Definitions.TryGetValue("Exception", out JsonSchema value) ? value : null; var resolver = new CSharpTypeResolver(settings, exceptionSchema); resolver.RegisterSchemaDefinitions(document.Definitions diff --git a/src/NSwag.CodeGeneration.CSharp/CSharpGeneratorBaseSettings.cs b/src/NSwag.CodeGeneration.CSharp/CSharpGeneratorBaseSettings.cs index e09ed39910..aede0182a9 100644 --- a/src/NSwag.CodeGeneration.CSharp/CSharpGeneratorBaseSettings.cs +++ b/src/NSwag.CodeGeneration.CSharp/CSharpGeneratorBaseSettings.cs @@ -26,11 +26,10 @@ protected CSharpGeneratorBaseSettings() SchemaType = SchemaType.Swagger2 }; - CSharpGeneratorSettings.TemplateFactory = new DefaultTemplateFactory(CSharpGeneratorSettings, new[] - { + CSharpGeneratorSettings.TemplateFactory = new DefaultTemplateFactory(CSharpGeneratorSettings, [ typeof(CSharpGeneratorSettings).GetTypeInfo().Assembly, - typeof(CSharpGeneratorBaseSettings).GetTypeInfo().Assembly, - }); + typeof(CSharpGeneratorBaseSettings).GetTypeInfo().Assembly + ]); ResponseArrayType = "System.Collections.Generic.ICollection"; ResponseDictionaryType = "System.Collections.Generic.IDictionary"; @@ -38,8 +37,8 @@ protected CSharpGeneratorBaseSettings() ParameterArrayType = "System.Collections.Generic.IEnumerable"; ParameterDictionaryType = "System.Collections.Generic.IDictionary"; - AdditionalNamespaceUsages = new string[0]; - AdditionalContractNamespaceUsages = new string[0]; + AdditionalNamespaceUsages = []; + AdditionalContractNamespaceUsages = []; } /// Gets the CSharp generator settings. diff --git a/src/NSwag.CodeGeneration.CSharp/Models/CSharpClientTemplateModel.cs b/src/NSwag.CodeGeneration.CSharp/Models/CSharpClientTemplateModel.cs index e73787d160..27d4741384 100644 --- a/src/NSwag.CodeGeneration.CSharp/Models/CSharpClientTemplateModel.cs +++ b/src/NSwag.CodeGeneration.CSharp/Models/CSharpClientTemplateModel.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NJsonSchema.CodeGeneration.CSharp; @@ -165,7 +163,7 @@ public string JsonSerializerParameterCode get { var parameterCode = CSharpJsonSerializerGenerator.GenerateJsonSerializerParameterCode( - _settings.CSharpGeneratorSettings, RequiresJsonExceptionConverter ? new[] { "JsonExceptionConverter" } : null); + _settings.CSharpGeneratorSettings, RequiresJsonExceptionConverter ? jsonExceptionConverterArray : null); if (!parameterCode.Contains("new Newtonsoft.Json.JsonSerializerSettings")) { @@ -180,13 +178,7 @@ public string JsonSerializerParameterCode /// Gets the JSON converters array code. public string JsonConvertersArrayCode - { - get - { - return CSharpJsonSerializerGenerator.GenerateJsonConvertersArrayCode( - _settings.CSharpGeneratorSettings, RequiresJsonExceptionConverter ? new[] { "JsonExceptionConverter" } : null); - } - } + => CSharpJsonSerializerGenerator.GenerateJsonConvertersArrayCode(_settings.CSharpGeneratorSettings, RequiresJsonExceptionConverter ? jsonExceptionConverterArray : null); /// Gets the Title. public string Title => _document.Info.Title; @@ -204,5 +196,7 @@ public string JsonConvertersArrayCode _settings.CSharpGeneratorSettings.JsonLibrary == CSharpJsonLibrary.NewtonsoftJson && _settings.CSharpGeneratorSettings.ExcludedTypeNames?.Contains("JsonExceptionConverter") != true && _document.Operations.Any(o => o.Operation.ActualResponses.Any(r => r.Value.Schema?.InheritsSchema(_exceptionSchema) == true)); + + private static readonly string[] jsonExceptionConverterArray = ["JsonExceptionConverter"]; } } \ No newline at end of file diff --git a/src/NSwag.CodeGeneration.CSharp/Models/CSharpControllerTemplateModel.cs b/src/NSwag.CodeGeneration.CSharp/Models/CSharpControllerTemplateModel.cs index 7390cd4a37..8a578ee002 100644 --- a/src/NSwag.CodeGeneration.CSharp/Models/CSharpControllerTemplateModel.cs +++ b/src/NSwag.CodeGeneration.CSharp/Models/CSharpControllerTemplateModel.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; - namespace NSwag.CodeGeneration.CSharp.Models { /// The CSharp controller template model. diff --git a/src/NSwag.CodeGeneration.CSharp/Models/CSharpFileTemplateModel.cs b/src/NSwag.CodeGeneration.CSharp/Models/CSharpFileTemplateModel.cs index 6002400490..0a90a87550 100644 --- a/src/NSwag.CodeGeneration.CSharp/Models/CSharpFileTemplateModel.cs +++ b/src/NSwag.CodeGeneration.CSharp/Models/CSharpFileTemplateModel.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using NJsonSchema.CodeGeneration; using NJsonSchema.CodeGeneration.CSharp; @@ -56,20 +54,16 @@ public CSharpFileTemplateModel( /// Gets the all the namespace usages. public string[] NamespaceUsages => (_outputType == ClientGeneratorOutputType.Contracts ? _settings.AdditionalContractNamespaceUsages?.Where(n => n != null).ToArray() : - _settings.AdditionalNamespaceUsages?.Where(n => n != null).ToArray()) ?? new string[] { }; + _settings.AdditionalNamespaceUsages?.Where(n => n != null).ToArray()) ?? []; /// Gets a value indicating whether the C#8 nullable reference types are enabled for this file. public bool GenerateNullableReferenceTypes => _settings.CSharpGeneratorSettings.GenerateNullableReferenceTypes; /// Gets a value indicating whether to generate contract code. - public bool GenerateContracts => - _outputType == ClientGeneratorOutputType.Full || - _outputType == ClientGeneratorOutputType.Contracts; + public bool GenerateContracts => _outputType is ClientGeneratorOutputType.Full or ClientGeneratorOutputType.Contracts; /// Gets a value indicating whether to generate implementation code. - public bool GenerateImplementation => - _outputType == ClientGeneratorOutputType.Full || - _outputType == ClientGeneratorOutputType.Implementation; + public bool GenerateImplementation => _outputType is ClientGeneratorOutputType.Full or ClientGeneratorOutputType.Implementation; /// Gets or sets a value indicating whether to generate client types. public bool GenerateClientClasses => _settings.GenerateClientClasses; @@ -105,10 +99,10 @@ public CSharpFileTemplateModel( /// Gets a value indicating whether [generate file response class]. public bool GenerateFileResponseClass => _settings.CSharpGeneratorSettings.ExcludedTypeNames?.Contains("FileResponse") != true && - _document.Operations.Any(o => o.Operation.ActualResponses.Any(r => r.Value.IsBinary(o.Operation) == true)); + _document.Operations.Any(o => o.Operation.ActualResponses.Any(r => r.Value.IsBinary(o.Operation))); /// Gets or sets a value indicating whether to generate exception classes (default: true). - public bool GenerateExceptionClasses => (_settings as CSharpClientGeneratorSettings)?.GenerateExceptionClasses == true; + public bool GenerateExceptionClasses => _settings is CSharpClientGeneratorSettings { GenerateExceptionClasses: true }; /// Gets or sets a value indicating whether to wrap success responses to allow full response access. public bool WrapResponses => _settings.WrapResponses; @@ -130,7 +124,7 @@ public IEnumerable ResponseClassNames .Distinct(); } - return new[] { _settings.ResponseClass.Replace("{controller}", string.Empty) }; + return [_settings.ResponseClass.Replace("{controller}", string.Empty)]; } } @@ -139,8 +133,7 @@ public IEnumerable ExceptionClassNames { get { - var settings = _settings as CSharpClientGeneratorSettings; - if (settings != null) + if (_settings is CSharpClientGeneratorSettings settings) { if (settings.OperationNameGenerator.SupportsMultipleClients) { @@ -152,10 +145,10 @@ public IEnumerable ExceptionClassNames } else { - return new[] { settings.ExceptionClass.Replace("{controller}", string.Empty) }; + return [settings.ExceptionClass.Replace("{controller}", string.Empty)]; } } - return new string[] { }; + return []; } } } diff --git a/src/NSwag.CodeGeneration.CSharp/Models/CSharpOperationModel.cs b/src/NSwag.CodeGeneration.CSharp/Models/CSharpOperationModel.cs index 0c11abc0bf..d681ca8934 100644 --- a/src/NSwag.CodeGeneration.CSharp/Models/CSharpOperationModel.cs +++ b/src/NSwag.CodeGeneration.CSharp/Models/CSharpOperationModel.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NJsonSchema.CodeGeneration; using NJsonSchema.CodeGeneration.CSharp; @@ -18,15 +16,15 @@ namespace NSwag.CodeGeneration.CSharp.Models /// The CSharp operation model. public class CSharpOperationModel : OperationModelBase { - private static readonly string[] ReservedKeywords = - { + private static readonly HashSet ReservedKeywords = + [ "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while" - }; + ]; private readonly CSharpGeneratorBaseSettings _settings; private readonly OpenApiOperation _operation; @@ -57,17 +55,16 @@ public CSharpOperationModel( // TODO: Move to CSharpControllerOperationModel if (generator is CSharpControllerGenerator) { - parameters = parameters + parameters = [.. parameters .OrderBy(p => p.Position ?? 0) - .OrderBy(p => !p.IsRequired) - .ThenBy(p => p.Default == null).ToList(); + .ThenBy(p => !p.IsRequired) + .ThenBy(p => p.Default == null)]; } else { - parameters = parameters + parameters = [.. parameters .OrderBy(p => p.Position ?? 0) - .OrderBy(p => !p.IsRequired) - .ToList(); + .ThenBy(p => !p.IsRequired)]; } } @@ -90,8 +87,7 @@ public string MethodAccessModifier get { var controllerName = _settings.GenerateControllerName(ControllerName); - var settings = _settings as CSharpClientGeneratorSettings; - if (settings != null && settings.ProtectedMethods?.Contains(controllerName + "." + ConversionUtilities.ConvertToUpperCamelCase(OperationName, false) + "Async") == true) + if (_settings is CSharpClientGeneratorSettings settings && settings.ProtectedMethods?.Contains(controllerName + "." + ConversionUtilities.ConvertToUpperCamelCase(OperationName, false) + "Async") == true) { return "protected"; } @@ -113,7 +109,7 @@ public string MethodAccessModifier /// /// The default value of the result type, i.e. default(T) or default(T)! depending on whether NRT are enabled. /// - public string UnwrappedResultDefaultValue => $"default({UnwrappedResultType}){((_settings as CSharpClientGeneratorSettings)?.CSharpGeneratorSettings.GenerateNullableReferenceTypes == true ? "!" : "")}"; + public string UnwrappedResultDefaultValue => $"default({UnwrappedResultType}){(_settings is CSharpClientGeneratorSettings { CSharpGeneratorSettings.GenerateNullableReferenceTypes: true } ? "!" : "")}"; /// Gets or sets the synchronous type of the result. public string SyncResultType @@ -132,15 +128,9 @@ public string SyncResultType } /// Gets or sets the type of the result. - public override string ResultType - { - get - { - return SyncResultType == "void" + public override string ResultType => SyncResultType == "void" ? "System.Threading.Tasks.Task" : "System.Threading.Tasks.Task<" + SyncResultType + ">"; - } - } /// Gets or sets the type of the exception. public override string ExceptionType @@ -169,7 +159,7 @@ public IEnumerable ExceptionDescriptions .Where(r => r.ThrowsException) .SelectMany(r => { - if (r.ExpectedSchemas?.Any() == true) + if (r.ExpectedSchemas?.Count > 0) { return r.ExpectedSchemas .Where(s => s.Schema.ActualSchema?.InheritsSchema(_resolver.ExceptionSchema) == true) @@ -183,14 +173,14 @@ public IEnumerable ExceptionDescriptions } else if (r.InheritsExceptionSchema) { - return new[] - { + return + [ new CSharpExceptionDescriptionModel(r.Type, r.ExceptionDescription, controllerName, settings) - }; + ]; } else { - return new CSharpExceptionDescriptionModel[] { }; + return []; } }); } @@ -204,8 +194,7 @@ public string RouteName { get { - var settings = _settings as CSharpControllerGeneratorSettings; - if (settings != null) + if (_settings is CSharpControllerGeneratorSettings settings) { return settings.GetRouteName(_operation); } @@ -215,7 +204,7 @@ public string RouteName } /// True if the operation has any security schemes - public bool RequiresAuthentication => (_operation.ActualSecurity?.Count() ?? 0) != 0; + public bool RequiresAuthentication => (_operation.ActualSecurity?.Count ?? 0) != 0; /// Gets the security schemas that apply to this operation public IEnumerable Security => _operation.ActualSecurity; diff --git a/src/NSwag.CodeGeneration.CSharp/Models/CSharpParameterModel.cs b/src/NSwag.CodeGeneration.CSharp/Models/CSharpParameterModel.cs index 1d584ecf4c..ea6b4b1842 100644 --- a/src/NSwag.CodeGeneration.CSharp/Models/CSharpParameterModel.cs +++ b/src/NSwag.CodeGeneration.CSharp/Models/CSharpParameterModel.cs @@ -6,10 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; using NJsonSchema.CodeGeneration; -using NJsonSchema.CodeGeneration.CSharp; using NSwag.CodeGeneration.Models; namespace NSwag.CodeGeneration.CSharp.Models @@ -43,10 +40,10 @@ public CSharpParameterModel( } /// Gets a value indicating whether the type is a Nullable<>. - public bool IsSystemNullable => Type.EndsWith("?"); + public bool IsSystemNullable => Type.EndsWith('?'); /// Gets the type of the parameter when used in a controller interface where we can set default values before calling. - public string TypeInControllerInterface => HasDefault ? Type.EndsWith("?") ? Type.Substring(0, Type.Length - 1) : Type : Type; + public string TypeInControllerInterface => HasDefault ? Type.EndsWith('?') ? Type.Substring(0, Type.Length - 1) : Type : Type; /// Gets a value indicating whether the parameter name is a valid CSharp identifier. public bool IsValidIdentifier => Name.Equals(VariableName, StringComparison.OrdinalIgnoreCase); diff --git a/src/NSwag.CodeGeneration.CSharp/Models/CSharpTemplateModelBase.cs b/src/NSwag.CodeGeneration.CSharp/Models/CSharpTemplateModelBase.cs index d4d27e6004..e30f388a7b 100644 --- a/src/NSwag.CodeGeneration.CSharp/Models/CSharpTemplateModelBase.cs +++ b/src/NSwag.CodeGeneration.CSharp/Models/CSharpTemplateModelBase.cs @@ -38,8 +38,8 @@ protected CSharpTemplateModelBase(string controllerName, CSharpGeneratorBaseSett public bool UseSystemTextJson => _settings.CSharpGeneratorSettings.JsonLibrary == CSharpJsonLibrary.SystemTextJson; /// Gets the JSON serializer settings type. - public string JsonSerializerSettingsType => _settings.CSharpGeneratorSettings.JsonLibrary == CSharpJsonLibrary.SystemTextJson ? - "System.Text.Json.JsonSerializerOptions" : - "Newtonsoft.Json.JsonSerializerSettings"; + public string JsonSerializerSettingsType => _settings.CSharpGeneratorSettings.JsonLibrary == CSharpJsonLibrary.SystemTextJson + ? "System.Text.Json.JsonSerializerOptions" + : "Newtonsoft.Json.JsonSerializerSettings"; } } diff --git a/src/NSwag.CodeGeneration.CSharp/NSwag.CodeGeneration.CSharp.csproj b/src/NSwag.CodeGeneration.CSharp/NSwag.CodeGeneration.CSharp.csproj index b39beed50c..ddfe5057c7 100644 --- a/src/NSwag.CodeGeneration.CSharp/NSwag.CodeGeneration.CSharp.csproj +++ b/src/NSwag.CodeGeneration.CSharp/NSwag.CodeGeneration.CSharp.csproj @@ -6,6 +6,7 @@ + @@ -13,6 +14,7 @@ - + + \ No newline at end of file diff --git a/src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs b/src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs index 8dd18deccb..6e7254c682 100644 --- a/src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs +++ b/src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs @@ -1,9 +1,5 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; +using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; -using System.Threading.Tasks; using NJsonSchema; using NJsonSchema.CodeGeneration.TypeScript; using NJsonSchema.Generation; @@ -99,7 +95,7 @@ public void When_generating_CSharp_code_with_SystemTextJson_and_JsonConverters_t // Act var settings = new CSharpClientGeneratorSettings(); settings.CSharpGeneratorSettings.JsonLibrary = NJsonSchema.CodeGeneration.CSharp.CSharpJsonLibrary.SystemTextJson; - settings.CSharpGeneratorSettings.JsonConverters = new[] { "CustomConverter1", "CustomConverter2" }; + settings.CSharpGeneratorSettings.JsonConverters = ["CustomConverter1", "CustomConverter2"]; var generator = new CSharpClientGenerator(document, settings); var code = generator.GenerateFile(); @@ -140,7 +136,7 @@ public static Person FromJson(string data) // Act var settings = new CSharpClientGeneratorSettings(); settings.CSharpGeneratorSettings.JsonLibrary = NJsonSchema.CodeGeneration.CSharp.CSharpJsonLibrary.SystemTextJson; - settings.CSharpGeneratorSettings.JsonConverters = new[] { "CustomConverter1", "CustomConverter2" }; + settings.CSharpGeneratorSettings.JsonConverters = ["CustomConverter1", "CustomConverter2"]; settings.CSharpGeneratorSettings.GenerateJsonMethods = true; var generator = new CSharpClientGenerator(document, settings); @@ -211,7 +207,8 @@ public async Task When_using_json_schema_with_references_in_service_then_referen document.Definitions["Foo"] = schema; // Assert - var jsonService = document.ToJson(); // no exception expected + var json = document.ToJson(); // no exception expected + Assert.NotNull(json); } [Fact] @@ -237,7 +234,7 @@ public void When_using_MultipleClientsFromFirstTagAndOperationName_then_ensure_t // Arrange var operation = new OpenApiOperation { - Tags = tags.ToList() + Tags = [.. tags] }; var generator = new MultipleClientsFromFirstTagAndOperationNameGenerator(); @@ -315,17 +312,19 @@ private static OpenApiDocument CreateDocument() var settings = new NewtonsoftJsonSchemaGeneratorSettings(); var generator = new JsonSchemaGenerator(settings); - document.Paths["/Person"] = new OpenApiPathItem(); - document.Paths["/Person"][OpenApiOperationMethod.Get] = new OpenApiOperation + document.Paths["/Person"] = new OpenApiPathItem { - Responses = + [OpenApiOperationMethod.Get] = new OpenApiOperation { + Responses = { - "200", new OpenApiResponse { - Schema = new JsonSchema + "200", new OpenApiResponse { - Reference = generator.Generate(typeof(Person), new OpenApiSchemaResolver(document, settings)) + Schema = new JsonSchema + { + Reference = generator.Generate(typeof(Person), new OpenApiSchemaResolver(document, settings)) + } } } } diff --git a/src/NSwag.CodeGeneration.Tests/NSwag.CodeGeneration.Tests.csproj b/src/NSwag.CodeGeneration.Tests/NSwag.CodeGeneration.Tests.csproj index beb9f8746b..f46643c26b 100644 --- a/src/NSwag.CodeGeneration.Tests/NSwag.CodeGeneration.Tests.csproj +++ b/src/NSwag.CodeGeneration.Tests/NSwag.CodeGeneration.Tests.csproj @@ -1,13 +1,18 @@  net8.0 + $(NoWarn);CA1707 + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/AngularJSTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/AngularJSTests.cs index da485990da..2c5fdeefc8 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/AngularJSTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/AngularJSTests.cs @@ -1,8 +1,6 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; using NSwag.Generation.WebApi; using Microsoft.AspNetCore.Mvc; -using NJsonSchema.Generation; using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; @@ -18,16 +16,16 @@ public class Foo public class DiscussionController : Controller { [HttpPost] - public void AddMessage([FromBody]Foo message) + public void AddMessage([FromBody] Foo message) { } } - - public class UrlEncodedRequestConsumingController: Controller + + public class UrlEncodedRequestConsumingController : Controller { [HttpPost] [Consumes("application/x-www-form-urlencoded")] - public void AddMessage([FromForm]Foo message, [FromForm]string messageId) + public void AddMessage([FromForm] Foo message, [FromForm] string messageId) { } } @@ -40,9 +38,10 @@ public async Task When_export_types_is_true_then_add_export_before_classes() { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings { SchemaType = SchemaType.Swagger2 } }); - + var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -70,9 +69,10 @@ public async Task When_export_types_is_false_then_dont_add_export_before_classes { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings { SchemaType = SchemaType.Swagger2 } }); - + var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -91,7 +91,7 @@ public async Task When_export_types_is_false_then_dont_add_export_before_classes Assert.DoesNotContain("export class DiscussionClient", code); Assert.DoesNotContain("export interface IDiscussionClient", code); } - + [Fact] public async Task When_consumes_is_url_encoded_then_construct_url_encoded_request() { @@ -102,6 +102,7 @@ public async Task When_consumes_is_url_encoded_then_construct_url_encoded_reques }); var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -120,4 +121,4 @@ public async Task When_consumes_is_url_encoded_then_construct_url_encoded_reques Assert.Contains("\"Content-Type\": \"application/x-www-form-urlencoded\"", code); } } -} +} \ No newline at end of file diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/AngularTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/AngularTests.cs index 251a943019..1a4a48a116 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/AngularTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/AngularTests.cs @@ -1,9 +1,7 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; using NSwag.Generation.WebApi; using Microsoft.AspNetCore.Mvc; using System.ComponentModel.DataAnnotations; -using NJsonSchema.Generation; using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; @@ -20,7 +18,7 @@ public class Foo public class DiscussionController : Controller { [HttpPost] - public void AddMessage([FromBody, Required]Foo message) + public void AddMessage([FromBody, Required] Foo message) { } @@ -68,7 +66,7 @@ public class UrlEncodedRequestConsumingController : Controller { [HttpPost] [Consumes("application/x-www-form-urlencoded")] - public void AddMessage([FromForm]Foo message, [FromForm]string messageId) + public void AddMessage([FromForm] Foo message, [FromForm] string messageId) { } } @@ -83,6 +81,7 @@ public async Task When_return_value_is_void_then_client_returns_observable_of_vo }); var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -110,6 +109,7 @@ public async Task When_export_types_is_true_then_add_export_before_classes() }); var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -139,6 +139,7 @@ public async Task When_export_types_is_false_then_dont_add_export_before_classes }); var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -168,6 +169,7 @@ public async Task When_generic_request() }); var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -197,6 +199,7 @@ public async Task When_consumes_is_url_encoded_then_construct_url_encoded_reques }); var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/ArrayParameterTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/ArrayParameterTests.cs index 8e4bb474bc..9bf692ecfa 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/ArrayParameterTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/ArrayParameterTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.CodeGeneration.TypeScript.Tests { diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/AxiosTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/AxiosTests.cs index 3961e043e6..9ba3d13574 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/AxiosTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/AxiosTests.cs @@ -1,8 +1,6 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; using NSwag.Generation.WebApi; using Microsoft.AspNetCore.Mvc; -using NJsonSchema.Generation; using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; @@ -43,6 +41,7 @@ public async Task When_export_types_is_true_then_add_export_before_classes() var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -73,6 +72,7 @@ public async Task When_export_types_is_false_then_dont_add_export_before_classes var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -103,6 +103,7 @@ public async Task When_consumes_is_url_encoded_then_construct_url_encoded_reques var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -132,6 +133,7 @@ public async Task Add_cancel_token_to_every_call() var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -163,6 +165,7 @@ public async Task When_abort_signal() var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/BinaryTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/BinaryTests.cs index a16bd4a69d..4284ae23b5 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/BinaryTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/BinaryTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.CodeGeneration.TypeScript.Tests { diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/FetchTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/FetchTests.cs index a7c21f49ad..fadcc1d773 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/FetchTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/FetchTests.cs @@ -1,9 +1,7 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; using NSwag.Generation.WebApi; using Microsoft.AspNetCore.Mvc; using NJsonSchema; -using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; namespace NSwag.CodeGeneration.TypeScript.Tests @@ -18,16 +16,17 @@ public class Foo public class DiscussionController : Controller { [HttpPost] - public void AddMessage([FromBody]Foo message) + public void AddMessage([FromBody] Foo message) { } } - public class UrlEncodedRequestConsumingController: Controller + public class UrlEncodedRequestConsumingController : Controller { [HttpPost] [Consumes("application/x-www-form-urlencoded")] - public void AddMessage([FromForm]Foo message, [FromForm]string messageId, [FromForm]System.DateTime date, [FromForm]System.Collections.Generic.List list) + public void AddMessage([FromForm] Foo message, [FromForm] string messageId, [FromForm] System.DateTime date, + [FromForm] System.Collections.Generic.List list) { } } @@ -43,6 +42,7 @@ public async Task When_export_types_is_true_then_add_export_before_classes() var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -73,6 +73,7 @@ public async Task When_export_types_is_false_then_dont_add_export_before_classes var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -103,6 +104,7 @@ public async Task When_consumes_is_url_encoded_then_construct_url_encoded_reques var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -129,9 +131,10 @@ public async Task When_abort_signal() { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings { SchemaType = SchemaType.Swagger2 } }); - + var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -160,6 +163,7 @@ public async Task When_no_abort_signal() var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -216,6 +220,7 @@ public async Task When_no_includeHttpContext() var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -233,4 +238,4 @@ public async Task When_no_includeHttpContext() Assert.DoesNotContain("context: httpContext", code); } } -} +} \ No newline at end of file diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/InheritanceTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/InheritanceTests.cs index c3d84cf174..9f324c21d1 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/InheritanceTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/InheritanceTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.CodeGeneration.TypeScript.Tests { diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/JQueryCallbacksTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/JQueryCallbacksTests.cs index 7fad26d3fb..83d2a40f0f 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/JQueryCallbacksTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/JQueryCallbacksTests.cs @@ -1,8 +1,6 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; using NSwag.Generation.WebApi; using Microsoft.AspNetCore.Mvc; -using NJsonSchema.Generation; using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; @@ -18,16 +16,16 @@ public class Foo public class DiscussionController : Controller { [HttpPost] - public void AddMessage([FromBody]Foo message) + public void AddMessage([FromBody] Foo message) { } } - - public class UrlEncodedRequestConsumingController: Controller + + public class UrlEncodedRequestConsumingController : Controller { [HttpPost] [Consumes("application/x-www-form-urlencoded")] - public void AddMessage([FromForm]Foo message, [FromForm]string messageId) + public void AddMessage([FromForm] Foo message, [FromForm] string messageId) { } } @@ -43,6 +41,7 @@ public async Task When_export_types_is_true_then_add_export_before_classes() var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -73,6 +72,7 @@ public async Task When_export_types_is_false_then_dont_add_export_before_classes var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -91,7 +91,7 @@ public async Task When_export_types_is_false_then_dont_add_export_before_classes Assert.DoesNotContain("export class DiscussionClient", code); Assert.DoesNotContain("export interface IDiscussionClient", code); } - + [Fact] public async Task When_consumes_is_url_encoded_then_construct_url_encoded_request() { @@ -103,6 +103,7 @@ public async Task When_consumes_is_url_encoded_then_construct_url_encoded_reques var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/JQueryPromisesTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/JQueryPromisesTests.cs index 8fd5d4afcd..5f2ece96ce 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/JQueryPromisesTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/JQueryPromisesTests.cs @@ -1,7 +1,5 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using NJsonSchema; -using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.WebApi; using Xunit; @@ -18,16 +16,16 @@ public class Foo public class DiscussionController : Controller { [HttpPost] - public void AddMessage([FromBody]Foo message) + public void AddMessage([FromBody] Foo message) { } } - - public class UrlEncodedRequestConsumingController: Controller + + public class UrlEncodedRequestConsumingController : Controller { [HttpPost] [Consumes("application/x-www-form-urlencoded")] - public void AddMessage([FromForm]Foo message, [FromForm]string messageId) + public void AddMessage([FromForm] Foo message, [FromForm] string messageId) { } } @@ -43,6 +41,7 @@ public async Task When_export_types_is_true_then_add_export_before_classes() var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -73,6 +72,7 @@ public async Task When_export_types_is_false_then_dont_add_export_before_classes var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings @@ -91,7 +91,7 @@ public async Task When_export_types_is_false_then_dont_add_export_before_classes Assert.DoesNotContain("export class DiscussionClient", code); Assert.DoesNotContain("export interface IDiscussionClient", code); } - + [Fact] public async Task When_consumes_is_url_encoded_then_construct_url_encoded_request() { @@ -103,6 +103,7 @@ public async Task When_consumes_is_url_encoded_then_construct_url_encoded_reques var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); // Act var codeGen = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/NSwag.CodeGeneration.TypeScript.Tests.csproj b/src/NSwag.CodeGeneration.TypeScript.Tests/NSwag.CodeGeneration.TypeScript.Tests.csproj index 900bd37ad9..f8815de7b6 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/NSwag.CodeGeneration.TypeScript.Tests.csproj +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/NSwag.CodeGeneration.TypeScript.Tests.csproj @@ -2,12 +2,17 @@ net8.0 true + $(NoWarn);CA1707;IDE1006 + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/ObjectParameterTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/ObjectParameterTests.cs index e00b8a0c3c..a3c8bcc3aa 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/ObjectParameterTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/ObjectParameterTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.CodeGeneration.TypeScript.Tests { diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/OperationParameterTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/OperationParameterTests.cs index fe5f93e689..51fa37593e 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/OperationParameterTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/OperationParameterTests.cs @@ -1,14 +1,9 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using NJsonSchema; using NSwag.Generation.WebApi; -using System.Collections.Generic; using Xunit; -using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; namespace NSwag.CodeGeneration.TypeScript.Tests @@ -20,11 +15,12 @@ public class FooController : Controller [Route("foos/")] public Foo[] GetFoos([FromUri] Bar[] bars) { - return new Foo[0]; + return []; } } - public class FromUriAttribute : Attribute { } + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter)] + public class FromUriAttribute : Attribute; public enum Bar { @@ -44,7 +40,7 @@ public async Task When_query_parameter_is_enum_array_then_the_enum_is_referenced { var serializerSettings = new JsonSerializerSettings { - Converters = new List {new StringEnumConverter()} + Converters = [new StringEnumConverter()] }; // Arrange @@ -62,6 +58,7 @@ public async Task When_query_parameter_is_enum_array_then_the_enum_is_referenced // Act var document = await generator.GenerateForControllerAsync(); var json = document.ToJson(); + Assert.NotNull(json); var clientSettings = new TypeScriptClientGeneratorSettings { diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/TypeScriptDiscriminatorTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/TypeScriptDiscriminatorTests.cs index 30a2ae510d..b52fe2a825 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/TypeScriptDiscriminatorTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/TypeScriptDiscriminatorTests.cs @@ -1,13 +1,10 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using NJsonSchema.CodeGeneration.TypeScript; using NSwag.Generation.WebApi; -using System.Collections.Generic; using System.Runtime.Serialization; using Xunit; using NJsonSchema.NewtonsoftJson.Converters; -using NJsonSchema.Generation; using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; @@ -42,7 +39,7 @@ public class SecondChild : Base public class Nested { public Base Child { get; set; } - + public ICollection ChildCollection { get; set; } } @@ -53,19 +50,19 @@ public string TestLeaf(Base param) { return null; } - + [Route("foo-arr")] public string TestLeafArr(ICollection param) { return null; } - + [Route("bar")] public string Test(OneChild param) { return null; } - + [Route("baz")] public string TestNested(Nested param) { @@ -94,6 +91,7 @@ public async Task When_parameter_is_abstract_then_generate_union() }); var json = document.ToJson(); + Assert.NotNull(json); // Act var code = clientGenerator.GenerateFile(); diff --git a/src/NSwag.CodeGeneration.TypeScript.Tests/TypeScriptOperationParameterTests.cs b/src/NSwag.CodeGeneration.TypeScript.Tests/TypeScriptOperationParameterTests.cs index 813557d191..c65c5799e3 100644 --- a/src/NSwag.CodeGeneration.TypeScript.Tests/TypeScriptOperationParameterTests.cs +++ b/src/NSwag.CodeGeneration.TypeScript.Tests/TypeScriptOperationParameterTests.cs @@ -1,8 +1,6 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using NJsonSchema; using NJsonSchema.CodeGeneration.TypeScript; -using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.WebApi; using Xunit; @@ -43,12 +41,13 @@ public async Task When_parameter_is_nullable_and_ts20_then_it_is_a_union_type_wi { TypeScriptGeneratorSettings = { - TypeScriptVersion = 2.0m, + TypeScriptVersion = 2.0m, NullValue = TypeScriptNullValue.Undefined } }); var json = document.ToJson(); + Assert.NotNull(json); // Act var code = clientGenerator.GenerateFile(); @@ -77,6 +76,7 @@ public async Task When_parameter_is_nullable_and_ts20_then_it_is_not_included_in }); var json = document.ToJson(); + Assert.NotNull(json); // Act var code = clientGenerator.GenerateFile(); @@ -105,6 +105,7 @@ public async Task When_parameter_is_nullable_optional_and_ts20_then_it_is_a_unio }); var json = document.ToJson(); + Assert.NotNull(json); // Act var code = clientGenerator.GenerateFile(); @@ -133,6 +134,7 @@ public async Task When_parameter_is_nullable_optional_and_ts20_then_it_is_not_in }); var json = document.ToJson(); + Assert.NotNull(json); // Act var code = clientGenerator.GenerateFile(); diff --git a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptClientTemplateModel.cs b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptClientTemplateModel.cs index 97b795332d..c8ba381c52 100644 --- a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptClientTemplateModel.cs +++ b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptClientTemplateModel.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using NJsonSchema.CodeGeneration.TypeScript; namespace NSwag.CodeGeneration.TypeScript.Models diff --git a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFileTemplateModel.cs b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFileTemplateModel.cs index 97798b8976..96fe7bb0f1 100644 --- a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFileTemplateModel.cs +++ b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFileTemplateModel.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using NJsonSchema.CodeGeneration; using NJsonSchema.CodeGeneration.TypeScript; @@ -17,7 +15,9 @@ namespace NSwag.CodeGeneration.TypeScript.Models public class TypeScriptFileTemplateModel { private readonly TypeScriptClientGeneratorSettings _settings; +#pragma warning disable IDE0052 private readonly TypeScriptTypeResolver _resolver; +#pragma warning restore IDE0052 private readonly string _clientCode; private readonly IEnumerable _clientTypes; private readonly OpenApiDocument _document; @@ -81,7 +81,7 @@ public IEnumerable ResponseClassNames .Distinct(); } - return new[] { _settings.ResponseClass.Replace("{controller}", string.Empty) }; + return [_settings.ResponseClass.Replace("{controller}", string.Empty)]; } } @@ -104,9 +104,9 @@ public IEnumerable ResponseClassNames public string ExtensionCodeImport => _extensionCode.ImportCode; /// Gets or sets the extension code to insert at the beginning. - public string ExtensionCodeTop => _settings.ConfigurationClass != null && _extensionCode.ExtensionClasses.ContainsKey(_settings.ConfigurationClass) ? - _extensionCode.ExtensionClasses[_settings.ConfigurationClass] + "\n\n" + _extensionCode.TopCode : - _extensionCode.TopCode; + public string ExtensionCodeTop => _settings.ConfigurationClass != null && _extensionCode.ExtensionClasses.TryGetValue(_settings.ConfigurationClass, out string value) + ? value + "\n\n" + _extensionCode.TopCode + : _extensionCode.TopCode; /// Gets or sets the extension code to insert at the end. public string ExtensionCodeBottom { get; } diff --git a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFrameworkModel.cs b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFrameworkModel.cs index 5f1f8e4f8a..760eb38958 100644 --- a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFrameworkModel.cs +++ b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFrameworkModel.cs @@ -36,18 +36,16 @@ internal TypeScriptFrameworkModel(TypeScriptClientGeneratorSettings settings) public bool IsKnockout => _settings.TypeScriptGeneratorSettings.TypeStyle == TypeScriptTypeStyle.KnockoutClass; /// Gets a value indicating whether to render for JQuery. - public bool IsJQuery => _settings.Template == TypeScriptTemplate.JQueryCallbacks || _settings.Template == TypeScriptTemplate.JQueryPromises; + public bool IsJQuery => _settings.Template is TypeScriptTemplate.JQueryCallbacks or TypeScriptTemplate.JQueryPromises; /// Gets a value indicating whether to render for Fetch or Aurelia - public bool IsFetchOrAurelia => _settings.Template == TypeScriptTemplate.Fetch || - _settings.Template == TypeScriptTemplate.Aurelia; + public bool IsFetchOrAurelia => _settings.Template is TypeScriptTemplate.Fetch or TypeScriptTemplate.Aurelia; /// Gets a value indicating whether to render for Axios. public bool IsAxios => _settings.Template == TypeScriptTemplate.Axios; /// Gets a value indicating whether MomentJS is required. - public bool UseMomentJS => _settings.TypeScriptGeneratorSettings.DateTimeType == TypeScriptDateTimeType.MomentJS || - _settings.TypeScriptGeneratorSettings.DateTimeType == TypeScriptDateTimeType.OffsetMomentJS; + public bool UseMomentJS => _settings.TypeScriptGeneratorSettings.DateTimeType is TypeScriptDateTimeType.MomentJS or TypeScriptDateTimeType.OffsetMomentJS; /// Gets a value indicating whether DayJS is required. public bool UseDayJS => _settings.TypeScriptGeneratorSettings.DateTimeType == TypeScriptDateTimeType.DayJS; diff --git a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptOperationModel.cs b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptOperationModel.cs index bf9e0f7929..d277ab401c 100644 --- a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptOperationModel.cs +++ b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptOperationModel.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Linq; using NJsonSchema; using NJsonSchema.CodeGeneration; using NSwag.CodeGeneration.Models; @@ -40,10 +39,7 @@ public TypeScriptOperationModel( if (settings.GenerateOptionalParameters) { - parameters = parameters - .OrderBy(p => p.Position ?? 0) - .OrderBy(p => !p.IsRequired) - .ToList(); + parameters = [.. parameters.OrderBy(p => p.Position ?? 0).ThenBy(p => !p.IsRequired)]; } Parameters = parameters @@ -109,12 +105,10 @@ public override string ResultType public bool IsAngular => _settings.Template == TypeScriptTemplate.Angular; /// Gets a value indicating whether to render for JQuery. - public bool IsJQuery => _settings.Template == TypeScriptTemplate.JQueryCallbacks || - _settings.Template == TypeScriptTemplate.JQueryPromises; + public bool IsJQuery => _settings.Template is TypeScriptTemplate.JQueryCallbacks or TypeScriptTemplate.JQueryPromises; /// Gets a value indicating whether to render for Fetch or Aurelia - public bool IsFetchOrAurelia => _settings.Template == TypeScriptTemplate.Fetch || - _settings.Template == TypeScriptTemplate.Aurelia; + public bool IsFetchOrAurelia => _settings.Template is TypeScriptTemplate.Fetch or TypeScriptTemplate.Aurelia; /// Gets a value indicating whether to use HttpClient with the Angular template. public bool UseAngularHttpClient => IsAngular && _settings.HttpClass == HttpClass.HttpClient; @@ -124,7 +118,7 @@ public override string ExceptionType { get { - if (_operation.ActualResponses.Count(r => !HttpUtilities.IsSuccessStatusCode(r.Key)) == 0) + if (_operation.ActualResponses.All(r => HttpUtilities.IsSuccessStatusCode(r.Key))) { return "string"; } @@ -132,7 +126,7 @@ public override string ExceptionType return string.Join(" | ", _operation.ActualResponses .Where(r => !HttpUtilities.IsSuccessStatusCode(r.Key) && r.Value.Schema != null) .Select(r => _generator.GetTypeName(r.Value.Schema, r.Value.IsNullable(_settings.CodeGeneratorSettings.SchemaType), "Exception")) - .Concat(new[] { "string" })); + .Concat(["string"])); } } diff --git a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptParameterModel.cs b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptParameterModel.cs index 4df9edd217..30e7cf008e 100644 --- a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptParameterModel.cs +++ b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptParameterModel.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; using NJsonSchema; using NJsonSchema.CodeGeneration; using NJsonSchema.CodeGeneration.TypeScript; @@ -52,7 +50,7 @@ public string TypePostfix { if (_settings.TypeScriptGeneratorSettings.SupportsStrictNullChecks) { - return (IsNullable == true ? " | null" : "") + (IsRequired == false ? " | undefined" : ""); + return (IsNullable ? " | null" : "") + (!IsRequired ? " | undefined" : ""); } else { diff --git a/src/NSwag.CodeGeneration.TypeScript/NSwag.CodeGeneration.TypeScript.csproj b/src/NSwag.CodeGeneration.TypeScript/NSwag.CodeGeneration.TypeScript.csproj index c053b170af..cb2159b1c5 100644 --- a/src/NSwag.CodeGeneration.TypeScript/NSwag.CodeGeneration.TypeScript.csproj +++ b/src/NSwag.CodeGeneration.TypeScript/NSwag.CodeGeneration.TypeScript.csproj @@ -13,6 +13,6 @@ - + \ No newline at end of file diff --git a/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGenerator.cs b/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGenerator.cs index 0e60d64687..f12b23849d 100644 --- a/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGenerator.cs +++ b/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGenerator.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NJsonSchema.CodeGeneration; using NJsonSchema.CodeGeneration.TypeScript; @@ -48,8 +45,8 @@ public TypeScriptClientGenerator(OpenApiDocument document, TypeScriptClientGener _extensionCode = new TypeScriptExtensionCode( Settings.TypeScriptGeneratorSettings.ExtensionCode, - (Settings.TypeScriptGeneratorSettings.ExtendedClasses ?? new string[] { }).Concat(new[] { Settings.ConfigurationClass }).ToArray(), - new[] { Settings.ClientBaseClass }); + [.. (Settings.TypeScriptGeneratorSettings.ExtendedClasses ?? []), Settings.ConfigurationClass], + [Settings.ClientBaseClass]); } /// Gets or sets the generator settings. @@ -82,8 +79,9 @@ public override string GetTypeName(JsonSchema schema, bool isNullable, string ty /// The type name. public override string GetBinaryResponseTypeName() { - return Settings.Template != TypeScriptTemplate.JQueryCallbacks && - Settings.Template != TypeScriptTemplate.JQueryPromises ? "FileResponse" : "any"; + return Settings.Template is not TypeScriptTemplate.JQueryCallbacks and not TypeScriptTemplate.JQueryPromises + ? "FileResponse" + : "any"; } /// Generates the file. diff --git a/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGeneratorSettings.cs b/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGeneratorSettings.cs index b1df7c1344..7b159d6c56 100644 --- a/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGeneratorSettings.cs +++ b/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGeneratorSettings.cs @@ -36,13 +36,12 @@ public TypeScriptClientGeneratorSettings() TypeScriptVersion = 2.7m }; - TypeScriptGeneratorSettings.TemplateFactory = new DefaultTemplateFactory(TypeScriptGeneratorSettings, new Assembly[] - { + TypeScriptGeneratorSettings.TemplateFactory = new DefaultTemplateFactory(TypeScriptGeneratorSettings, [ typeof(TypeScriptGeneratorSettings).GetTypeInfo().Assembly, - typeof(TypeScriptClientGeneratorSettings).GetTypeInfo().Assembly, - }); + typeof(TypeScriptClientGeneratorSettings).GetTypeInfo().Assembly + ]); - ProtectedMethods = new string[0]; + ProtectedMethods = []; } /// Gets the TypeScript generator settings. @@ -92,7 +91,7 @@ public TypeScriptClientGeneratorSettings() public string ExceptionClass { get; set; } /// Gets or sets a value indicating whether to use the AbortSignal (Aurelia/Axios/Fetch template only, default: false). - public bool UseAbortSignal { get; set; } = false; + public bool UseAbortSignal { get; set; } // TODO: Angular specific => move @@ -100,19 +99,19 @@ public TypeScriptClientGeneratorSettings() public HttpClass HttpClass { get; set; } = HttpClass.HttpClient; /// Gets or sets a value indicating whether to set the withCredentials flag. - public bool WithCredentials { get; set; } = false; + public bool WithCredentials { get; set; } /// Gets the RxJs version (Angular template only, default: 6.0). public decimal RxJsVersion { get; set; } = 6.0m; /// Gets a value indicating whether to use the Angular 6 Singleton Provider (Angular template only, default: false). - public bool UseSingletonProvider { get; set; } = false; + public bool UseSingletonProvider { get; set; } /// Gets or sets the injection token type (applies only for the Angular template). public InjectionTokenType InjectionTokenType { get; set; } = InjectionTokenType.OpaqueToken; /// Gets a value indicating whether to include the httpContext parameter (Angular template only, default: false). - public bool IncludeHttpContext { get; set; } = false; + public bool IncludeHttpContext { get; set; } internal ITemplate CreateTemplate(object model) { diff --git a/src/NSwag.CodeGeneration/ClientGeneratorBase.cs b/src/NSwag.CodeGeneration/ClientGeneratorBase.cs index bca6c349d4..eccc67c2dd 100644 --- a/src/NSwag.CodeGeneration/ClientGeneratorBase.cs +++ b/src/NSwag.CodeGeneration/ClientGeneratorBase.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NJsonSchema.CodeGeneration; using NSwag.CodeGeneration.Models; @@ -30,7 +28,8 @@ public abstract class ClientGeneratorBaseThe document. /// The code generator settings. /// The type resolver. - protected ClientGeneratorBase(OpenApiDocument document, CodeGeneratorSettingsBase settings, TypeResolverBase resolver) + protected ClientGeneratorBase(OpenApiDocument document, CodeGeneratorSettingsBase settings, + TypeResolverBase resolver) { _document = document; Resolver = resolver; @@ -72,19 +71,21 @@ public string GenerateFile(ClientGeneratorOutputType outputType) { var clientTypes = GenerateAllClientTypes(); - var dtoTypes = BaseSettings.GenerateDtoTypes ? - GenerateDtoTypes() : - Enumerable.Empty(); + var dtoTypes = BaseSettings.GenerateDtoTypes ? GenerateDtoTypes() : []; - clientTypes = - outputType == ClientGeneratorOutputType.Full ? clientTypes : - outputType == ClientGeneratorOutputType.Implementation ? clientTypes.Where(t => t.Category != CodeArtifactCategory.Contract) : - outputType == ClientGeneratorOutputType.Contracts ? clientTypes.Where(t => t.Category == CodeArtifactCategory.Contract) : - Enumerable.Empty(); - - dtoTypes = - outputType == ClientGeneratorOutputType.Full || - outputType == ClientGeneratorOutputType.Contracts ? dtoTypes : Enumerable.Empty(); + clientTypes = outputType switch + { + ClientGeneratorOutputType.Full => clientTypes, + ClientGeneratorOutputType.Implementation => clientTypes.Where(t => + t.Category != CodeArtifactCategory.Contract), + ClientGeneratorOutputType.Contracts => clientTypes.Where(t => + t.Category == CodeArtifactCategory.Contract), + _ => [] + }; + + dtoTypes = outputType is ClientGeneratorOutputType.Full or ClientGeneratorOutputType.Contracts + ? dtoTypes + : []; return GenerateFile(clientTypes, dtoTypes, outputType) .Replace("\r", string.Empty) @@ -97,7 +98,8 @@ public string GenerateFile(ClientGeneratorOutputType outputType) /// The DTO types. /// Type of the output. /// The code. - protected abstract string GenerateFile(IEnumerable clientTypes, IEnumerable dtoTypes, ClientGeneratorOutputType outputType); + protected abstract string GenerateFile(IEnumerable clientTypes, + IEnumerable dtoTypes, ClientGeneratorOutputType outputType); /// Generates the client types. /// The code artifact collection. @@ -113,7 +115,7 @@ protected virtual IEnumerable GenerateAllClientTypes() { var controllerName = controllerOperations.Key; var controllerClassName = BaseSettings.GenerateControllerName(controllerOperations.Key); - var clientType = GenerateClientTypes(controllerName, controllerClassName, controllerOperations.ToList()); + var clientType = GenerateClientTypes(controllerName, controllerClassName, [.. controllerOperations]); clientTypes.AddRange(clientType); } } @@ -133,7 +135,8 @@ protected virtual IEnumerable GenerateAllClientTypes() /// Name of the controller class. /// The operations. /// The code. - protected abstract IEnumerable GenerateClientTypes(string controllerName, string controllerClassName, IEnumerable operations); + protected abstract IEnumerable GenerateClientTypes(string controllerName, + string controllerClassName, IEnumerable operations); /// Generates all DTO types. /// The code artifact collection. @@ -143,7 +146,8 @@ protected virtual IEnumerable GenerateAllClientTypes() /// The operation. /// The settings. /// The operation model. - protected abstract TOperationModel CreateOperationModel(OpenApiOperation operation, ClientGeneratorBaseSettings settings); + protected abstract TOperationModel CreateOperationModel(OpenApiOperation operation, + ClientGeneratorBaseSettings settings); private List GetOperations(OpenApiDocument document) { @@ -158,20 +162,22 @@ private List GetOperations(OpenApiDocument document) var httpMethod = p.Key; var operation = p.Value; - var operationName = BaseSettings.OperationNameGenerator.GetOperationName(document, path, httpMethod, operation); + var operationName = + BaseSettings.OperationNameGenerator.GetOperationName(document, path, httpMethod, operation); if (operationName.Contains(".")) { operationName = operationName.Replace(".", "_"); } - if (operationName.EndsWith("Async")) + if (operationName.EndsWith("Async", StringComparison.Ordinal)) { operationName = operationName.Substring(0, operationName.Length - "Async".Length); } var operationModel = CreateOperationModel(operation, BaseSettings); - operationModel.ControllerName = BaseSettings.OperationNameGenerator.GetClientName(document, path, httpMethod, operation); + operationModel.ControllerName = + BaseSettings.OperationNameGenerator.GetClientName(document, path, httpMethod, operation); operationModel.Path = path; operationModel.HttpMethod = httpMethod; operationModel.OperationName = operationName; @@ -179,7 +185,8 @@ private List GetOperations(OpenApiDocument document) result.Add(operationModel); } } + return result; } } -} +} \ No newline at end of file diff --git a/src/NSwag.CodeGeneration/ClientGeneratorBaseSettings.cs b/src/NSwag.CodeGeneration/ClientGeneratorBaseSettings.cs index 1e2e79e021..88d40e2589 100644 --- a/src/NSwag.CodeGeneration/ClientGeneratorBaseSettings.cs +++ b/src/NSwag.CodeGeneration/ClientGeneratorBaseSettings.cs @@ -29,8 +29,8 @@ protected ClientGeneratorBaseSettings() GenerateResponseClasses = true; ResponseClass = "SwaggerResponse"; - WrapResponseMethods = new string[0]; - ExcludedParameterNames = new string[0]; + WrapResponseMethods = []; + ExcludedParameterNames = []; } /// Gets the code generator settings. diff --git a/src/NSwag.CodeGeneration/DefaultParameterNameGenerator.cs b/src/NSwag.CodeGeneration/DefaultParameterNameGenerator.cs index ff5e1cf633..dc8f81394f 100644 --- a/src/NSwag.CodeGeneration/DefaultParameterNameGenerator.cs +++ b/src/NSwag.CodeGeneration/DefaultParameterNameGenerator.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using NJsonSchema; namespace NSwag.CodeGeneration diff --git a/src/NSwag.CodeGeneration/DefaultTemplateFactory.cs b/src/NSwag.CodeGeneration/DefaultTemplateFactory.cs index 342f891c84..f099760a77 100644 --- a/src/NSwag.CodeGeneration/DefaultTemplateFactory.cs +++ b/src/NSwag.CodeGeneration/DefaultTemplateFactory.cs @@ -6,10 +6,8 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; using System.Reflection; using NJsonSchema.CodeGeneration; -using System.IO; namespace NSwag.CodeGeneration { @@ -50,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.CodeGeneration/IParameterNameGenerator.cs b/src/NSwag.CodeGeneration/IParameterNameGenerator.cs index becd8839f8..97838504a4 100644 --- a/src/NSwag.CodeGeneration/IParameterNameGenerator.cs +++ b/src/NSwag.CodeGeneration/IParameterNameGenerator.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; - namespace NSwag.CodeGeneration { /// The parameter name generator interface. diff --git a/src/NSwag.CodeGeneration/JsonSchemaExtensions.cs b/src/NSwag.CodeGeneration/JsonSchemaExtensions.cs index aa7c5d6d30..8ec3e76c77 100644 --- a/src/NSwag.CodeGeneration/JsonSchemaExtensions.cs +++ b/src/NSwag.CodeGeneration/JsonSchemaExtensions.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using NJsonSchema; namespace NSwag.CodeGeneration @@ -20,7 +18,7 @@ public static class JsonSchema4Extensions /// true or false public static bool UsesComplexObjectSchema(this JsonSchema schema) { - return UsesComplexObjectSchema(schema, new List()); + return UsesComplexObjectSchema(schema, []); } private static bool UsesComplexObjectSchema(this JsonSchema schema, List checkedSchemas) diff --git a/src/NSwag.CodeGeneration/Models/IOperationModel.cs b/src/NSwag.CodeGeneration/Models/IOperationModel.cs index ddcd4942cb..44694bef59 100644 --- a/src/NSwag.CodeGeneration/Models/IOperationModel.cs +++ b/src/NSwag.CodeGeneration/Models/IOperationModel.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; - namespace NSwag.CodeGeneration.Models { /// The operation model interface. diff --git a/src/NSwag.CodeGeneration/Models/OperationModelBase.cs b/src/NSwag.CodeGeneration/Models/OperationModelBase.cs index 9af99efa68..bd4393668b 100644 --- a/src/NSwag.CodeGeneration/Models/OperationModelBase.cs +++ b/src/NSwag.CodeGeneration/Models/OperationModelBase.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NJsonSchema.CodeGeneration; @@ -88,13 +85,10 @@ protected abstract TResponseModel CreateResponseModel(OpenApiOperation operation public string HttpMethodLower => ConversionUtilities.ConvertToLowerCamelCase(HttpMethod.ToString(), false); /// Gets a value indicating whether the HTTP method is GET or DELETE or HEAD. - public bool IsGetOrDeleteOrHead => - HttpMethod == OpenApiOperationMethod.Get || - HttpMethod == OpenApiOperationMethod.Delete || - HttpMethod == OpenApiOperationMethod.Head; + public bool IsGetOrDeleteOrHead => HttpMethod is OpenApiOperationMethod.Get or OpenApiOperationMethod.Delete or OpenApiOperationMethod.Head; /// Gets a value indicating whether the HTTP method is GET or HEAD. - public bool IsGetOrHead => HttpMethod == OpenApiOperationMethod.Get || HttpMethod == OpenApiOperationMethod.Head; + public bool IsGetOrHead => HttpMethod is OpenApiOperationMethod.Get or OpenApiOperationMethod.Head; // TODO: Remove this (may not work correctly) /// Gets or sets a value indicating whether the operation has a result type (i.e. not void). @@ -114,7 +108,7 @@ public string UnwrappedResultType return "void"; } - if (response.Value.IsBinary(_operation) == true) + if (response.Value.IsBinary(_operation)) { return _generator.GetBinaryResponseTypeName(); } @@ -199,7 +193,7 @@ public TParameterModel ContentParameter public IEnumerable PathParameters => Parameters.Where(p => p.Kind == OpenApiParameterKind.Path); /// Gets the query parameters. - public IEnumerable QueryParameters => Parameters.Where(p => p.Kind == OpenApiParameterKind.Query || p.Kind == OpenApiParameterKind.ModelBinding); + public IEnumerable QueryParameters => Parameters.Where(p => p.Kind is OpenApiParameterKind.Query or OpenApiParameterKind.ModelBinding); /// Gets a value indicating whether the operation has query parameters. public bool HasQueryParameters => QueryParameters.Any(); @@ -208,7 +202,7 @@ public TParameterModel ContentParameter public IEnumerable HeaderParameters => Parameters.Where(p => p.Kind == OpenApiParameterKind.Header); /// Gets or sets a value indicating whether the accept header is defined in a parameter. - public bool HasAcceptHeaderParameterParameter => HeaderParameters.Any(p => p.Name.ToLowerInvariant() == "accept"); + public bool HasAcceptHeaderParameterParameter => HeaderParameters.Any(p => p.Name.Equals("accept", StringComparison.OrdinalIgnoreCase)); /// Gets a value indicating whether the operation has form parameters. public bool HasFormParameters => Parameters.Any(p => p.Kind == OpenApiParameterKind.FormData); @@ -337,7 +331,7 @@ protected virtual string ResolveParameterType(OpenApiParameter parameter) } var typeNameHint = !schema.HasTypeNameTitle ? ConversionUtilities.ConvertToUpperCamelCase(parameter.Name, true) : null; - var isNullable = parameter.IsRequired == false || parameter.IsNullable(_settings.CodeGeneratorSettings.SchemaType); + var isNullable = !parameter.IsRequired || parameter.IsNullable(_settings.CodeGeneratorSettings.SchemaType); return _resolver.Resolve(schema, isNullable, typeNameHint); } @@ -351,7 +345,7 @@ protected IList GetActualParameters() var formDataSchema = _operation?.ActualRequestBody?.Content?.ContainsKey("multipart/form-data") == true ? - _operation.ActualRequestBody.Content["multipart/form-data"]?.Schema.ActualSchema: null; + _operation.ActualRequestBody.Content["multipart/form-data"]?.Schema.ActualSchema : null; if (formDataSchema != null && formDataSchema.ActualProperties.Count > 0) { diff --git a/src/NSwag.CodeGeneration/Models/ParameterModelBase.cs b/src/NSwag.CodeGeneration/Models/ParameterModelBase.cs index 8a9a26c84c..ed9cea5efb 100644 --- a/src/NSwag.CodeGeneration/Models/ParameterModelBase.cs +++ b/src/NSwag.CodeGeneration/Models/ParameterModelBase.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NJsonSchema.CodeGeneration; @@ -102,22 +99,10 @@ public string Default public bool IsForm => _parameter.Style == OpenApiParameterStyle.Form; /// Gets the contained value property names (OpenAPI 3). - public IEnumerable PropertyNames - { - get - { - return _properties.Where(p => !p.IsCollection); - } - } + public IEnumerable PropertyNames => _properties.Where(p => !p.IsCollection); /// Gets the contained collection property names (OpenAPI 3). - public IEnumerable CollectionPropertyNames - { - get - { - return _properties.Where(p => p.IsCollection); - } - } + public IEnumerable CollectionPropertyNames => _properties.Where(p => p.IsCollection); /// Gets a value indicating whether the parameter has a description. public bool HasDescription => !string.IsNullOrEmpty(Description); @@ -135,7 +120,7 @@ public IEnumerable CollectionPropertyNames public bool IsNullable => _parameter.IsNullable(_settings.SchemaType); /// Gets a value indicating whether the parameter is optional (i.e. not required). - public bool IsOptional => _parameter.IsRequired == false; + public bool IsOptional => !_parameter.IsRequired; /// Gets a value indicating whether the parameter has a description or is optional. public bool HasDescriptionOrIsOptional => HasDescription || !IsRequired; diff --git a/src/NSwag.CodeGeneration/Models/ResponseModelBase.cs b/src/NSwag.CodeGeneration/Models/ResponseModelBase.cs index fbe848806b..f1a9b5838c 100644 --- a/src/NSwag.CodeGeneration/Models/ResponseModelBase.cs +++ b/src/NSwag.CodeGeneration/Models/ResponseModelBase.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NJsonSchema.CodeGeneration; @@ -73,26 +71,13 @@ protected ResponseModelBase(IOperationModel operationModel, public ICollection ExpectedSchemas => _response.ExpectedSchemas; /// Gets a value indicating whether the response is of type date. - public bool IsDate - { - get - { - return ActualResponseSchema != null && + public bool IsDate => ActualResponseSchema != null && (ActualResponseSchema.Format == JsonFormatStrings.Date || ActualResponseSchema.Format == JsonFormatStrings.DateTime) && _generator.GetTypeName(ActualResponseSchema, IsNullable, "Response") != "string"; - } - } /// Gets a value indicating whether the response requires a text/plain content. - public bool IsPlainText - { - get - { - return !_response.Content.ContainsKey("application/json") && - _response.Content.ContainsKey("text/plain"); - } - } + public bool IsPlainText => !_response.Content.ContainsKey("application/json") && _response.Content.ContainsKey("text/plain"); /// Gets a value indicating whether this is a file response. public bool IsFile => IsSuccess && _response.IsBinary(_operation); diff --git a/src/NSwag.CodeGeneration/NSwag.CodeGeneration.csproj b/src/NSwag.CodeGeneration/NSwag.CodeGeneration.csproj index 1153c8fdd0..c97006081b 100644 --- a/src/NSwag.CodeGeneration/NSwag.CodeGeneration.csproj +++ b/src/NSwag.CodeGeneration/NSwag.CodeGeneration.csproj @@ -5,7 +5,7 @@ - + diff --git a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndOperationIdGenerator.cs b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndOperationIdGenerator.cs index f9df12a5e0..6bad98a59c 100644 --- a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndOperationIdGenerator.cs +++ b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndOperationIdGenerator.cs @@ -7,7 +7,6 @@ //----------------------------------------------------------------------- using NJsonSchema; -using System.Linq; namespace NSwag.CodeGeneration.OperationNameGenerators { diff --git a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndOperationNameGenerator.cs b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndOperationNameGenerator.cs index f25ab37b22..e7445b92ce 100644 --- a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndOperationNameGenerator.cs +++ b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndOperationNameGenerator.cs @@ -7,7 +7,6 @@ //----------------------------------------------------------------------- using NJsonSchema; -using System.Linq; namespace NSwag.CodeGeneration.OperationNameGenerators { diff --git a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndPathSegmentsOperationNameGenerator.cs b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndPathSegmentsOperationNameGenerator.cs index 0a74d51426..5b38537538 100644 --- a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndPathSegmentsOperationNameGenerator.cs +++ b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromFirstTagAndPathSegmentsOperationNameGenerator.cs @@ -7,7 +7,6 @@ //----------------------------------------------------------------------- using NJsonSchema; -using System.Linq; namespace NSwag.CodeGeneration.OperationNameGenerators { diff --git a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromOperationIdOperationNameGenerator.cs b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromOperationIdOperationNameGenerator.cs index 10e29f7a8b..acb555941f 100644 --- a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromOperationIdOperationNameGenerator.cs +++ b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromOperationIdOperationNameGenerator.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Diagnostics; -using System.Linq; using NJsonSchema; namespace NSwag.CodeGeneration.OperationNameGenerators @@ -80,7 +77,7 @@ private static ReadOnlySpan GetClientName(OpenApiOperation operation) // no underscore, fast path if (idxFirst == -1) { - return ReadOnlySpan.Empty; + return []; } int idxLast = operationIdSpan.LastIndexOf(underscoreSeparator); @@ -91,7 +88,7 @@ private static ReadOnlySpan GetClientName(OpenApiOperation operation) // underscore is the first character if (idxFirst == 0) { - return ReadOnlySpan.Empty; + return []; } return operationIdSpan.Slice(0, idxFirst); diff --git a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromPathSegmentsOperationNameGenerator.cs b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromPathSegmentsOperationNameGenerator.cs index a5817ad7c2..c3daf43f57 100644 --- a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromPathSegmentsOperationNameGenerator.cs +++ b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromPathSegmentsOperationNameGenerator.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Linq; - namespace NSwag.CodeGeneration.OperationNameGenerators { /// Generates the client and operation name based on the path segments (operation name = last segment, client name = second to last segment). @@ -45,8 +43,8 @@ public virtual string GetOperationName(OpenApiDocument document, string path, st var hasNameConflict = document.Paths .SelectMany(pair => pair.Value.ActualPathItem .Select(p => new { Path = pair.Key.Trim('/'), HttpMethod = p.Key, Operation = p.Value })) - .Where(op => - GetClientName(document, op.Path, op.HttpMethod, op.Operation) == GetClientName(document, path, httpMethod, operation) && + .Where(op => + GetClientName(document, op.Path, op.HttpMethod, op.Operation) == GetClientName(document, path, httpMethod, operation) && ConvertPathToName(op.Path) == operationName ).ToList() .Count > 1; diff --git a/src/NSwag.CodeGeneration/OperationNameGenerators/SingleClientFromPathSegmentsOperationNameGenerator.cs b/src/NSwag.CodeGeneration/OperationNameGenerators/SingleClientFromPathSegmentsOperationNameGenerator.cs index 760fccbcd3..501de49887 100644 --- a/src/NSwag.CodeGeneration/OperationNameGenerators/SingleClientFromPathSegmentsOperationNameGenerator.cs +++ b/src/NSwag.CodeGeneration/OperationNameGenerators/SingleClientFromPathSegmentsOperationNameGenerator.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Linq; using System.Text.RegularExpressions; namespace NSwag.CodeGeneration.OperationNameGenerators @@ -40,8 +39,8 @@ public virtual string GetOperationName(OpenApiDocument document, string path, st var hasNameConflict = document.Paths .SelectMany(pair => pair.Value.ActualPathItem .Select(p => new { Path = pair.Key.Trim('/'), HttpMethod = p.Key, Operation = p.Value })) - .Where(op => - GetClientName(document, op.Path, op.HttpMethod, op.Operation) == GetClientName(document, path, httpMethod, operation) && + .Where(op => + GetClientName(document, op.Path, op.HttpMethod, op.Operation) == GetClientName(document, path, httpMethod, operation) && ConvertPathToName(op.Path) == operationName ) .ToList().Count > 1; diff --git a/src/NSwag.Commands/CodeGeneratorCollection.cs b/src/NSwag.Commands/CodeGeneratorCollection.cs index ed57e642d4..280c5db82c 100644 --- a/src/NSwag.Commands/CodeGeneratorCollection.cs +++ b/src/NSwag.Commands/CodeGeneratorCollection.cs @@ -1,12 +1,12 @@ -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json; +using Newtonsoft.Json; using NSwag.Commands.CodeGeneration; namespace NSwag.Commands { /// The command collection. +#pragma warning disable CA1711 public class CodeGeneratorCollection +#pragma warning restore CA1711 { /// Gets or sets the SwaggerToTypeScriptClientCommand. [JsonProperty("OpenApiToTypeScriptClient", NullValueHandling = NullValueHandling.Ignore)] diff --git a/src/NSwag.Commands/Commands/CodeGeneration/CodeGeneratorCommandBase.cs b/src/NSwag.Commands/Commands/CodeGeneration/CodeGeneratorCommandBase.cs index 3f866553aa..f926caca4c 100644 --- a/src/NSwag.Commands/Commands/CodeGeneration/CodeGeneratorCommandBase.cs +++ b/src/NSwag.Commands/Commands/CodeGeneration/CodeGeneratorCommandBase.cs @@ -26,8 +26,8 @@ protected CodeGeneratorCommandBase(TSettings settings) [Argument(Name = "TemplateDirectory", IsRequired = false, Description = "The Liquid template directory (experimental).")] public string TemplateDirectory { - get { return Settings.CodeGeneratorSettings.TemplateDirectory; } - set { Settings.CodeGeneratorSettings.TemplateDirectory = value; } + get => Settings.CodeGeneratorSettings.TemplateDirectory; + set => Settings.CodeGeneratorSettings.TemplateDirectory = value; } } } \ No newline at end of file diff --git a/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToCSharpCommand.cs b/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToCSharpCommand.cs index 1d72e3ebfd..85569bcc1c 100644 --- a/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToCSharpCommand.cs +++ b/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToCSharpCommand.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Threading.Tasks; using NConsole; using Newtonsoft.Json; using NJsonSchema.CodeGeneration.CSharp; @@ -32,210 +31,210 @@ public JsonSchemaToCSharpCommand() [Argument(Name = "Namespace", Description = "The namespace of the generated classes.")] public string Namespace { - get { return Settings.Namespace; } - set { Settings.Namespace = value; } + get => Settings.Namespace; + set => Settings.Namespace = value; } [Argument(Name = "RequiredPropertiesMustBeDefined", IsRequired = false, Description = "Specifies whether a required property must be defined in JSON (sets Required.Always when the property is required).")] public bool RequiredPropertiesMustBeDefined { - get { return Settings.RequiredPropertiesMustBeDefined; } - set { Settings.RequiredPropertiesMustBeDefined = value; } + get => Settings.RequiredPropertiesMustBeDefined; + set => Settings.RequiredPropertiesMustBeDefined = value; } [Argument(Name = "DateType", IsRequired = false, Description = "The date .NET type (default: 'DateTimeOffset').")] public string DateType { - get { return Settings.DateType; } - set { Settings.DateType = value; } + get => Settings.DateType; + set => Settings.DateType = value; } [Argument(Name = "JsonConverters", IsRequired = false, Description = "Specifies the custom Json.NET converter types (optional, comma separated).")] public string[] JsonConverters { - get { return Settings.JsonConverters; } - set { Settings.JsonConverters = value; } + get => Settings.JsonConverters; + set => Settings.JsonConverters = value; } [Argument(Name = "AnyType", IsRequired = false, Description = "The any .NET type (default: 'object').")] public string AnyType { - get { return Settings.AnyType; } - set { Settings.AnyType = value; } + get => Settings.AnyType; + set => Settings.AnyType = value; } [Argument(Name = "DateTimeType", IsRequired = false, Description = "The date time .NET type (default: 'DateTimeOffset').")] public string DateTimeType { - get { return Settings.DateTimeType; } - set { Settings.DateTimeType = value; } + get => Settings.DateTimeType; + set => Settings.DateTimeType = value; } [Argument(Name = "TimeType", IsRequired = false, Description = "The time .NET type (default: 'TimeSpan').")] public string TimeType { - get { return Settings.TimeType; } - set { Settings.TimeType = value; } + get => Settings.TimeType; + set => Settings.TimeType = value; } [Argument(Name = "TimeSpanType", IsRequired = false, Description = "The time span .NET type (default: 'TimeSpan').")] public string TimeSpanType { - get { return Settings.TimeSpanType; } - set { Settings.TimeSpanType = value; } + get => Settings.TimeSpanType; + set => Settings.TimeSpanType = value; } [Argument(Name = "ArrayType", IsRequired = false, Description = "The generic array .NET type (default: 'ICollection').")] public string ArrayType { - get { return Settings.ArrayType; } - set { Settings.ArrayType = value; } + get => Settings.ArrayType; + set => Settings.ArrayType = value; } [Argument(Name = "ArrayInstanceType", IsRequired = false, Description = "The generic array .NET instance type (default: empty = ArrayType).")] public string ArrayInstanceType { - get { return Settings.ArrayInstanceType; } - set { Settings.ArrayInstanceType = value; } + get => Settings.ArrayInstanceType; + set => Settings.ArrayInstanceType = value; } [Argument(Name = "DictionaryType", IsRequired = false, Description = "The generic dictionary .NET type (default: 'IDictionary').")] public string DictionaryType { - get { return Settings.DictionaryType; } - set { Settings.DictionaryType = value; } + get => Settings.DictionaryType; + set => Settings.DictionaryType = value; } [Argument(Name = "DictionaryInstanceType", IsRequired = false, Description = "The generic dictionary .NET instance type (default: empty = DictionaryType).")] public string DictionaryInstanceType { - get { return Settings.DictionaryInstanceType; } - set { Settings.DictionaryInstanceType = value; } + get => Settings.DictionaryInstanceType; + set => Settings.DictionaryInstanceType = value; } [Argument(Name = "ArrayBaseType", IsRequired = false, Description = "The generic array .NET type (default: 'Collection').")] public string ArrayBaseType { - get { return Settings.ArrayBaseType; } - set { Settings.ArrayBaseType = value; } + get => Settings.ArrayBaseType; + set => Settings.ArrayBaseType = value; } [Argument(Name = "DictionaryBaseType", IsRequired = false, Description = "The generic dictionary .NET type (default: 'Dictionary').")] public string DictionaryBaseType { - get { return Settings.DictionaryBaseType; } - set { Settings.DictionaryBaseType = value; } + get => Settings.DictionaryBaseType; + set => Settings.DictionaryBaseType = value; } [Argument(Name = "ClassStyle", IsRequired = false, Description = "The CSharp class style, 'Poco' or 'Inpc' (default: 'Poco').")] public CSharpClassStyle ClassStyle { - get { return Settings.ClassStyle; } - set { Settings.ClassStyle = value; } + get => Settings.ClassStyle; + set => Settings.ClassStyle = value; } [Argument(Name = "JsonLibrary", IsRequired = false, Description = "The CSharp JSON library, 'NewtonsoftJson' or 'SystemTextJson' (default: 'NewtonsoftJson', 'SystemTextJson' is experimental).")] public CSharpJsonLibrary JsonLibrary { - get { return Settings.JsonLibrary; } - set { Settings.JsonLibrary = value; } + get => Settings.JsonLibrary; + set => Settings.JsonLibrary = value; } [Argument(Name = "GenerateDefaultValues", IsRequired = false, Description = "Specifies whether to generate default values for properties (may generate CSharp 6 code, default: true).")] public bool GenerateDefaultValues { - get { return Settings.GenerateDefaultValues; } - set { Settings.GenerateDefaultValues = value; } + get => Settings.GenerateDefaultValues; + set => Settings.GenerateDefaultValues = value; } [Argument(Name = "GenerateDataAnnotations", IsRequired = false, Description = "Specifies whether to generate data annotation attributes on DTO classes (default: true).")] public bool GenerateDataAnnotations { - get { return Settings.GenerateDataAnnotations; } - set { Settings.GenerateDataAnnotations = value; } + get => Settings.GenerateDataAnnotations; + set => Settings.GenerateDataAnnotations = value; } [Argument(Name = "ExcludedTypeNames", IsRequired = false, Description = "The excluded DTO type names (must be defined in an import or other namespace).")] public string[] ExcludedTypeNames { - get { return Settings.ExcludedTypeNames; } - set { Settings.ExcludedTypeNames = value; } + get => Settings.ExcludedTypeNames; + set => Settings.ExcludedTypeNames = value; } [Argument(Name = "HandleReferences", IsRequired = false, Description = "Use preserve references handling (All) in the JSON serializer (default: false).")] public bool HandleReferences { - get { return Settings.HandleReferences; } - set { Settings.HandleReferences = value; } + get => Settings.HandleReferences; + set => Settings.HandleReferences = value; } [Argument(Name = "GenerateImmutableArrayProperties", IsRequired = false, Description = "Specifies whether to remove the setter for non-nullable array properties (default: false).")] public bool GenerateImmutableArrayProperties { - get { return Settings.GenerateImmutableArrayProperties; } - set { Settings.GenerateImmutableArrayProperties = value; } + get => Settings.GenerateImmutableArrayProperties; + set => Settings.GenerateImmutableArrayProperties = value; } [Argument(Name = "GenerateImmutableDictionaryProperties", IsRequired = false, Description = "Specifies whether to remove the setter for non-nullable dictionary properties (default: false).")] public bool GenerateImmutableDictionaryProperties { - get { return Settings.GenerateImmutableDictionaryProperties; } - set { Settings.GenerateImmutableDictionaryProperties = value; } + get => Settings.GenerateImmutableDictionaryProperties; + set => Settings.GenerateImmutableDictionaryProperties = value; } [Argument(Name = "JsonSerializerSettingsTransformationMethod", IsRequired = false, Description = "The name of a static method which is called to transform the JsonSerializerSettings used in the generated ToJson()/FromJson() methods (default: none).")] public string JsonSerializerSettingsTransformationMethod { - get { return Settings.JsonSerializerSettingsTransformationMethod; } - set { Settings.JsonSerializerSettingsTransformationMethod = value; } + get => Settings.JsonSerializerSettingsTransformationMethod; + set => Settings.JsonSerializerSettingsTransformationMethod = value; } [Argument(Name = "InlineNamedArrays", Description = "Inline named arrays (default: false).", IsRequired = false)] public bool InlineNamedArrays { - get { return Settings.InlineNamedArrays; } - set { Settings.InlineNamedArrays = value; } + get => Settings.InlineNamedArrays; + set => Settings.InlineNamedArrays = value; } [Argument(Name = "InlineNamedDictionaries", Description = "Inline named dictionaries (default: false).", IsRequired = false)] public bool InlineNamedDictionaries { - get { return Settings.InlineNamedDictionaries; } - set { Settings.InlineNamedDictionaries = value; } + get => Settings.InlineNamedDictionaries; + set => Settings.InlineNamedDictionaries = value; } [Argument(Name = "InlineNamedTuples", Description = "Inline named tuples (default: true).", IsRequired = false)] public bool InlineNamedTuples { - get { return Settings.InlineNamedTuples; } - set { Settings.InlineNamedTuples = value; } + get => Settings.InlineNamedTuples; + set => Settings.InlineNamedTuples = value; } [Argument(Name = "InlineNamedAny", Description = "Inline named any types (default: false).", IsRequired = false)] public bool InlineNamedAny { - get { return Settings.InlineNamedAny; } - set { Settings.InlineNamedAny = value; } + get => Settings.InlineNamedAny; + set => Settings.InlineNamedAny = value; } [Argument(Name = "GenerateOptionalPropertiesAsNullable", IsRequired = false, Description = "Specifies whether optional schema properties " + "(not required) are generated as nullable properties (default: false).")] public bool GenerateOptionalPropertiesAsNullable { - get { return Settings.GenerateOptionalPropertiesAsNullable; } - set { Settings.GenerateOptionalPropertiesAsNullable = value; } + get => Settings.GenerateOptionalPropertiesAsNullable; + set => Settings.GenerateOptionalPropertiesAsNullable = value; } [Argument(Name = "GenerateNullableReferenceTypes", IsRequired = false, Description = "Specifies whether whether to " + "generate Nullable Reference Type annotations (default: false).")] public bool GenerateNullableReferenceTypes { - get { return Settings.GenerateNullableReferenceTypes; } - set { Settings.GenerateNullableReferenceTypes = value; } + get => Settings.GenerateNullableReferenceTypes; + set => Settings.GenerateNullableReferenceTypes = value; } public override async Task RunAsync(CommandLineProcessor processor, IConsoleHost host) diff --git a/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToOpenApiCommand.cs b/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToOpenApiCommand.cs index 44609e747c..e51106d1cb 100644 --- a/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToOpenApiCommand.cs +++ b/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToOpenApiCommand.cs @@ -1,5 +1,4 @@ using System.Text.RegularExpressions; -using System.Threading.Tasks; using NConsole; using Newtonsoft.Json; using NJsonSchema; diff --git a/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToTypeScriptCommand.cs b/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToTypeScriptCommand.cs index 64c8e7be54..ff3f0c1f00 100644 --- a/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToTypeScriptCommand.cs +++ b/src/NSwag.Commands/Commands/CodeGeneration/JsonSchemaToTypeScriptCommand.cs @@ -6,9 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Threading.Tasks; using NConsole; -using NJsonSchema; using NJsonSchema.CodeGeneration.TypeScript; #pragma warning disable 1591 diff --git a/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpClientCommand.cs b/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpClientCommand.cs index fcb02cd5b0..4b6a248011 100644 --- a/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpClientCommand.cs +++ b/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpClientCommand.cs @@ -6,10 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using NConsole; using NSwag.CodeGeneration; using NSwag.CodeGeneration.CSharp; @@ -28,182 +24,182 @@ public OpenApiToCSharpClientCommand() : base(new CSharpClientGeneratorSettings() [Argument(Name = "ClientBaseClass", IsRequired = false, Description = "The client base class (empty for no base class).")] public string ClientBaseClass { - get { return Settings.ClientBaseClass; } - set { Settings.ClientBaseClass = value; } + get => Settings.ClientBaseClass; + set => Settings.ClientBaseClass = value; } [Argument(Name = "ConfigurationClass", IsRequired = false, Description = "The configuration class. The setting ClientBaseClass must be set. (empty for no configuration class).")] public string ConfigurationClass { - get { return Settings.ConfigurationClass; } - set { Settings.ConfigurationClass = value; } + get => Settings.ConfigurationClass; + set => Settings.ConfigurationClass = value; } [Argument(Name = "GenerateClientClasses", IsRequired = false, Description = "Specifies whether generate client classes.")] public bool GenerateClientClasses { - get { return Settings.GenerateClientClasses; } - set { Settings.GenerateClientClasses = value; } + get => Settings.GenerateClientClasses; + set => Settings.GenerateClientClasses = value; } [Argument(Name = "SuppressClientClassesOutput", IsRequired = false, Description = "Specifies whether generate output for client classes.")] public bool SuppressClientClassesOutput { - get { return Settings.SuppressClientClassesOutput; } - set { Settings.SuppressClientClassesOutput = value; } + get => Settings.SuppressClientClassesOutput; + set => Settings.SuppressClientClassesOutput = value; } [Argument(Name = "GenerateClientInterfaces", IsRequired = false, Description = "Specifies whether generate interfaces for the client classes.")] public bool GenerateClientInterfaces { - get { return Settings.GenerateClientInterfaces; } - set { Settings.GenerateClientInterfaces = value; } + get => Settings.GenerateClientInterfaces; + set => Settings.GenerateClientInterfaces = value; } [Argument(Name = "SuppressClientInterfacesOutput", IsRequired = false, Description = "Specifies whether generate output for interfaces for the client classes.")] public bool SuppressClientInterfacesOutput { - get { return Settings.SuppressClientInterfacesOutput; } - set { Settings.SuppressClientInterfacesOutput = value; } + get => Settings.SuppressClientInterfacesOutput; + set => Settings.SuppressClientInterfacesOutput = value; } [Argument(Name = "ClientBaseInterface", IsRequired = false, Description = "Base interface for client interfaces (empty for no client base interface).")] public string ClientBaseInterface { - get { return Settings.ClientBaseInterface; } - set { Settings.ClientBaseInterface = value; } + get => Settings.ClientBaseInterface; + set => Settings.ClientBaseInterface = value; } [Argument(Name = "InjectHttpClient", IsRequired = false, Description = "Specifies whether an HttpClient instance is injected (default: true).")] public bool InjectHttpClient { - get { return Settings.InjectHttpClient; } - set { Settings.InjectHttpClient = value; } + get => Settings.InjectHttpClient; + set => Settings.InjectHttpClient = value; } [Argument(Name = "DisposeHttpClient", IsRequired = false, Description = "Specifies whether to dispose the HttpClient (injected HttpClient is never disposed).")] public bool DisposeHttpClient { - get { return Settings.DisposeHttpClient; } - set { Settings.DisposeHttpClient = value; } + get => Settings.DisposeHttpClient; + set => Settings.DisposeHttpClient = value; } [Argument(Name = "ProtectedMethods", IsRequired = false, Description = "List of methods with a protected access modifier ('classname.methodname').")] public string[] ProtectedMethods { - get { return Settings.ProtectedMethods; } - set { Settings.ProtectedMethods = value; } + get => Settings.ProtectedMethods; + set => Settings.ProtectedMethods = value; } [Argument(Name = "GenerateExceptionClasses", IsRequired = false, Description = "Specifies whether to generate exception classes (default: true).")] public bool GenerateExceptionClasses { - get { return Settings.GenerateExceptionClasses; } - set { Settings.GenerateExceptionClasses = value; } + get => Settings.GenerateExceptionClasses; + set => Settings.GenerateExceptionClasses = value; } [Argument(Name = "ExceptionClass", IsRequired = false, Description = "The exception class (default 'SwaggerException', may use '{controller}' placeholder).")] public string ExceptionClass { - get { return Settings.ExceptionClass; } - set { Settings.ExceptionClass = value; } + get => Settings.ExceptionClass; + set => Settings.ExceptionClass = value; } [Argument(Name = "WrapDtoExceptions", IsRequired = false, Description = "Specifies whether DTO exceptions are wrapped in a SwaggerException instance (default: true).")] public bool WrapDtoExceptions { - get { return Settings.WrapDtoExceptions; } - set { Settings.WrapDtoExceptions = value; } + get => Settings.WrapDtoExceptions; + set => Settings.WrapDtoExceptions = value; } [Argument(Name = "UseHttpClientCreationMethod", IsRequired = false, Description = "Specifies whether to call CreateHttpClientAsync on the base class to create a new HttpClient.")] public bool UseHttpClientCreationMethod { - get { return Settings.UseHttpClientCreationMethod; } - set { Settings.UseHttpClientCreationMethod = value; } + get => Settings.UseHttpClientCreationMethod; + set => Settings.UseHttpClientCreationMethod = value; } [Argument(Name = "HttpClientType", IsRequired = false, Description = "Specifies the HttpClient type. By default the 'System.Net.Http.HttpClient' is used.")] public string HttpClientType { - get { return Settings.HttpClientType; } - set { Settings.HttpClientType = value; } + get => Settings.HttpClientType; + set => Settings.HttpClientType = value; } [Argument(Name = "UseHttpRequestMessageCreationMethod", IsRequired = false, Description = "Specifies whether to call CreateHttpRequestMessageAsync on the base class to create a new HttpRequestMethod.")] public bool UseHttpRequestMessageCreationMethod { - get { return Settings.UseHttpRequestMessageCreationMethod; } - set { Settings.UseHttpRequestMessageCreationMethod = value; } + get => Settings.UseHttpRequestMessageCreationMethod; + set => Settings.UseHttpRequestMessageCreationMethod = value; } [Argument(Name = "UseBaseUrl", IsRequired = false, Description = "Specifies whether to use and expose the base URL (default: true).")] public bool UseBaseUrl { - get { return Settings.UseBaseUrl; } - set { Settings.UseBaseUrl = value; } + get => Settings.UseBaseUrl; + set => Settings.UseBaseUrl = value; } [Argument(Name = nameof(GenerateBaseUrlProperty), IsRequired = false, Description = "Specifies whether to generate the BaseUrl property, must be defined on the base class otherwise (default: true).")] public bool GenerateBaseUrlProperty { - get { return Settings.GenerateBaseUrlProperty; } - set { Settings.GenerateBaseUrlProperty = value; } + get => Settings.GenerateBaseUrlProperty; + set => Settings.GenerateBaseUrlProperty = value; } [Argument(Name = "GenerateSyncMethods", IsRequired = false, Description = "Specifies whether to generate synchronous methods (not recommended, default: false).")] public bool GenerateSyncMethods { - get { return Settings.GenerateSyncMethods; } - set { Settings.GenerateSyncMethods = value; } + get => Settings.GenerateSyncMethods; + set => Settings.GenerateSyncMethods = value; } [Argument(Name = "GeneratePrepareRequestAndProcessResponseAsAsyncMethods", IsRequired = false, Description = "Specifies whether to generate PrepareRequest and ProcessResponse methods as asynchronous methods (if true, both must be defined in the base class or in the partial class, default: false).")] public bool GeneratePrepareRequestAndProcessResponseAsAsyncMethods { - get { return Settings.GeneratePrepareRequestAndProcessResponseAsAsyncMethods; } - set { Settings.GeneratePrepareRequestAndProcessResponseAsAsyncMethods = value; } + get => Settings.GeneratePrepareRequestAndProcessResponseAsAsyncMethods; + set => Settings.GeneratePrepareRequestAndProcessResponseAsAsyncMethods = value; } [Argument(Name = nameof(ExposeJsonSerializerSettings), IsRequired = false, Description = "Specifies whether to expose the JsonSerializerSettings property (default: false).")] public bool ExposeJsonSerializerSettings { - get { return Settings.ExposeJsonSerializerSettings; } - set { Settings.ExposeJsonSerializerSettings = value; } + get => Settings.ExposeJsonSerializerSettings; + set => Settings.ExposeJsonSerializerSettings = value; } [Argument(Name = "ClientClassAccessModifier", IsRequired = false, Description = "The client class access modifier (default: public).")] public string ClientClassAccessModifier { - get { return Settings.ClientClassAccessModifier; } - set { Settings.ClientClassAccessModifier = value; } + get => Settings.ClientClassAccessModifier; + set => Settings.ClientClassAccessModifier = value; } [Argument(Name = "TypeAccessModifier", IsRequired = false, Description = "The DTO class/enum access modifier (default: public).")] public string TypeAccessModifier { - get { return Settings.CSharpGeneratorSettings.TypeAccessModifier; } - set { Settings.CSharpGeneratorSettings.TypeAccessModifier = value; } + get => Settings.CSharpGeneratorSettings.TypeAccessModifier; + set => Settings.CSharpGeneratorSettings.TypeAccessModifier = value; } [Argument(Name = "PropertySetterAccessModifier", IsRequired = false, Description = "The access modifier of property setters (default: '').")] public string PropertySetterAccessModifier { - get { return Settings.CSharpGeneratorSettings.PropertySetterAccessModifier; } - set { Settings.CSharpGeneratorSettings.PropertySetterAccessModifier = value; } + get => Settings.CSharpGeneratorSettings.PropertySetterAccessModifier; + set => Settings.CSharpGeneratorSettings.PropertySetterAccessModifier = value; } [Argument(Name = "GenerateNativeRecords", IsRequired = false, Description = "Generate C# 9.0 record types instead of record-like classes (default: false).")] public bool GenerateNativeRecords { - get { return Settings.CSharpGeneratorSettings.GenerateNativeRecords; } - set { Settings.CSharpGeneratorSettings.GenerateNativeRecords = value; } + get => Settings.CSharpGeneratorSettings.GenerateNativeRecords; + set => Settings.CSharpGeneratorSettings.GenerateNativeRecords = value; } [Argument(Name = "GenerateContractsOutput", IsRequired = false, @@ -221,48 +217,48 @@ public bool GenerateNativeRecords Description = "Specifies the format for DateTime type method parameters (default: s).")] public string ParameterDateTimeFormat { - get { return Settings.ParameterDateTimeFormat; } - set { Settings.ParameterDateTimeFormat = value; } + get => Settings.ParameterDateTimeFormat; + set => Settings.ParameterDateTimeFormat = value; } [Argument(Name = "ParameterDateFormat", IsRequired = false, Description = "Specifies the format for Date type method parameters (default: yyyy-MM-dd).")] public string ParameterDateFormat { - get { return Settings.ParameterDateFormat; } - set { Settings.ParameterDateFormat = value; } + get => Settings.ParameterDateFormat; + set => Settings.ParameterDateFormat = value; } [Argument(Name = "GenerateUpdateJsonSerializerSettingsMethod", IsRequired = false, Description = "Generate the UpdateJsonSerializerSettings method (must be implemented in the base class otherwise, default: true).")] public bool GenerateUpdateJsonSerializerSettingsMethod { - get { return Settings.GenerateUpdateJsonSerializerSettingsMethod; } - set { Settings.GenerateUpdateJsonSerializerSettingsMethod = value; } + get => Settings.GenerateUpdateJsonSerializerSettingsMethod; + set => Settings.GenerateUpdateJsonSerializerSettingsMethod = value; } [Argument(Name = "UseRequestAndResponseSerializationSettings", IsRequired = false, Description = "Generate different request and response serialization settings (default: false).")] public bool UseRequestAndResponseSerializationSettings { - get { return Settings.UseRequestAndResponseSerializationSettings; } - set { Settings.UseRequestAndResponseSerializationSettings = value; } + get => Settings.UseRequestAndResponseSerializationSettings; + set => Settings.UseRequestAndResponseSerializationSettings = value; } [Argument(Name = "SerializeTypeInformation", IsRequired = false, Description = "Serialize the type information in a $type property (not recommended, also sets TypeNameHandling = Auto, default: false).")] public bool SerializeTypeInformation { - get { return Settings.SerializeTypeInformation; } - set { Settings.SerializeTypeInformation = value; } + get => Settings.SerializeTypeInformation; + set => Settings.SerializeTypeInformation = value; } [Argument(Name = nameof(QueryNullValue), IsRequired = false, Description = "The null value used for query parameters which are null (default: '').")] public string QueryNullValue { - get { return Settings.QueryNullValue; } - set { Settings.QueryNullValue = value; } + get => Settings.QueryNullValue; + set => Settings.QueryNullValue = value; } public override async Task RunAsync(CommandLineProcessor processor, IConsoleHost host) @@ -299,7 +295,7 @@ private void GenerateImplementation(Dictionary result, CSharpCli { var savedAdditionalNamespaceUsages = Settings.AdditionalNamespaceUsages?.ToArray(); Settings.AdditionalNamespaceUsages = - Settings.AdditionalNamespaceUsages?.Concat(new[] { ContractsNamespace }).ToArray() ?? new[] { ContractsNamespace }; + Settings.AdditionalNamespaceUsages?.Concat([ContractsNamespace]).ToArray() ?? [ContractsNamespace]; result[OutputFilePath ?? "Implementation"] = clientGenerator.GenerateFile(ClientGeneratorOutputType.Implementation); Settings.AdditionalNamespaceUsages = savedAdditionalNamespaceUsages; } diff --git a/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpCommandBase.cs b/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpCommandBase.cs index a4b13b1fb5..914c5ea011 100644 --- a/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpCommandBase.cs +++ b/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpCommandBase.cs @@ -25,109 +25,109 @@ protected OpenApiToCSharpCommandBase(TSettings settings) [Argument(Name = "ClassName", IsRequired = false, Description = "The class name of the generated client.")] public string ClassName { - get { return Settings.ClassName; } - set { Settings.ClassName = value; } + get => Settings.ClassName; + set => Settings.ClassName = value; } [Argument(Name = "OperationGenerationMode", IsRequired = false, Description = "The operation generation mode ('SingleClientFromOperationId' or 'MultipleClientsFromPathSegments').")] public OperationGenerationMode OperationGenerationMode { - get { return OperationGenerationModeConverter.GetOperationGenerationMode(Settings.OperationNameGenerator); } - set { Settings.OperationNameGenerator = OperationGenerationModeConverter.GetOperationNameGenerator(value); } + get => OperationGenerationModeConverter.GetOperationGenerationMode(Settings.OperationNameGenerator); + set => Settings.OperationNameGenerator = OperationGenerationModeConverter.GetOperationNameGenerator(value); } [Argument(Name = "AdditionalNamespaceUsages", IsRequired = false, Description = "The additional namespace usages.")] public string[] AdditionalNamespaceUsages { - get { return Settings.AdditionalNamespaceUsages; } - set { Settings.AdditionalNamespaceUsages = value; } + get => Settings.AdditionalNamespaceUsages; + set => Settings.AdditionalNamespaceUsages = value; } [Argument(Name = "AdditionalContractNamespaceUsages", IsRequired = false, Description = "The additional contract namespace usages.")] public string[] AdditionalContractNamespaceUsages { - get { return Settings.AdditionalContractNamespaceUsages; } - set { Settings.AdditionalContractNamespaceUsages = value; } + get => Settings.AdditionalContractNamespaceUsages; + set => Settings.AdditionalContractNamespaceUsages = value; } [Argument(Name = "GenerateOptionalParameters", IsRequired = false, Description = "Specifies whether to reorder parameters (required first, optional at the end) and generate optional parameters (default: false).")] public bool GenerateOptionalParameters { - get { return Settings.GenerateOptionalParameters; } - set { Settings.GenerateOptionalParameters = value; } + get => Settings.GenerateOptionalParameters; + set => Settings.GenerateOptionalParameters = value; } [Argument(Name = "GenerateJsonMethods", IsRequired = false, Description = "Specifies whether to render ToJson() and FromJson() methods for DTOs (default: true).")] public bool GenerateJsonMethods { - get { return Settings.CSharpGeneratorSettings.GenerateJsonMethods; } - set { Settings.CSharpGeneratorSettings.GenerateJsonMethods = value; } + get => Settings.CSharpGeneratorSettings.GenerateJsonMethods; + set => Settings.CSharpGeneratorSettings.GenerateJsonMethods = value; } [Argument(Name = "EnforceFlagEnums", IsRequired = false, Description = "Specifies whether enums should be always generated as bit flags (default: false).")] public bool EnforceFlagEnums { - get { return Settings.CSharpGeneratorSettings.EnforceFlagEnums; } - set { Settings.CSharpGeneratorSettings.EnforceFlagEnums = value; } + get => Settings.CSharpGeneratorSettings.EnforceFlagEnums; + set => Settings.CSharpGeneratorSettings.EnforceFlagEnums = value; } [Argument(Name = "ParameterArrayType", IsRequired = false, Description = "The generic array .NET type of operation parameters (default: 'IEnumerable').")] public string ParameterArrayType { - get { return Settings.ParameterArrayType; } - set { Settings.ParameterArrayType = value; } + get => Settings.ParameterArrayType; + set => Settings.ParameterArrayType = value; } [Argument(Name = "ParameterDictionaryType", IsRequired = false, Description = "The generic dictionary .NET type of operation parameters (default: 'IDictionary').")] public string ParameterDictionaryType { - get { return Settings.ParameterDictionaryType; } - set { Settings.ParameterDictionaryType = value; } + get => Settings.ParameterDictionaryType; + set => Settings.ParameterDictionaryType = value; } [Argument(Name = "ResponseArrayType", IsRequired = false, Description = "The generic array .NET type of operation responses (default: 'ICollection').")] public string ResponseArrayType { - get { return Settings.ResponseArrayType; } - set { Settings.ResponseArrayType = value; } + get => Settings.ResponseArrayType; + set => Settings.ResponseArrayType = value; } [Argument(Name = "ResponseDictionaryType", IsRequired = false, Description = "The generic dictionary .NET type of operation responses (default: 'IDictionary').")] public string ResponseDictionaryType { - get { return Settings.ResponseDictionaryType; } - set { Settings.ResponseDictionaryType = value; } + get => Settings.ResponseDictionaryType; + set => Settings.ResponseDictionaryType = value; } [Argument(Name = "WrapResponses", IsRequired = false, Description = "Specifies whether to wrap success responses to allow full response access.")] public bool WrapResponses { - get { return Settings.WrapResponses; } - set { Settings.WrapResponses = value; } + get => Settings.WrapResponses; + set => Settings.WrapResponses = value; } [Argument(Name = "WrapResponseMethods", IsRequired = false, Description = "List of methods where responses are wrapped ('ControllerName.MethodName', WrapResponses must be true).")] public string[] WrapResponseMethods { - get { return Settings.WrapResponseMethods; } - set { Settings.WrapResponseMethods = value; } + get => Settings.WrapResponseMethods; + set => Settings.WrapResponseMethods = value; } [Argument(Name = "GenerateResponseClasses", IsRequired = false, Description = "Specifies whether to generate response classes (default: true).")] public bool GenerateResponseClasses { - get { return Settings.GenerateResponseClasses; } - set { Settings.GenerateResponseClasses = value; } + get => Settings.GenerateResponseClasses; + set => Settings.GenerateResponseClasses = value; } [Argument(Name = "ResponseClass", IsRequired = false, Description = "The response class (default 'SwaggerResponse', may use '{controller}' placeholder).")] public string ResponseClass { - get { return Settings.ResponseClass; } - set { Settings.ResponseClass = value; } + get => Settings.ResponseClass; + set => Settings.ResponseClass = value; } // CSharpGeneratorSettings @@ -135,224 +135,224 @@ public string ResponseClass [Argument(Name = "Namespace", Description = "The namespace of the generated classes.")] public string Namespace { - get { return Settings.CSharpGeneratorSettings.Namespace; } - set { Settings.CSharpGeneratorSettings.Namespace = value; } + get => Settings.CSharpGeneratorSettings.Namespace; + set => Settings.CSharpGeneratorSettings.Namespace = value; } [Argument(Name = "RequiredPropertiesMustBeDefined", IsRequired = false, Description = "Specifies whether a required property must be defined in JSON (sets Required.Always when the property is required).")] public bool RequiredPropertiesMustBeDefined { - get { return Settings.CSharpGeneratorSettings.RequiredPropertiesMustBeDefined; } - set { Settings.CSharpGeneratorSettings.RequiredPropertiesMustBeDefined = value; } + get => Settings.CSharpGeneratorSettings.RequiredPropertiesMustBeDefined; + set => Settings.CSharpGeneratorSettings.RequiredPropertiesMustBeDefined = value; } [Argument(Name = "DateType", IsRequired = false, Description = "The date .NET type (default: 'DateTimeOffset').")] public string DateType { - get { return Settings.CSharpGeneratorSettings.DateType; } - set { Settings.CSharpGeneratorSettings.DateType = value; } + get => Settings.CSharpGeneratorSettings.DateType; + set => Settings.CSharpGeneratorSettings.DateType = value; } [Argument(Name = "JsonConverters", IsRequired = false, Description = "Specifies the custom Json.NET converter types (optional, comma separated).")] public string[] JsonConverters { - get { return Settings.CSharpGeneratorSettings.JsonConverters; } - set { Settings.CSharpGeneratorSettings.JsonConverters = value; } + get => Settings.CSharpGeneratorSettings.JsonConverters; + set => Settings.CSharpGeneratorSettings.JsonConverters = value; } [Argument(Name = "AnyType", IsRequired = false, Description = "The any .NET type (default: 'object').")] public string AnyType { - get { return Settings.CSharpGeneratorSettings.AnyType; } - set { Settings.CSharpGeneratorSettings.AnyType = value; } + get => Settings.CSharpGeneratorSettings.AnyType; + set => Settings.CSharpGeneratorSettings.AnyType = value; } [Argument(Name = "DateTimeType", IsRequired = false, Description = "The date time .NET type (default: 'DateTimeOffset').")] public string DateTimeType { - get { return Settings.CSharpGeneratorSettings.DateTimeType; } - set { Settings.CSharpGeneratorSettings.DateTimeType = value; } + get => Settings.CSharpGeneratorSettings.DateTimeType; + set => Settings.CSharpGeneratorSettings.DateTimeType = value; } [Argument(Name = "TimeType", IsRequired = false, Description = "The time .NET type (default: 'TimeSpan').")] public string TimeType { - get { return Settings.CSharpGeneratorSettings.TimeType; } - set { Settings.CSharpGeneratorSettings.TimeType = value; } + get => Settings.CSharpGeneratorSettings.TimeType; + set => Settings.CSharpGeneratorSettings.TimeType = value; } [Argument(Name = "TimeSpanType", IsRequired = false, Description = "The time span .NET type (default: 'TimeSpan').")] public string TimeSpanType { - get { return Settings.CSharpGeneratorSettings.TimeSpanType; } - set { Settings.CSharpGeneratorSettings.TimeSpanType = value; } + get => Settings.CSharpGeneratorSettings.TimeSpanType; + set => Settings.CSharpGeneratorSettings.TimeSpanType = value; } [Argument(Name = "ArrayType", IsRequired = false, Description = "The generic array .NET type (default: 'ICollection').")] public string ArrayType { - get { return Settings.CSharpGeneratorSettings.ArrayType; } - set { Settings.CSharpGeneratorSettings.ArrayType = value; } + get => Settings.CSharpGeneratorSettings.ArrayType; + set => Settings.CSharpGeneratorSettings.ArrayType = value; } [Argument(Name = "ArrayInstanceType", IsRequired = false, Description = "The generic array .NET instance type (default: empty = ArrayType).")] public string ArrayInstanceType { - get { return Settings.CSharpGeneratorSettings.ArrayInstanceType; } - set { Settings.CSharpGeneratorSettings.ArrayInstanceType = value; } + get => Settings.CSharpGeneratorSettings.ArrayInstanceType; + set => Settings.CSharpGeneratorSettings.ArrayInstanceType = value; } [Argument(Name = "DictionaryType", IsRequired = false, Description = "The generic dictionary .NET type (default: 'IDictionary').")] public string DictionaryType { - get { return Settings.CSharpGeneratorSettings.DictionaryType; } - set { Settings.CSharpGeneratorSettings.DictionaryType = value; } + get => Settings.CSharpGeneratorSettings.DictionaryType; + set => Settings.CSharpGeneratorSettings.DictionaryType = value; } [Argument(Name = "DictionaryInstanceType", IsRequired = false, Description = "The generic dictionary .NET instance type (default: empty = DictionaryType).")] public string DictionaryInstanceType { - get { return Settings.CSharpGeneratorSettings.DictionaryInstanceType; } - set { Settings.CSharpGeneratorSettings.DictionaryInstanceType = value; } + get => Settings.CSharpGeneratorSettings.DictionaryInstanceType; + set => Settings.CSharpGeneratorSettings.DictionaryInstanceType = value; } [Argument(Name = "ArrayBaseType", IsRequired = false, Description = "The generic array .NET type (default: 'Collection').")] public string ArrayBaseType { - get { return Settings.CSharpGeneratorSettings.ArrayBaseType; } - set { Settings.CSharpGeneratorSettings.ArrayBaseType = value; } + get => Settings.CSharpGeneratorSettings.ArrayBaseType; + set => Settings.CSharpGeneratorSettings.ArrayBaseType = value; } [Argument(Name = "DictionaryBaseType", IsRequired = false, Description = "The generic dictionary .NET type (default: 'Dictionary').")] public string DictionaryBaseType { - get { return Settings.CSharpGeneratorSettings.DictionaryBaseType; } - set { Settings.CSharpGeneratorSettings.DictionaryBaseType = value; } + get => Settings.CSharpGeneratorSettings.DictionaryBaseType; + set => Settings.CSharpGeneratorSettings.DictionaryBaseType = value; } [Argument(Name = "ClassStyle", IsRequired = false, Description = "The CSharp class style, 'Poco' or 'Inpc' (default: 'Poco').")] public CSharpClassStyle ClassStyle { - get { return Settings.CSharpGeneratorSettings.ClassStyle; } - set { Settings.CSharpGeneratorSettings.ClassStyle = value; } + get => Settings.CSharpGeneratorSettings.ClassStyle; + set => Settings.CSharpGeneratorSettings.ClassStyle = value; } [Argument(Name = "JsonLibrary", IsRequired = false, Description = "The CSharp JSON library, 'NewtonsoftJson' or 'SystemTextJson' (default: 'NewtonsoftJson', 'SystemTextJson' is experimental).")] public CSharpJsonLibrary JsonLibrary { - get { return Settings.CSharpGeneratorSettings.JsonLibrary; } - set { Settings.CSharpGeneratorSettings.JsonLibrary = value; } + get => Settings.CSharpGeneratorSettings.JsonLibrary; + set => Settings.CSharpGeneratorSettings.JsonLibrary = value; } [Argument(Name = "GenerateDefaultValues", IsRequired = false, Description = "Specifies whether to generate default values for properties (may generate CSharp 6 code, default: true).")] public bool GenerateDefaultValues { - get { return Settings.CSharpGeneratorSettings.GenerateDefaultValues; } - set { Settings.CSharpGeneratorSettings.GenerateDefaultValues = value; } + get => Settings.CSharpGeneratorSettings.GenerateDefaultValues; + set => Settings.CSharpGeneratorSettings.GenerateDefaultValues = value; } [Argument(Name = "GenerateDataAnnotations", IsRequired = false, Description = "Specifies whether to generate data annotation attributes on DTO classes (default: true).")] public bool GenerateDataAnnotations { - get { return Settings.CSharpGeneratorSettings.GenerateDataAnnotations; } - set { Settings.CSharpGeneratorSettings.GenerateDataAnnotations = value; } + get => Settings.CSharpGeneratorSettings.GenerateDataAnnotations; + set => Settings.CSharpGeneratorSettings.GenerateDataAnnotations = value; } [Argument(Name = "ExcludedTypeNames", IsRequired = false, Description = "The excluded DTO type names (must be defined in an import or other namespace).")] public string[] ExcludedTypeNames { - get { return Settings.CSharpGeneratorSettings.ExcludedTypeNames; } - set { Settings.CSharpGeneratorSettings.ExcludedTypeNames = value; } + get => Settings.CSharpGeneratorSettings.ExcludedTypeNames; + set => Settings.CSharpGeneratorSettings.ExcludedTypeNames = value; } [Argument(Name = "ExcludedParameterNames", IsRequired = false, Description = "The globally excluded parameter names.")] public string[] ExcludedParameterNames { - get { return Settings.ExcludedParameterNames; } - set { Settings.ExcludedParameterNames = value; } + get => Settings.ExcludedParameterNames; + set => Settings.ExcludedParameterNames = value; } [Argument(Name = "HandleReferences", IsRequired = false, Description = "Use preserve references handling (All) in the JSON serializer (default: false).")] public bool HandleReferences { - get { return Settings.CSharpGeneratorSettings.HandleReferences; } - set { Settings.CSharpGeneratorSettings.HandleReferences = value; } + get => Settings.CSharpGeneratorSettings.HandleReferences; + set => Settings.CSharpGeneratorSettings.HandleReferences = value; } [Argument(Name = "GenerateImmutableArrayProperties", IsRequired = false, Description = "Specifies whether to remove the setter for non-nullable array properties (default: false).")] public bool GenerateImmutableArrayProperties { - get { return Settings.CSharpGeneratorSettings.GenerateImmutableArrayProperties; } - set { Settings.CSharpGeneratorSettings.GenerateImmutableArrayProperties = value; } + get => Settings.CSharpGeneratorSettings.GenerateImmutableArrayProperties; + set => Settings.CSharpGeneratorSettings.GenerateImmutableArrayProperties = value; } [Argument(Name = "GenerateImmutableDictionaryProperties", IsRequired = false, Description = "Specifies whether to remove the setter for non-nullable dictionary properties (default: false).")] public bool GenerateImmutableDictionaryProperties { - get { return Settings.CSharpGeneratorSettings.GenerateImmutableDictionaryProperties; } - set { Settings.CSharpGeneratorSettings.GenerateImmutableDictionaryProperties = value; } + get => Settings.CSharpGeneratorSettings.GenerateImmutableDictionaryProperties; + set => Settings.CSharpGeneratorSettings.GenerateImmutableDictionaryProperties = value; } [Argument(Name = "JsonSerializerSettingsTransformationMethod", IsRequired = false, Description = "The name of a static method which is called to transform the JsonSerializerSettings used in the generated ToJson()/FromJson() methods (default: none).")] public string JsonSerializerSettingsTransformationMethod { - get { return Settings.CSharpGeneratorSettings.JsonSerializerSettingsTransformationMethod; } - set { Settings.CSharpGeneratorSettings.JsonSerializerSettingsTransformationMethod = value; } + get => Settings.CSharpGeneratorSettings.JsonSerializerSettingsTransformationMethod; + set => Settings.CSharpGeneratorSettings.JsonSerializerSettingsTransformationMethod = value; } [Argument(Name = "InlineNamedArrays", Description = "Inline named arrays (default: false).", IsRequired = false)] public bool InlineNamedArrays { - get { return Settings.CSharpGeneratorSettings.InlineNamedArrays; } - set { Settings.CSharpGeneratorSettings.InlineNamedArrays = value; } + get => Settings.CSharpGeneratorSettings.InlineNamedArrays; + set => Settings.CSharpGeneratorSettings.InlineNamedArrays = value; } [Argument(Name = "InlineNamedDictionaries", Description = "Inline named dictionaries (default: false).", IsRequired = false)] public bool InlineNamedDictionaries { - get { return Settings.CSharpGeneratorSettings.InlineNamedDictionaries; } - set { Settings.CSharpGeneratorSettings.InlineNamedDictionaries = value; } + get => Settings.CSharpGeneratorSettings.InlineNamedDictionaries; + set => Settings.CSharpGeneratorSettings.InlineNamedDictionaries = value; } [Argument(Name = "InlineNamedTuples", Description = "Inline named tuples (default: true).", IsRequired = false)] public bool InlineNamedTuples { - get { return Settings.CSharpGeneratorSettings.InlineNamedTuples; } - set { Settings.CSharpGeneratorSettings.InlineNamedTuples = value; } + get => Settings.CSharpGeneratorSettings.InlineNamedTuples; + set => Settings.CSharpGeneratorSettings.InlineNamedTuples = value; } [Argument(Name = "InlineNamedAny", Description = "Inline named any types (default: false).", IsRequired = false)] public bool InlineNamedAny { - get { return Settings.CSharpGeneratorSettings.InlineNamedAny; } - set { Settings.CSharpGeneratorSettings.InlineNamedAny = value; } + get => Settings.CSharpGeneratorSettings.InlineNamedAny; + set => Settings.CSharpGeneratorSettings.InlineNamedAny = value; } [Argument(Name = "GenerateDtoTypes", IsRequired = false, Description = "Specifies whether to generate DTO classes.")] public bool GenerateDtoTypes { - get { return Settings.GenerateDtoTypes; } - set { Settings.GenerateDtoTypes = value; } + get => Settings.GenerateDtoTypes; + set => Settings.GenerateDtoTypes = value; } [Argument(Name = "GenerateOptionalPropertiesAsNullable", IsRequired = false, Description = "Specifies whether optional schema properties " + "(not required) are generated as nullable properties (default: false).")] public bool GenerateOptionalPropertiesAsNullable { - get { return Settings.CSharpGeneratorSettings.GenerateOptionalPropertiesAsNullable; } - set { Settings.CSharpGeneratorSettings.GenerateOptionalPropertiesAsNullable = value; } + get => Settings.CSharpGeneratorSettings.GenerateOptionalPropertiesAsNullable; + set => Settings.CSharpGeneratorSettings.GenerateOptionalPropertiesAsNullable = value; } [Argument(Name = "GenerateNullableReferenceTypes", IsRequired = false, Description = "Specifies whether whether to " + "generate Nullable Reference Type annotations (default: false).")] public bool GenerateNullableReferenceTypes { - get { return Settings.CSharpGeneratorSettings.GenerateNullableReferenceTypes; } - set { Settings.CSharpGeneratorSettings.GenerateNullableReferenceTypes = value; } + get => Settings.CSharpGeneratorSettings.GenerateNullableReferenceTypes; + set => Settings.CSharpGeneratorSettings.GenerateNullableReferenceTypes = value; } } } diff --git a/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpControllerCommand.cs b/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpControllerCommand.cs index 3fea5b27ac..6be66fdfef 100644 --- a/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpControllerCommand.cs +++ b/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpControllerCommand.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Threading.Tasks; using NConsole; using NSwag.CodeGeneration.CSharp; using NSwag.CodeGeneration.CSharp.Models; @@ -26,57 +24,57 @@ public OpenApiToCSharpControllerCommand() : base(new CSharpControllerGeneratorSe [Argument(Name = "ControllerBaseClass", Description = "The controller base class (empty for 'ApiController').", IsRequired = false)] public string ControllerBaseClass { - get { return Settings.ControllerBaseClass; } - set { Settings.ControllerBaseClass = value; } + get => Settings.ControllerBaseClass; + set => Settings.ControllerBaseClass = value; } [Argument(Name = "ControllerStyle", Description = "The controller generation style (partial, abstract; default: partial).", IsRequired = false)] public CSharpControllerStyle ControllerStyle { - get { return Settings.ControllerStyle; } - set { Settings.ControllerStyle = value; } + get => Settings.ControllerStyle; + set => Settings.ControllerStyle = value; } [Argument(Name = "ControllerTarget", Description = "controller target framework (default: AspNetCore).", IsRequired = false)] public CSharpControllerTarget ControllerTarget { - get { return Settings.ControllerTarget; } - set { Settings.ControllerTarget = value; } + get => Settings.ControllerTarget; + set => Settings.ControllerTarget = value; } [Argument(Name = "UseCancellationToken", Description = "Add a cancellation token parameter (default: false).", IsRequired = false)] public bool UseCancellationToken { - get { return Settings.UseCancellationToken; } - set { Settings.UseCancellationToken = value; } + get => Settings.UseCancellationToken; + set => Settings.UseCancellationToken = value; } [Argument(Name = "UseActionResultType", Description = "Use ASP.Net Core (2.1) ActionResult type as return type (default: false)", IsRequired = false)] public bool UseActionResultType { - get { return Settings.UseActionResultType; } - set { Settings.UseActionResultType = value; } + get => Settings.UseActionResultType; + set => Settings.UseActionResultType = value; } [Argument(Name = "GenerateModelValidationAttributes", Description = "Add model validation attributes (default: false).", IsRequired = false)] public bool GenerateModelValidationAttributes { - get { return Settings.GenerateModelValidationAttributes; } - set { Settings.GenerateModelValidationAttributes = value; } + get => Settings.GenerateModelValidationAttributes; + set => Settings.GenerateModelValidationAttributes = value; } [Argument(Name = "RouteNamingStrategy", Description = "The strategy for naming controller routes (none, operationid; default: none).", IsRequired = false)] public CSharpControllerRouteNamingStrategy RouteNamingStrategy { - get { return Settings.RouteNamingStrategy; } - set { Settings.RouteNamingStrategy = value; } + get => Settings.RouteNamingStrategy; + set => Settings.RouteNamingStrategy = value; } [Argument(Name = "BasePath", Description = "The Base path on which the API is served, which is relative to the Host", IsRequired = false)] public string BasePath { - get { return Settings.BasePath; } - set { Settings.BasePath = value; } + get => Settings.BasePath; + set => Settings.BasePath = value; } public override async Task RunAsync(CommandLineProcessor processor, IConsoleHost host) diff --git a/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToTypeScriptClientCommand.cs b/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToTypeScriptClientCommand.cs index 0368d784ae..01d96e0132 100644 --- a/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToTypeScriptClientCommand.cs +++ b/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToTypeScriptClientCommand.cs @@ -6,12 +6,8 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.IO; -using System.Threading.Tasks; using NConsole; using NJsonSchema.CodeGeneration.TypeScript; -using NJsonSchema.Infrastructure; using NSwag.CodeGeneration.TypeScript; #pragma warning disable 1591 @@ -29,262 +25,262 @@ public OpenApiToTypeScriptClientCommand() [Argument(Name = "ClassName", IsRequired = false, Description = "The class name of the generated client.")] public string ClassName { - get { return Settings.ClassName; } - set { Settings.ClassName = value; } + get => Settings.ClassName; + set => Settings.ClassName = value; } [Argument(Name = "ModuleName", IsRequired = false, Description = "The TypeScript module name (default: '', no module).")] public string ModuleName { - get { return Settings.TypeScriptGeneratorSettings.ModuleName; } - set { Settings.TypeScriptGeneratorSettings.ModuleName = value; } + get => Settings.TypeScriptGeneratorSettings.ModuleName; + set => Settings.TypeScriptGeneratorSettings.ModuleName = value; } [Argument(Name = "Namespace", IsRequired = false, Description = "The TypeScript namespace (default: '', no namespace).")] public string Namespace { - get { return Settings.TypeScriptGeneratorSettings.Namespace; } - set { Settings.TypeScriptGeneratorSettings.Namespace = value; } + get => Settings.TypeScriptGeneratorSettings.Namespace; + set => Settings.TypeScriptGeneratorSettings.Namespace = value; } [Argument(Name = "TypeScriptVersion", IsRequired = false, Description = "The target TypeScript version (default: 2.7).")] public decimal TypeScriptVersion { - get { return Settings.TypeScriptGeneratorSettings.TypeScriptVersion; } - set { Settings.TypeScriptGeneratorSettings.TypeScriptVersion = value; } + get => Settings.TypeScriptGeneratorSettings.TypeScriptVersion; + set => Settings.TypeScriptGeneratorSettings.TypeScriptVersion = value; } [Argument(Name = "Template", IsRequired = false, Description = "The type of the asynchronism handling " + "('JQueryCallbacks', 'JQueryPromises', 'AngularJS', 'Angular', 'Fetch', 'Aurelia').")] public TypeScriptTemplate Template { - get { return Settings.Template; } - set { Settings.Template = value; } + get => Settings.Template; + set => Settings.Template = value; } [Argument(Name = "PromiseType", IsRequired = false, Description = "The promise type ('Promise' or 'QPromise').")] public PromiseType PromiseType { - get { return Settings.PromiseType; } - set { Settings.PromiseType = value; } + get => Settings.PromiseType; + set => Settings.PromiseType = value; } [Argument(Name = "HttpClass", IsRequired = false, Description = "The Angular HTTP service class (default 'Http', 'HttpClient').")] public HttpClass HttpClass { - get { return Settings.HttpClass; } - set { Settings.HttpClass = value; } + get => Settings.HttpClass; + set => Settings.HttpClass = value; } [Argument(Name = "WithCredentials", IsRequired = false, Description = "The Angular HttpClient will send withCredentials: true in http requests (default: false).")] public bool WithCredentials { - get { return Settings.WithCredentials; } - set { Settings.WithCredentials = value; } + get => Settings.WithCredentials; + set => Settings.WithCredentials = value; } [Argument(Name = "UseSingletonProvider", IsRequired = false, Description = "Specifies whether to use the Angular 6 Singleton Provider (Angular template only, default: false).")] public bool UseSingletonProvider { - get { return Settings.UseSingletonProvider; } - set { Settings.UseSingletonProvider = value; } + get => Settings.UseSingletonProvider; + set => Settings.UseSingletonProvider = value; } [Argument(Name = "InjectionTokenType", IsRequired = false, Description = "The Angular injection token type (default 'InjectionToken', 'OpaqueToken').")] public InjectionTokenType InjectionTokenType { - get { return Settings.InjectionTokenType; } - set { Settings.InjectionTokenType = value; } + get => Settings.InjectionTokenType; + set => Settings.InjectionTokenType = value; } [Argument(Name = "RxJsVersion", IsRequired = false, Description = "The target RxJs version (default: 6.0).")] public decimal RxJsVersion { - get { return Settings.RxJsVersion; } - set { Settings.RxJsVersion = value; } + get => Settings.RxJsVersion; + set => Settings.RxJsVersion = value; } [Argument(Name = "DateTimeType", IsRequired = false, Description = "The date time type ('Date', 'MomentJS', 'Luxon', 'DayJS', 'OffsetMomentJS', 'string').")] public TypeScriptDateTimeType DateTimeType { - get { return Settings.TypeScriptGeneratorSettings.DateTimeType; } - set { Settings.TypeScriptGeneratorSettings.DateTimeType = value; } + get => Settings.TypeScriptGeneratorSettings.DateTimeType; + set => Settings.TypeScriptGeneratorSettings.DateTimeType = value; } [Argument(Name = "NullValue", IsRequired = false, Description = "The null value used in object initializers (default 'Undefined', 'Null').")] public TypeScriptNullValue NullValue { - get { return Settings.TypeScriptGeneratorSettings.NullValue; } - set { Settings.TypeScriptGeneratorSettings.NullValue = value; } + get => Settings.TypeScriptGeneratorSettings.NullValue; + set => Settings.TypeScriptGeneratorSettings.NullValue = value; } [Argument(Name = "GenerateClientClasses", IsRequired = false, Description = "Specifies whether generate client classes.")] public bool GenerateClientClasses { - get { return Settings.GenerateClientClasses; } - set { Settings.GenerateClientClasses = value; } + get => Settings.GenerateClientClasses; + set => Settings.GenerateClientClasses = value; } [Argument(Name = "GenerateClientInterfaces", IsRequired = false, Description = "Specifies whether generate interfaces for the client classes (default: false).")] public bool GenerateClientInterfaces { - get { return Settings.GenerateClientInterfaces; } - set { Settings.GenerateClientInterfaces = value; } + get => Settings.GenerateClientInterfaces; + set => Settings.GenerateClientInterfaces = value; } [Argument(Name = "GenerateOptionalParameters", IsRequired = false, Description = "Specifies whether to reorder parameters (required first, optional at the end) and generate optional parameters (default: false).")] public bool GenerateOptionalParameters { - get { return Settings.GenerateOptionalParameters; } - set { Settings.GenerateOptionalParameters = value; } + get => Settings.GenerateOptionalParameters; + set => Settings.GenerateOptionalParameters = value; } [Argument(Name = "ExportTypes", IsRequired = false, Description = "Specifies whether the export keyword should be added to all classes, interfaces and enums (default: true).")] public bool ExportTypes { - get { return Settings.TypeScriptGeneratorSettings.ExportTypes; } - set { Settings.TypeScriptGeneratorSettings.ExportTypes = value; } + get => Settings.TypeScriptGeneratorSettings.ExportTypes; + set => Settings.TypeScriptGeneratorSettings.ExportTypes = value; } [Argument(Name = "WrapDtoExceptions", IsRequired = false, Description = "Specifies whether DTO exceptions are wrapped in a SwaggerException instance (default: false).")] public bool WrapDtoExceptions { - get { return Settings.WrapDtoExceptions; } - set { Settings.WrapDtoExceptions = value; } + get => Settings.WrapDtoExceptions; + set => Settings.WrapDtoExceptions = value; } [Argument(Name = "ExceptionClass", IsRequired = false, Description = "The exception class (default 'ApiException').")] public string ExceptionClass { - get { return Settings.ExceptionClass; } - set { Settings.ExceptionClass = value; } + get => Settings.ExceptionClass; + set => Settings.ExceptionClass = value; } [Argument(Name = "ClientBaseClass", IsRequired = false, Description = "The base class of the generated client classes (optional, must be imported or implemented in the extension code).")] public string ClientBaseClass { - get { return Settings.ClientBaseClass; } - set { Settings.ClientBaseClass = value; } + get => Settings.ClientBaseClass; + set => Settings.ClientBaseClass = value; } [Argument(Name = "WrapResponses", IsRequired = false, Description = "Specifies whether to wrap success responses to allow full response access (experimental).")] public bool WrapResponses { - get { return Settings.WrapResponses; } - set { Settings.WrapResponses = value; } + get => Settings.WrapResponses; + set => Settings.WrapResponses = value; } [Argument(Name = "WrapResponseMethods", IsRequired = false, Description = "List of methods where responses are wrapped ('ControllerName.MethodName', WrapResponses must be true).")] public string[] WrapResponseMethods { - get { return Settings.WrapResponseMethods; } - set { Settings.WrapResponseMethods = value; } + get => Settings.WrapResponseMethods; + set => Settings.WrapResponseMethods = value; } [Argument(Name = "GenerateResponseClasses", IsRequired = false, Description = "Specifies whether to generate response classes (default: true).")] public bool GenerateResponseClasses { - get { return Settings.GenerateResponseClasses; } - set { Settings.GenerateResponseClasses = value; } + get => Settings.GenerateResponseClasses; + set => Settings.GenerateResponseClasses = value; } [Argument(Name = "ResponseClass", IsRequired = false, Description = "The response class (default 'SwaggerResponse', may use '{controller}' placeholder).")] public string ResponseClass { - get { return Settings.ResponseClass; } - set { Settings.ResponseClass = value; } + get => Settings.ResponseClass; + set => Settings.ResponseClass = value; } [Argument(Name = "ProtectedMethods", IsRequired = false, Description = "List of methods with a protected access modifier ('classname.methodname').")] public string[] ProtectedMethods { - get { return Settings.ProtectedMethods; } - set { Settings.ProtectedMethods = value; } + get => Settings.ProtectedMethods; + set => Settings.ProtectedMethods = value; } [Argument(Name = "ConfigurationClass", IsRequired = false, Description = "The configuration class. The setting ClientBaseClass must be set. (empty for no configuration class).")] public string ConfigurationClass { - get { return Settings.ConfigurationClass; } - set { Settings.ConfigurationClass = value; } + get => Settings.ConfigurationClass; + set => Settings.ConfigurationClass = value; } [Argument(Name = "UseTransformOptionsMethod", IsRequired = false, Description = "Call 'transformOptions' on the base class or extension class (default: false).")] public bool UseTransformOptionsMethod { - get { return Settings.UseTransformOptionsMethod; } - set { Settings.UseTransformOptionsMethod = value; } + get => Settings.UseTransformOptionsMethod; + set => Settings.UseTransformOptionsMethod = value; } [Argument(Name = "UseTransformResultMethod", IsRequired = false, Description = "Call 'transformResult' on the base class or extension class (default: false).")] public bool UseTransformResultMethod { - get { return Settings.UseTransformResultMethod; } - set { Settings.UseTransformResultMethod = value; } + get => Settings.UseTransformResultMethod; + set => Settings.UseTransformResultMethod = value; } [Argument(Name = "GenerateDtoTypes", IsRequired = false, Description = "Specifies whether to generate DTO classes.")] public bool GenerateDtoTypes { - get { return Settings.GenerateDtoTypes; } - set { Settings.GenerateDtoTypes = value; } + get => Settings.GenerateDtoTypes; + set => Settings.GenerateDtoTypes = value; } [Argument(Name = "OperationGenerationMode", IsRequired = false, Description = "The operation generation mode ('SingleClientFromOperationId' or 'MultipleClientsFromPathSegments').")] public OperationGenerationMode OperationGenerationMode { - get { return OperationGenerationModeConverter.GetOperationGenerationMode(Settings.OperationNameGenerator); } - set { Settings.OperationNameGenerator = OperationGenerationModeConverter.GetOperationNameGenerator(value); } + get => OperationGenerationModeConverter.GetOperationGenerationMode(Settings.OperationNameGenerator); + set => Settings.OperationNameGenerator = OperationGenerationModeConverter.GetOperationNameGenerator(value); } [Argument(Name = "MarkOptionalProperties", IsRequired = false, Description = "Specifies whether to mark optional properties with ? (default: false).")] public bool MarkOptionalProperties { - get { return Settings.TypeScriptGeneratorSettings.MarkOptionalProperties; } - set { Settings.TypeScriptGeneratorSettings.MarkOptionalProperties = value; } + get => Settings.TypeScriptGeneratorSettings.MarkOptionalProperties; + set => Settings.TypeScriptGeneratorSettings.MarkOptionalProperties = value; } [Argument(Name = "GenerateCloneMethod", IsRequired = false, Description = "Specifies whether a clone() method should be generated in the DTO classes (default: false).")] public bool GenerateCloneMethod { - get { return Settings.TypeScriptGeneratorSettings.GenerateCloneMethod; } - set { Settings.TypeScriptGeneratorSettings.GenerateCloneMethod = value; } + get => Settings.TypeScriptGeneratorSettings.GenerateCloneMethod; + set => Settings.TypeScriptGeneratorSettings.GenerateCloneMethod = value; } [Argument(Name = "TypeStyle", IsRequired = false, Description = "The type style (default: Class).")] public TypeScriptTypeStyle TypeStyle { - get { return Settings.TypeScriptGeneratorSettings.TypeStyle; } - set { Settings.TypeScriptGeneratorSettings.TypeStyle = value; } + get => Settings.TypeScriptGeneratorSettings.TypeStyle; + set => Settings.TypeScriptGeneratorSettings.TypeStyle = value; } [Argument(Name = "EnumStyle", IsRequired = false, Description = "The enum style (Enum or StringLiteral, default: Enum).")] public TypeScriptEnumStyle EnumStyle { - get { return Settings.TypeScriptGeneratorSettings.EnumStyle; } - set { Settings.TypeScriptGeneratorSettings.EnumStyle = value; } + get => Settings.TypeScriptGeneratorSettings.EnumStyle; + set => Settings.TypeScriptGeneratorSettings.EnumStyle = value; } [Argument(Name = "UseLeafType", IsRequired = false, Description = "Generate leaf types for an object with discriminator (default: false).")] public bool UseLeafType { - get { return Settings.TypeScriptGeneratorSettings.UseLeafType; } - set { Settings.TypeScriptGeneratorSettings.UseLeafType = value; } + get => Settings.TypeScriptGeneratorSettings.UseLeafType; + set => Settings.TypeScriptGeneratorSettings.UseLeafType = value; } [Argument(Name = "ClassTypes", IsRequired = false, Description = "The type names which always generate plain TypeScript classes.")] public string[] ClassTypes { - get { return Settings.TypeScriptGeneratorSettings.ClassTypes; } - set { Settings.TypeScriptGeneratorSettings.ClassTypes = value; } + get => Settings.TypeScriptGeneratorSettings.ClassTypes; + set => Settings.TypeScriptGeneratorSettings.ClassTypes = value; } [Argument(Name = "ExtendedClasses", IsRequired = false, Description = "The list of extended classes.")] public string[] ExtendedClasses { - get { return Settings.TypeScriptGeneratorSettings.ExtendedClasses; } - set { Settings.TypeScriptGeneratorSettings.ExtendedClasses = value; } + get => Settings.TypeScriptGeneratorSettings.ExtendedClasses; + set => Settings.TypeScriptGeneratorSettings.ExtendedClasses = value; } [Argument(Name = "ExtensionCode", IsRequired = false, Description = "The extension code (string or file path).")] @@ -293,107 +289,107 @@ public string[] ExtendedClasses [Argument(Name = "GenerateDefaultValues", IsRequired = false, Description = "Specifies whether to generate default values for properties (default: true).")] public bool GenerateDefaultValues { - get { return Settings.TypeScriptGeneratorSettings.GenerateDefaultValues; } - set { Settings.TypeScriptGeneratorSettings.GenerateDefaultValues = value; } + get => Settings.TypeScriptGeneratorSettings.GenerateDefaultValues; + set => Settings.TypeScriptGeneratorSettings.GenerateDefaultValues = value; } [Argument(Name = "ExcludedTypeNames", IsRequired = false, Description = "The excluded DTO type names (must be defined in an import or other namespace).")] public string[] ExcludedTypeNames { - get { return Settings.TypeScriptGeneratorSettings.ExcludedTypeNames; } - set { Settings.TypeScriptGeneratorSettings.ExcludedTypeNames = value; } + get => Settings.TypeScriptGeneratorSettings.ExcludedTypeNames; + set => Settings.TypeScriptGeneratorSettings.ExcludedTypeNames = value; } [Argument(Name = "ExcludedParameterNames", IsRequired = false, Description = "The globally excluded parameter names.")] public string[] ExcludedParameterNames { - get { return Settings.ExcludedParameterNames; } - set { Settings.ExcludedParameterNames = value; } + get => Settings.ExcludedParameterNames; + set => Settings.ExcludedParameterNames = value; } [Argument(Name = "HandleReferences", IsRequired = false, Description = "Handle JSON references (default: false).")] public bool HandleReferences { - get { return Settings.TypeScriptGeneratorSettings.HandleReferences; } - set { Settings.TypeScriptGeneratorSettings.HandleReferences = value; } + get => Settings.TypeScriptGeneratorSettings.HandleReferences; + set => Settings.TypeScriptGeneratorSettings.HandleReferences = value; } [Argument(Name = "GenerateTypeCheckFunctions", IsRequired = false, Description = "Generate type check functions (only available when TypeStyle is Interface, default: false).")] public bool GenerateTypeCheckFunctions { - get { return Settings.TypeScriptGeneratorSettings.GenerateTypeCheckFunctions; } - set { Settings.TypeScriptGeneratorSettings.GenerateTypeCheckFunctions = value; } + get => Settings.TypeScriptGeneratorSettings.GenerateTypeCheckFunctions; + set => Settings.TypeScriptGeneratorSettings.GenerateTypeCheckFunctions = value; } [Argument(Name = "GenerateConstructorInterface", IsRequired = false, Description = "Generate an class interface which is used in the constructor to initialize the class (only available when TypeStyle is Class, default: true).")] public bool GenerateConstructorInterface { - get { return Settings.TypeScriptGeneratorSettings.GenerateConstructorInterface; } - set { Settings.TypeScriptGeneratorSettings.GenerateConstructorInterface = value; } + get => Settings.TypeScriptGeneratorSettings.GenerateConstructorInterface; + set => Settings.TypeScriptGeneratorSettings.GenerateConstructorInterface = value; } [Argument(Name = "ConvertConstructorInterfaceData", IsRequired = false, Description = "Convert POJO objects in the constructor data to DTO instances (GenerateConstructorInterface must be enabled, default: false).")] public bool ConvertConstructorInterfaceData { - get { return Settings.TypeScriptGeneratorSettings.ConvertConstructorInterfaceData; } - set { Settings.TypeScriptGeneratorSettings.ConvertConstructorInterfaceData = value; } + get => Settings.TypeScriptGeneratorSettings.ConvertConstructorInterfaceData; + set => Settings.TypeScriptGeneratorSettings.ConvertConstructorInterfaceData = value; } [Argument(Name = "ImportRequiredTypes", IsRequired = false, Description = "Specifies whether required types should be imported (default: true).")] public bool ImportRequiredTypes { - get { return Settings.ImportRequiredTypes; } - set { Settings.ImportRequiredTypes = value; } + get => Settings.ImportRequiredTypes; + set => Settings.ImportRequiredTypes = value; } [Argument(Name = "UseGetBaseUrlMethod", IsRequired = false, Description = "Specifies whether to use the 'getBaseUrl(defaultUrl: string)' method from the base class (default: false).")] public bool UseGetBaseUrlMethod { - get { return Settings.UseGetBaseUrlMethod; } - set { Settings.UseGetBaseUrlMethod = value; } + get => Settings.UseGetBaseUrlMethod; + set => Settings.UseGetBaseUrlMethod = value; } [Argument(Name = "BaseUrlTokenName", IsRequired = false, Description = "The token name for injecting the API base URL string (used in the Angular template, default: 'API_BASE_URL').")] public string BaseUrlTokenName { - get { return Settings.BaseUrlTokenName; } - set { Settings.BaseUrlTokenName = value; } + get => Settings.BaseUrlTokenName; + set => Settings.BaseUrlTokenName = value; } [Argument(Name = nameof(QueryNullValue), IsRequired = false, Description = "The null value used for query parameters which are null (default: '').")] public string QueryNullValue { - get { return Settings.QueryNullValue; } - set { Settings.QueryNullValue = value; } + get => Settings.QueryNullValue; + set => Settings.QueryNullValue = value; } [Argument(Name = "UseAbortSignal", IsRequired = false, Description = "Specifies whether to use the AbortSignal (Aurelia/Axios/Fetch template only, default: false).")] public bool UseAbortSignal { - get { return Settings.UseAbortSignal; } - set { Settings.UseAbortSignal = value; } + get => Settings.UseAbortSignal; + set => Settings.UseAbortSignal = value; } [Argument(Name = "InlineNamedDictionaries", Description = "Inline named dictionaries (default: false).", IsRequired = false)] public bool InlineNamedDictionaries { - get { return Settings.TypeScriptGeneratorSettings.InlineNamedDictionaries; } - set { Settings.TypeScriptGeneratorSettings.InlineNamedDictionaries = value; } + get => Settings.TypeScriptGeneratorSettings.InlineNamedDictionaries; + set => Settings.TypeScriptGeneratorSettings.InlineNamedDictionaries = value; } [Argument(Name = "InlineNamedAny", Description = "Inline named any types (default: false).", IsRequired = false)] public bool InlineNamedAny { - get { return Settings.TypeScriptGeneratorSettings.InlineNamedAny; } - set { Settings.TypeScriptGeneratorSettings.InlineNamedAny = value; } + get => Settings.TypeScriptGeneratorSettings.InlineNamedAny; + set => Settings.TypeScriptGeneratorSettings.InlineNamedAny = value; } [Argument(Name = "IncludeHttpContext", IsRequired = false, Description = "Gets a value indicating whether to include the httpContext (Angular template only, default: false).")] public bool IncludeHttpContext { - get { return Settings.IncludeHttpContext; } - set { Settings.IncludeHttpContext = value; } + get => Settings.IncludeHttpContext; + set => Settings.IncludeHttpContext = value; } public override async Task RunAsync(CommandLineProcessor processor, IConsoleHost host) diff --git a/src/NSwag.Commands/Commands/Document/CreateDocumentCommand.cs b/src/NSwag.Commands/Commands/Document/CreateDocumentCommand.cs index 1964501515..8d4625d118 100644 --- a/src/NSwag.Commands/Commands/Document/CreateDocumentCommand.cs +++ b/src/NSwag.Commands/Commands/Document/CreateDocumentCommand.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.IO; -using System.Threading.Tasks; using NConsole; using NSwag.Commands.CodeGeneration; @@ -33,7 +31,7 @@ public async Task RunAsync(CommandLineProcessor processor, IConsoleHost return null; } - private async Task CreateDocumentAsync(string filePath) + private static async Task CreateDocumentAsync(string filePath) { var document = new NSwagDocument(); document.Path = filePath; diff --git a/src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs b/src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs index 6c6538ba4f..c7f485993b 100644 --- a/src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs +++ b/src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs @@ -6,10 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.IO; -using System.Linq; -using System.Threading.Tasks; using NConsole; #pragma warning disable 1591 @@ -28,7 +24,7 @@ public class ExecuteDocumentCommand : IConsoleCommand public async Task RunAsync(CommandLineProcessor processor, IConsoleHost host) { // input can be nix-like file path starting with / - if (!string.IsNullOrEmpty(Input) && (!Input.StartsWith("/") || File.Exists(Input) || Input.EndsWith("nswag.json")) && !Input.StartsWith("-")) + if (!string.IsNullOrEmpty(Input) && (!Input.StartsWith('/') || File.Exists(Input) || Input.EndsWith("nswag.json", StringComparison.OrdinalIgnoreCase)) && !Input.StartsWith('-')) { await ExecuteDocumentAsync(host, Input); } @@ -42,7 +38,7 @@ public async Task RunAsync(CommandLineProcessor processor, IConsoleHost var currentDirectory = Directory.GetCurrentDirectory(); var files = Directory.GetFiles(currentDirectory, "*.nswag"); - if (files.Any()) + if (files.Length > 0) { foreach (var file in files) { diff --git a/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs b/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs index 041ffeecb3..8f47fb722f 100644 --- a/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs +++ b/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs @@ -6,12 +6,9 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable IDE0005 -using System; -using System.Collections.Generic; -using System.IO; using System.Reflection; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using NConsole; using Newtonsoft.Json; @@ -144,7 +141,7 @@ public override async Task RunAsync(CommandLineProcessor processor, ICon } if (projectMetadata.TargetFrameworkIdentifier == ".NETCoreApp" || - projectMetadata.TargetFrameworkIdentifier.StartsWith("net")) + projectMetadata.TargetFrameworkIdentifier.StartsWith("net", StringComparison.Ordinal)) { executable = "dotnet"; args.Add("exec"); @@ -156,7 +153,7 @@ public override async Task RunAsync(CommandLineProcessor processor, ICon var binaryName = LauncherBinaryName + ".dll"; var executorBinary = Path.Combine(toolDirectory, binaryName); - + if (!File.Exists(executorBinary)) { binaryName = LauncherBinaryName + ".exe"; diff --git a/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs b/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs index 3752d116e6..7ac88ccdb3 100644 --- a/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs +++ b/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.IO; using System.Reflection; using Newtonsoft.Json; @@ -15,7 +14,7 @@ namespace NSwag.Commands.Generation.AspNetCore { /// In-process entry point for the aspnetcore2swagger command. - internal class AspNetCoreToOpenApiGeneratorCommandEntryPoint + internal sealed class AspNetCoreToOpenApiGeneratorCommandEntryPoint { public static void Process(string commandContent, string outputFile, string applicationName) { diff --git a/src/NSwag.Commands/Commands/Generation/AspNetCore/Exe.cs b/src/NSwag.Commands/Commands/Generation/AspNetCore/Exe.cs index e137f2bba0..ada1859b0c 100644 --- a/src/NSwag.Commands/Commands/Generation/AspNetCore/Exe.cs +++ b/src/NSwag.Commands/Commands/Generation/AspNetCore/Exe.cs @@ -6,11 +6,8 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; using System.Diagnostics; using System.Text; -using System.Threading.Tasks; using NConsole; namespace NSwag.Commands.Generation.AspNetCore @@ -35,41 +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) { - if (process.ExitCode == 0) - { - tcs.TrySetResult(true); - } - else - { - tcs.TrySetException(new Exception($"Process failed with non-zero exit code '{process.ExitCode}'.")); - } - }; - - 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(); - } - - 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."); + tcs.TrySetResult(true); } else { - console?.WriteMessage($"Done executing command. Exit Code: {process.ExitCode}.{Environment.NewLine}"); - return process.ExitCode; +#pragma warning disable CA2201 + 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); + + 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; } } @@ -81,17 +78,17 @@ private static string ToArguments(IReadOnlyList args) var argument = args[i]; if (i != 0) { - builder.Append(" "); + builder.Append(' '); } - if (argument.IndexOf(' ') == -1) + if (!argument.Contains(' ')) { builder.Append(args[i]); continue; } - builder.Append("\""); + builder.Append('"'); var pendingBackslashs = 0; for (var j = 0; j < argument.Length; j++) @@ -116,7 +113,7 @@ private static string ToArguments(IReadOnlyList args) { if (pendingBackslashs == 1) { - builder.Append("\\"); + builder.Append('\\'); } else { @@ -136,7 +133,7 @@ private static string ToArguments(IReadOnlyList args) builder.Append('\\', pendingBackslashs * 2); } - builder.Append("\""); + builder.Append('"'); } return builder.ToString(); diff --git a/src/NSwag.Commands/Commands/Generation/AspNetCore/ProjectMetadata.cs b/src/NSwag.Commands/Commands/Generation/AspNetCore/ProjectMetadata.cs index 4c06c49f13..d74197cc72 100644 --- a/src/NSwag.Commands/Commands/Generation/AspNetCore/ProjectMetadata.cs +++ b/src/NSwag.Commands/Commands/Generation/AspNetCore/ProjectMetadata.cs @@ -6,19 +6,16 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; using System.Diagnostics; -using System.IO; -using System.Linq; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Text.Json; -using System.Threading.Tasks; using NConsole; namespace NSwag.Commands.Generation.AspNetCore { - internal class ProjectMetadata + [SuppressMessage("CodeQuality", "IDE0052:Remove unread private members")] + internal sealed class ProjectMetadata { private const string GetMetadataTarget = "__GetNSwagProjectMetadata"; @@ -86,11 +83,7 @@ public static async Task GetProjectMetadata( var args = CreateMsBuildArguments(file, framework, configuration, runtime, noBuild, outputPath); - var metadata = await TryReadingUsingGetProperties(args.ToList(), file, noBuild); - if (metadata == null) - { - metadata = await ReadUsingMsBuildTargets(args.ToList(), file, buildExtensionsDir, console); - } + var metadata = await TryReadingUsingGetProperties(args, file, noBuild) ?? await ReadUsingMsBuildTargets(args, file, buildExtensionsDir, console); var platformTarget = metadata[nameof(PlatformTarget)]; if (platformTarget.Length == 0) @@ -128,11 +121,7 @@ private static async Task> ReadUsingMsBuildTargets( string buildExtensionsDir, IConsoleHost console) { - if (buildExtensionsDir == null) - { - // fallback - buildExtensionsDir = Path.Combine(Path.GetDirectoryName(file), "obj"); - } + buildExtensionsDir ??= Path.Combine(Path.GetDirectoryName(file), "obj"); Directory.CreateDirectory(buildExtensionsDir); @@ -167,7 +156,7 @@ private static async Task> ReadUsingMsBuildTargets( console.WriteMessage("Output:" + Environment.NewLine + File.ReadAllText(metadataFile)); } - metadata = File.ReadLines(metadataFile).Select(l => l.Split(new[] { ':' }, 2)) + metadata = File.ReadLines(metadataFile).Select(l => l.Split([':'], 2)) .ToDictionary(s => s[0], s => s[1].TrimStart()); } finally @@ -245,7 +234,7 @@ private static async Task> TryReadingUsingGetProperti { WorkingDirectory = Path.GetDirectoryName(file), FileName = "dotnet", - Arguments = $"{string.Join(" " , args)} --getProperty:{string.Join(";", properties)}", + Arguments = $"{string.Join(" ", args)} --getProperty:{string.Join(";", properties)}", CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true diff --git a/src/NSwag.Commands/Commands/Generation/FromDocumentCommand.cs b/src/NSwag.Commands/Commands/Generation/FromDocumentCommand.cs index c84c0b2f22..2c40caf472 100644 --- a/src/NSwag.Commands/Commands/Generation/FromDocumentCommand.cs +++ b/src/NSwag.Commands/Commands/Generation/FromDocumentCommand.cs @@ -8,7 +8,6 @@ using System.ComponentModel; using System.Runtime.CompilerServices; -using System.Threading.Tasks; using NConsole; using Newtonsoft.Json; @@ -24,7 +23,7 @@ public class FromDocumentCommand : OutputCommandBase, INotifyPropertyChanged [JsonProperty("json", NullValueHandling = NullValueHandling.Ignore)] public string Json { - get { return _json; } + get => _json; set { _json = value; @@ -36,7 +35,7 @@ public string Json [JsonProperty("url", NullValueHandling = NullValueHandling.Ignore)] public string Url { - get { return _url; } + get => _url; set { _url = value; diff --git a/src/NSwag.Commands/Commands/InputOutputCommandBase.cs b/src/NSwag.Commands/Commands/InputOutputCommandBase.cs index 6358d5d386..7caba1eb1a 100644 --- a/src/NSwag.Commands/Commands/InputOutputCommandBase.cs +++ b/src/NSwag.Commands/Commands/InputOutputCommandBase.cs @@ -6,14 +6,9 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.IO; -using System.Linq; -using System.Threading.Tasks; using NConsole; using Newtonsoft.Json; using NJsonSchema; -using NJsonSchema.Infrastructure; #pragma warning disable 1591 @@ -59,7 +54,7 @@ protected async Task GetInputSwaggerDocument() document.Host = ServiceHost; } - if (ServiceSchemes != null && ServiceSchemes.Any()) + if (ServiceSchemes != null && ServiceSchemes.Length > 0) { document.Schemes = ServiceSchemes.Select(s => (OpenApiSchema)Enum.Parse(typeof(OpenApiSchema), s, true)).ToList(); } diff --git a/src/NSwag.Commands/Commands/OutputCommandBase.cs b/src/NSwag.Commands/Commands/OutputCommandBase.cs index 2549ab4b07..86e9b36b82 100644 --- a/src/NSwag.Commands/Commands/OutputCommandBase.cs +++ b/src/NSwag.Commands/Commands/OutputCommandBase.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Threading.Tasks; using NConsole; using Newtonsoft.Json; @@ -25,11 +23,11 @@ public abstract class OutputCommandBase : IOutputCommand public abstract Task RunAsync(CommandLineProcessor processor, IConsoleHost host); - protected Task ReadSwaggerDocumentAsync(string input) + protected static Task ReadSwaggerDocumentAsync(string input) { if (!IsJson(input) && !IsYaml(input)) { - if (input.StartsWith("http://") || input.StartsWith("https://")) + if (input.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || input.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { if (input.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase) || input.EndsWith(".yml", StringComparison.OrdinalIgnoreCase)) @@ -67,14 +65,14 @@ protected Task ReadSwaggerDocumentAsync(string input) } } - protected bool IsJson(string data) + protected static bool IsJson(string data) { - return data.StartsWith("{"); + return data.StartsWith('{'); } - protected bool IsYaml(string data) + protected static bool IsYaml(string data) { - return !IsJson(data) && data.Contains("\n"); + return !IsJson(data) && data.Contains('\n'); } protected Task TryWriteFileOutputAsync(IConsoleHost host, Func generator) diff --git a/src/NSwag.Commands/Commands/OutputCommandExtensions.cs b/src/NSwag.Commands/Commands/OutputCommandExtensions.cs index cbf47acfb6..c527f74d92 100644 --- a/src/NSwag.Commands/Commands/OutputCommandExtensions.cs +++ b/src/NSwag.Commands/Commands/OutputCommandExtensions.cs @@ -6,11 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.IO; -using System.Threading.Tasks; using NConsole; -using NJsonSchema.Infrastructure; #pragma warning disable 1591 @@ -34,7 +30,7 @@ public static Task TryWriteFileOutputAsync(this IOutputCommand command, st if (!string.IsNullOrEmpty(path)) { var directory = Path.GetDirectoryName(path); - if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory) == false) + if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { Directory.CreateDirectory(directory); } @@ -42,8 +38,12 @@ public static Task TryWriteFileOutputAsync(this IOutputCommand command, st var data = generator(); data = data?.Replace("\r", "") ?? ""; - data = newLineBehavior == NewLineBehavior.Auto ? data.Replace("\n", Environment.NewLine) : - newLineBehavior == NewLineBehavior.CRLF ? data.Replace("\n", "\r\n") : data; + data = newLineBehavior switch + { + NewLineBehavior.Auto => data.Replace("\n", Environment.NewLine), + NewLineBehavior.CRLF => data.Replace("\n", "\r\n"), + _ => data + }; if (!File.Exists(path) || File.ReadAllText(path) != data) { diff --git a/src/NSwag.Commands/Commands/Tooling/VersionCommand.cs b/src/NSwag.Commands/Commands/Tooling/VersionCommand.cs index b486205e19..5d3e62cccb 100644 --- a/src/NSwag.Commands/Commands/Tooling/VersionCommand.cs +++ b/src/NSwag.Commands/Commands/Tooling/VersionCommand.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Threading.Tasks; using NConsole; using NJsonSchema; diff --git a/src/NSwag.Commands/HostApplication.cs b/src/NSwag.Commands/HostApplication.cs index 0f17e87551..e98308f2b8 100644 --- a/src/NSwag.Commands/HostApplication.cs +++ b/src/NSwag.Commands/HostApplication.cs @@ -1,8 +1,6 @@ -using System; -using System.Linq; +#pragma warning disable IDE0005 + using System.Reflection; -using System.Threading; -using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server; @@ -32,32 +30,32 @@ public static IServiceProvider GetServiceProvider(Assembly assembly) if (buildWebHostMethod != null) { - var result = buildWebHostMethod.Invoke(null, new object[] { args }); + var result = buildWebHostMethod.Invoke(null, [args]); serviceProvider = ((IWebHost)result).Services; } else { var createWebHostMethod = - entryPointType?.GetRuntimeMethod("CreateWebHostBuilder", new[] { typeof(string[]) }) ?? + entryPointType?.GetRuntimeMethod("CreateWebHostBuilder", [typeof(string[])]) ?? entryPointType?.GetRuntimeMethod("CreateWebHostBuilder", Type.EmptyTypes); if (createWebHostMethod != null) { var webHostBuilder = (IWebHostBuilder)createWebHostMethod.Invoke( - null, createWebHostMethod.GetParameters().Length > 0 ? new object[] { args } : Array.Empty()); + null, createWebHostMethod.GetParameters().Length > 0 ? [args] : []); serviceProvider = webHostBuilder.Build().Services; } #if NETCOREAPP3_0_OR_GREATER else { var createHostMethod = - entryPointType?.GetRuntimeMethod("CreateHostBuilder", new[] { typeof(string[]) }) ?? + entryPointType?.GetRuntimeMethod("CreateHostBuilder", [typeof(string[])]) ?? entryPointType?.GetRuntimeMethod("CreateHostBuilder", Type.EmptyTypes); if (createHostMethod != null) { var webHostBuilder = (IHostBuilder)createHostMethod.Invoke( - null, createHostMethod.GetParameters().Length > 0 ? new object[] { args } : Array.Empty()); + null, createHostMethod.GetParameters().Length > 0 ? [args] : []); serviceProvider = webHostBuilder.Build().Services; } } @@ -65,10 +63,7 @@ public static IServiceProvider GetServiceProvider(Assembly assembly) } } - if (serviceProvider == null) - { - serviceProvider = GetServiceProviderWithHostFactoryResolver(assembly); - } + serviceProvider ??= GetServiceProviderWithHostFactoryResolver(assembly); if (serviceProvider == null) { @@ -156,7 +151,7 @@ void OnEntryPointExit(Exception exception) #if NET6_0_OR_GREATER var assemblyName = assembly.GetName()?.FullName ?? string.Empty; // We should set the application name to the startup assembly to avoid falling back to the entry assembly. - var services = ((IHost)factory(new[] { $"--{HostDefaults.ApplicationKey}={assemblyName}" })).Services; + var services = ((IHost)factory([$"--{HostDefaults.ApplicationKey}={assemblyName}"])).Services; #else var services = ((IHost)factory(Array.Empty())).Services; #endif @@ -166,11 +161,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) { @@ -181,13 +174,13 @@ void OnEntryPointExit(Exception exception) #endif } - private class NoopHostLifetime : IHostLifetime + private sealed class NoopHostLifetime : IHostLifetime { public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask; } - private class NoopServer : IServer + private sealed class NoopServer : IServer { public IFeatureCollection Features { get; } = new FeatureCollection(); public void Dispose() { } diff --git a/src/NSwag.Commands/HostFactoryResolver.cs b/src/NSwag.Commands/HostFactoryResolver.cs index 771113d020..df0569621f 100644 --- a/src/NSwag.Commands/HostFactoryResolver.cs +++ b/src/NSwag.Commands/HostFactoryResolver.cs @@ -1,12 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Diagnostics; using System.Reflection; -using System.Threading; -using System.Threading.Tasks; namespace Microsoft.Extensions.Hosting { @@ -89,7 +85,7 @@ private static Func ResolveFactory(Assembly assembly, string nam return null; } - return args => (T)factory.Invoke(null, new object[] { args }); + return args => (T)factory.Invoke(null, [args]); } // TReturn Factory(string[] args); @@ -153,7 +149,7 @@ public static Func ResolveServiceProviderFactory(Ass private static object Build(object builder) { var buildMethod = builder.GetType().GetMethod("Build"); - return buildMethod?.Invoke(builder, Array.Empty()); + return buildMethod?.Invoke(builder, []); } private static IServiceProvider GetServiceProvider(object host) @@ -176,8 +172,8 @@ private sealed class HostingListener : IObserver, IObserver< private readonly TaskCompletionSource _hostTcs = new TaskCompletionSource(); private IDisposable _disposable; - private Action _configure; - private Action _entrypointCompleted; + private readonly Action _configure; + private readonly Action _entrypointCompleted; private static readonly AsyncLocal _currentListener = new AsyncLocal(); public HostingListener(string[] args, MethodInfo entryPoint, TimeSpan waitTimeout, bool stopApplication, Action configure, Action entrypointCompleted) @@ -192,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, []); } - catch (TargetInvocationException tie) when (tie.InnerException is StopTheHostException) + else { - // The host was stopped by our own logic + _entryPoint.Invoke(null, [_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() diff --git a/src/NSwag.Commands/NSwag.Commands.csproj b/src/NSwag.Commands/NSwag.Commands.csproj index e078f8778f..0142c8b67a 100644 --- a/src/NSwag.Commands/NSwag.Commands.csproj +++ b/src/NSwag.Commands/NSwag.Commands.csproj @@ -1,7 +1,7 @@  - net462;net6.0;net8.0 + net462;net8.0;net9.0 true $(NoWarn),618,1591 @@ -11,18 +11,18 @@ - - - - - - + + + + + + @@ -34,7 +34,7 @@ - + @@ -45,4 +45,8 @@ + + + + diff --git a/src/NSwag.Commands/NSwagCommandProcessor.cs b/src/NSwag.Commands/NSwagCommandProcessor.cs index 731e9d80b4..fbec698d12 100644 --- a/src/NSwag.Commands/NSwagCommandProcessor.cs +++ b/src/NSwag.Commands/NSwagCommandProcessor.cs @@ -6,14 +6,10 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; using System.Diagnostics; -using System.IO; using System.Reflection; -using System.Threading.Tasks; using NConsole; using NJsonSchema; -using NJsonSchema.Infrastructure; using NSwag.Commands.CodeGeneration; namespace NSwag.Commands @@ -82,10 +78,10 @@ private void WriteBinDirectory() try { Assembly entryAssembly; - var getEntryAssemblyMethod = typeof(Assembly).GetRuntimeMethod("GetEntryAssembly", Array.Empty()); + var getEntryAssemblyMethod = typeof(Assembly).GetRuntimeMethod("GetEntryAssembly", []); if (getEntryAssemblyMethod != null) { - entryAssembly = (Assembly) getEntryAssemblyMethod.Invoke(null, Array.Empty()); + entryAssembly = (Assembly)getEntryAssemblyMethod.Invoke(null, []); } else { diff --git a/src/NSwag.Commands/NSwagDocument.cs b/src/NSwag.Commands/NSwagDocument.cs index 7bd11df052..52b9b9b0e5 100644 --- a/src/NSwag.Commands/NSwagDocument.cs +++ b/src/NSwag.Commands/NSwagDocument.cs @@ -6,15 +6,11 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; +#pragma warning disable IDE0005 + using System.Diagnostics; -using System.IO; -using System.Linq; using System.Reflection; -using System.Text; using System.Text.RegularExpressions; -using System.Threading.Tasks; using NSwag.Commands.Generation.AspNetCore; namespace NSwag.Commands @@ -142,7 +138,7 @@ public async Task ExecuteCommandLineAsync(bool r /// The absolute path. protected override string ConvertToAbsolutePath(string pathToConvert) { - if (!string.IsNullOrEmpty(pathToConvert) && !System.IO.Path.IsPathRooted(pathToConvert) && !pathToConvert.Contains("%")) + if (!string.IsNullOrEmpty(pathToConvert) && !System.IO.Path.IsPathRooted(pathToConvert) && !pathToConvert.Contains('%')) { return PathUtilities.MakeAbsolutePath(pathToConvert, GetDocumentDirectory()); } @@ -155,7 +151,7 @@ protected override string ConvertToAbsolutePath(string pathToConvert) /// The relative path. protected override string ConvertToRelativePath(string pathToConvert) { - if (!string.IsNullOrEmpty(pathToConvert) && !pathToConvert.Contains("C:\\Program Files\\") && !pathToConvert.Contains("%")) + if (!string.IsNullOrEmpty(pathToConvert) && !pathToConvert.Contains("C:\\Program Files\\") && !pathToConvert.Contains('%')) { return PathUtilities.MakeRelativePath(pathToConvert, GetDocumentDirectory())?.Replace("\\", "/"); } @@ -196,17 +192,17 @@ private async Task StartCommandLineProcessAsync(string command) if (process.ExitCode != 0) { - var errorStart = output.IndexOf("..."); + var errorStart = output.IndexOf("...", StringComparison.Ordinal); if (errorStart < 0) { errorStart = Regex.Match(output, "\n[^\n\r]*?Exception: .*", RegexOptions.Singleline)?.Index ?? -1; } var error = errorStart > 0 ? output.Substring(errorStart + 4) : output; - var stackTraceStart = error.IndexOf("Server stack trace: "); + var stackTraceStart = error.IndexOf("Server stack trace: ", StringComparison.Ordinal); if (stackTraceStart < 0) { - stackTraceStart = error.IndexOf(" at "); + stackTraceStart = error.IndexOf(" at ", StringComparison.Ordinal); } var message = stackTraceStart > 0 ? error.Substring(0, stackTraceStart) : error; @@ -214,12 +210,12 @@ private async Task StartCommandLineProcessAsync(string command) if (message.Contains("Could not load type")) { - message = message + "Try running the document in another runtime, e.g. /runtime:NetCore20"; + message += "Try running the document in another runtime, e.g. /runtime:NetCore20"; } if (message.Contains("The system cannot find the file specified")) { - message = message + "Check if .NET Core is installed and 'dotnet' is globally available."; + message += "Check if .NET Core is installed and 'dotnet' is globally available."; } throw new CommandLineException(message, "Runtime: " + Runtime + "\n" + stackTrace); @@ -230,47 +226,49 @@ private async Task StartCommandLineProcessAsync(string command) private string GetDocumentDirectory() { - var absoluteDocumentPath = PathUtilities.MakeAbsolutePath(Path, System.IO.Directory.GetCurrentDirectory()); + var absoluteDocumentPath = PathUtilities.MakeAbsolutePath(Path, Directory.GetCurrentDirectory()); return System.IO.Path.GetDirectoryName(absoluteDocumentPath); } +#pragma warning disable CA1822 private string GetArgumentsPrefix() +#pragma warning restore CA1822 { #if NET462 var runtime = Runtime != Runtime.Default ? Runtime : RuntimeUtilities.CurrentRuntime; - if (runtime == Runtime.Net60) + if (runtime == Runtime.Net80) { - return "\"" + System.IO.Path.Combine(RootBinaryDirectory, "Net60/dotnet-nswag.dll") + "\" "; + return "\"" + System.IO.Path.Combine(RootBinaryDirectory, "Net80/dotnet-nswag.dll") + "\" "; } - else if (runtime == Runtime.Net80) + if (runtime == Runtime.Net90) { - return "\"" + System.IO.Path.Combine(RootBinaryDirectory, "Net80/dotnet-nswag.dll") + "\" "; + return "\"" + System.IO.Path.Combine(RootBinaryDirectory, "Net90/dotnet-nswag.dll") + "\" "; } - else #endif return ""; } +#pragma warning disable CA1822 private string GetProgramName() +#pragma warning restore CA1822 { #if NET462 - var runtime = Runtime != Runtime.Default ? Runtime : RuntimeUtilities.CurrentRuntime; - if (runtime == Runtime.WinX64 || runtime == Runtime.Debug) + if (runtime is Runtime.WinX64 or Runtime.Debug) { return System.IO.Path.Combine(RootBinaryDirectory, "Win/nswag.exe"); } - else if (runtime == Runtime.WinX86) + + if (runtime == Runtime.WinX86) { return System.IO.Path.Combine(RootBinaryDirectory, "Win/nswag.x86.exe"); } - else #endif return "dotnet"; } - private string ReadFileIfExists(string filename) + private static string ReadFileIfExists(string filename) { if (filename != null && File.Exists(filename)) { @@ -280,7 +278,7 @@ private string ReadFileIfExists(string filename) return null; } - private void DeleteFileIfExists(string filename) + private static void DeleteFileIfExists(string filename) { if (File.Exists(filename)) { @@ -288,7 +286,7 @@ private void DeleteFileIfExists(string filename) } } - internal class CommandLineException : Exception + private sealed class CommandLineException : Exception { public CommandLineException(string message, string stackTrace) : base(message) diff --git a/src/NSwag.Commands/NSwagDocumentBase.cs b/src/NSwag.Commands/NSwagDocumentBase.cs index 8cd1598142..c3d54ca9cd 100644 --- a/src/NSwag.Commands/NSwagDocumentBase.cs +++ b/src/NSwag.Commands/NSwagDocumentBase.cs @@ -6,20 +6,16 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; +#pragma warning disable CA1507 + using System.ComponentModel; -using System.IO; -using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; -using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; -using NJsonSchema.Infrastructure; using NSwag.Commands.CodeGeneration; using NSwag.Commands.Generation; @@ -57,7 +53,7 @@ protected NSwagDocumentBase() public abstract Task ExecuteAsync(); /// Gets or sets the runtime where the document should be processed. - public Runtime Runtime { get; set; } = Runtime.Net60; + public Runtime Runtime { get; set; } = Runtime.Net80; /// Gets or sets the default variables. public string DefaultVariables { get; set; } @@ -104,7 +100,7 @@ internal JObject SelectedSwaggerGeneratorRaw [JsonIgnore] public string Path { - get { return _path; } + get => _path; set { _path = value; @@ -138,7 +134,7 @@ public string Name [JsonIgnore] public IOutputCommand SelectedSwaggerGenerator { - get { return _selectedSwaggerGenerator; } + get => _selectedSwaggerGenerator; set { _selectedSwaggerGenerator = value; @@ -267,7 +263,7 @@ public string ToJson() /// The document. protected async Task GenerateSwaggerDocumentAsync() { - return (OpenApiDocument) await SelectedSwaggerGenerator.RunAsync(null, null); + return (OpenApiDocument)await SelectedSwaggerGenerator.RunAsync(null, null); } private static string EscapeJsonString(string value) @@ -303,10 +299,10 @@ private static JsonSerializerSettings GetSerializerSettings() DefaultValueHandling = DefaultValueHandling.Include, NullValueHandling = NullValueHandling.Include, ContractResolver = new CamelCasePropertyNamesContractResolver(), - Converters = new List - { + Converters = + [ new StringEnumConverter() - } + ] }; } @@ -314,7 +310,8 @@ private void ConvertToAbsolutePaths() { if (SwaggerGenerators.FromDocumentCommand != null) { - if (!SwaggerGenerators.FromDocumentCommand.Url.StartsWith("http://") && !SwaggerGenerators.FromDocumentCommand.Url.StartsWith("https://")) + if (!SwaggerGenerators.FromDocumentCommand.Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) + && !SwaggerGenerators.FromDocumentCommand.Url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { SwaggerGenerators.FromDocumentCommand.Url = ConvertToAbsolutePath(SwaggerGenerators.FromDocumentCommand.Url); } @@ -378,7 +375,8 @@ private void ConvertToRelativePaths() { if (SwaggerGenerators.FromDocumentCommand != null) { - if (!SwaggerGenerators.FromDocumentCommand.Url.StartsWith("http://") && !SwaggerGenerators.FromDocumentCommand.Url.StartsWith("https://")) + if (!SwaggerGenerators.FromDocumentCommand.Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) + && !SwaggerGenerators.FromDocumentCommand.Url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { SwaggerGenerators.FromDocumentCommand.Url = ConvertToRelativePath(SwaggerGenerators.FromDocumentCommand.Url); } @@ -442,7 +440,7 @@ private static string TransformLegacyDocument(string data, out bool saveFile) saveFile = false; // Swagger to OpenApi rename - if (data.Contains("\"typeScriptVersion\":") && !data.ToLowerInvariant().Contains("ExceptionClass".ToLowerInvariant())) + if (data.Contains("\"typeScriptVersion\":") && !data.Contains("ExceptionClass", StringComparison.OrdinalIgnoreCase)) { data = data.Replace("\"typeScriptVersion\":", "\"exceptionClass\": \"SwaggerException\", \"typeScriptVersion\":"); saveFile = true; @@ -515,7 +513,7 @@ private static string TransformLegacyDocument(string data, out bool saveFile) saveFile = true; } - if (data.Contains("\"noBuild\":") && !data.ToLowerInvariant().Contains("RequireParametersWithoutDefault".ToLowerInvariant())) + if (data.Contains("\"noBuild\":") && !data.Contains("RequireParametersWithoutDefault", StringComparison.OrdinalIgnoreCase)) { data = data.Replace("\"noBuild\":", "\"requireParametersWithoutDefault\": true, \"noBuild\":"); saveFile = true; diff --git a/src/NSwag.Commands/NewLineBehavior.cs b/src/NSwag.Commands/NewLineBehavior.cs index e02525905b..a423f74102 100644 --- a/src/NSwag.Commands/NewLineBehavior.cs +++ b/src/NSwag.Commands/NewLineBehavior.cs @@ -16,12 +16,12 @@ public enum NewLineBehavior /// /// Automatic line ending based on the current OS. /// - Auto, + Auto, /// /// CRLF. /// - CRLF, + CRLF, /// /// LF. diff --git a/src/NSwag.Commands/OpenApiDocumentExecutionResult.cs b/src/NSwag.Commands/OpenApiDocumentExecutionResult.cs index e634626ee7..b9bde72c52 100644 --- a/src/NSwag.Commands/OpenApiDocumentExecutionResult.cs +++ b/src/NSwag.Commands/OpenApiDocumentExecutionResult.cs @@ -6,15 +6,12 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; - namespace NSwag.Commands { /// Stores the result of a execution. public class OpenApiDocumentExecutionResult { - private readonly IDictionary _generatorOutputs = new Dictionary(); + private readonly Dictionary _generatorOutputs = []; /// Initializes a new instance of the class. /// The command line output. diff --git a/src/NSwag.Commands/OpenApiGeneratorCollection.cs b/src/NSwag.Commands/OpenApiGeneratorCollection.cs index 87086be628..9b98efbae4 100644 --- a/src/NSwag.Commands/OpenApiGeneratorCollection.cs +++ b/src/NSwag.Commands/OpenApiGeneratorCollection.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using Newtonsoft.Json; +using Newtonsoft.Json; using NSwag.Commands.CodeGeneration; using NSwag.Commands.Generation; using NSwag.Commands.Generation.AspNetCore; @@ -7,7 +6,9 @@ namespace NSwag.Commands { /// +#pragma warning disable CA1711 public class OpenApiGeneratorCollection +#pragma warning restore CA1711 { /// Gets or sets the input to swagger command. [JsonIgnore] @@ -23,11 +24,11 @@ public class OpenApiGeneratorCollection /// Gets the items. [JsonIgnore] - public IEnumerable Items => new IOutputCommand[] - { + public IEnumerable Items => + [ FromDocumentCommand, JsonSchemaToOpenApiCommand, AspNetCoreToOpenApiCommand - }; + ]; } } \ No newline at end of file diff --git a/src/NSwag.Commands/OperationGenerationModeConverter.cs b/src/NSwag.Commands/OperationGenerationModeConverter.cs index 1e60cff0c7..e8b130c1dd 100644 --- a/src/NSwag.Commands/OperationGenerationModeConverter.cs +++ b/src/NSwag.Commands/OperationGenerationModeConverter.cs @@ -11,7 +11,7 @@ namespace NSwag.Commands { - internal class OperationGenerationModeConverter + internal sealed class OperationGenerationModeConverter { internal static OperationGenerationMode GetOperationGenerationMode(IOperationNameGenerator operationNameGenerator) { diff --git a/src/NSwag.Commands/PathUtilities.cs b/src/NSwag.Commands/PathUtilities.cs index 0595324ada..538fb178a9 100644 --- a/src/NSwag.Commands/PathUtilities.cs +++ b/src/NSwag.Commands/PathUtilities.cs @@ -6,10 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text; using System.Text.RegularExpressions; @@ -22,7 +18,7 @@ public static class PathUtilities /// All expanded file paths. public static IEnumerable ExpandFileWildcards(string path) { - return ExpandFileWildcards(new[] { path }); + return ExpandFileWildcards([path]); } /// Expands the given wildcards (** or *) in the paths. @@ -33,14 +29,14 @@ public static IEnumerable ExpandFileWildcards(IEnumerable paths) var allFiles = new List(); foreach (var path in paths) { - if (path.Contains("*")) + if (path.Contains('*')) { - var starIndex = path.IndexOf("*", StringComparison.Ordinal); + var starIndex = path.IndexOf('*'); - var rootIndex = path.Substring(0, starIndex).LastIndexOf("\\", StringComparison.Ordinal); + var rootIndex = path.Substring(0, starIndex).LastIndexOf('\\'); if (rootIndex == -1) { - rootIndex = path.Substring(0, starIndex).LastIndexOf("/", StringComparison.Ordinal); + rootIndex = path.Substring(0, starIndex).LastIndexOf('/'); } var rootPath = rootIndex >= 0 ? path.Substring(0, rootIndex + 1) : Directory.GetCurrentDirectory(); diff --git a/src/NSwag.Commands/Runtime.cs b/src/NSwag.Commands/Runtime.cs index 4e4a1f11ea..a700040dec 100644 --- a/src/NSwag.Commands/Runtime.cs +++ b/src/NSwag.Commands/Runtime.cs @@ -20,12 +20,12 @@ public enum Runtime /// Full .NET framework, x86. WinX86, - /// .NET 6 app. - Net60, - /// .NET 8 app. Net80, + /// .NET 9 app. + Net90, + /// Execute in the same process. Debug } diff --git a/src/NSwag.Commands/RuntimeUtilities.cs b/src/NSwag.Commands/RuntimeUtilities.cs index 92cbea8ecf..0fca74c267 100644 --- a/src/NSwag.Commands/RuntimeUtilities.cs +++ b/src/NSwag.Commands/RuntimeUtilities.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; #if !NETFRAMEWORK using Microsoft.Extensions.PlatformAbstractions; #endif @@ -27,17 +26,12 @@ public static Runtime CurrentRuntime var framework = PlatformServices.Default.Application.RuntimeFramework; if (framework.Identifier == ".NETCoreApp") { - if (framework.Version.Major >= 8) + if (framework.Version.Major >= 9) { - return Runtime.Net80; + return Runtime.Net90; } - if (framework.Version.Major >= 6) - { - return Runtime.Net60; - } - - return Runtime.Net60; + return Runtime.Net80; } return IntPtr.Size == 4 ? Runtime.WinX86 : Runtime.WinX64; #endif diff --git a/src/NSwag.Console/Program.cs b/src/NSwag.Console/Program.cs index 443df81c4e..2808c7277b 100644 --- a/src/NSwag.Console/Program.cs +++ b/src/NSwag.Console/Program.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using NConsole; +using NConsole; using NSwag.Commands; namespace NSwag diff --git a/src/NSwag.Sample.NET80Minimal/GeneratedClientsCs.gen b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.CheckCSharpClientsAsync_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt similarity index 99% rename from src/NSwag.Sample.NET80Minimal/GeneratedClientsCs.gen rename to src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.CheckCSharpClientsAsync_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt index 0a5d58ade6..8dd9c74dd8 100644 --- a/src/NSwag.Sample.NET80Minimal/GeneratedClientsCs.gen +++ b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.CheckCSharpClientsAsync_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt @@ -1,4 +1,4 @@ -//---------------------- +//---------------------- // // Generated using the NSwag toolchain v (http://NSwag.org) // diff --git a/src/NSwag.Sample.NET80Minimal/GeneratedControllersCs.gen b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.CheckCSharpControllersAsync_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt similarity index 99% rename from src/NSwag.Sample.NET80Minimal/GeneratedControllersCs.gen rename to src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.CheckCSharpControllersAsync_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt index 53d1086332..048437a5d1 100644 --- a/src/NSwag.Sample.NET80Minimal/GeneratedControllersCs.gen +++ b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.CheckCSharpControllersAsync_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt @@ -1,4 +1,4 @@ -//---------------------- +//---------------------- // // Generated using the NSwag toolchain v (http://NSwag.org) // diff --git a/src/NSwag.Sample.NET80Minimal/GeneratedClientsTs.gen b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.CheckTypeScriptAsync_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt similarity index 99% rename from src/NSwag.Sample.NET80Minimal/GeneratedClientsTs.gen rename to src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.CheckTypeScriptAsync_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt index 21ee891e02..dc6afc7fef 100644 --- a/src/NSwag.Sample.NET80Minimal/GeneratedClientsTs.gen +++ b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.CheckTypeScriptAsync_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt @@ -1,4 +1,4 @@ -//---------------------- +//---------------------- // // Generated using the NSwag toolchain v (http://NSwag.org) // diff --git a/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.Should_generate_openapi_for_project_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.Should_generate_openapi_for_project_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt new file mode 100644 index 0000000000..313ca86c6c --- /dev/null +++ b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.Should_generate_openapi_for_project_projectName=NSwag.Sample.NET90Minimal_targetFramework=net9.0_generatesCode=True.verified.txt @@ -0,0 +1,161 @@ +{ + "x-generator": "NSwag", + "openapi": "3.0.0", + "info": { + "title": "Minimal API", + "version": "v1" + }, + "paths": { + "/": { + "get": { + "tags": [ + "General" + ], + "operationId": "Get", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/sum/{a}/{b}": { + "get": { + "tags": [ + "Calculator" + ], + "operationId": "CalculateSum", + "parameters": [ + { + "name": "a", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + }, + "x-position": 1 + }, + { + "name": "b", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + }, + "x-position": 2 + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "integer", + "format": "int32" + } + } + } + } + } + } + }, + "/abs({a})": { + "get": { + "tags": [ + "Calculator" + ], + "operationId": "AbsoluteValue", + "parameters": [ + { + "name": "a", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + }, + "x-position": 1 + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "integer", + "format": "int32" + } + } + } + } + } + } + }, + "/id:{id}": { + "get": { + "tags": [ + "Calculator" + ], + "operationId": "Identity", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + }, + "x-position": 1 + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "integer", + "format": "int32" + } + } + } + } + } + } + }, + "/examples": { + "get": { + "tags": [ + "Example" + ], + "operationId": "Example_Get", + "responses": { + "200": { + "description": "", + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + } + } + }, + "components": {} +} \ No newline at end of file diff --git a/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.Should_generate_openapi_for_project_projectName=NSwag.Sample.NET90_targetFramework=net9.0_generatesCode=False.verified.txt b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.Should_generate_openapi_for_project_projectName=NSwag.Sample.NET90_targetFramework=net9.0_generatesCode=False.verified.txt new file mode 100644 index 0000000000..8f3057def2 --- /dev/null +++ b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.Should_generate_openapi_for_project_projectName=NSwag.Sample.NET90_targetFramework=net9.0_generatesCode=False.verified.txt @@ -0,0 +1,247 @@ +{ + "x-generator": "NSwag", + "openapi": "3.0.0", + "info": { + "title": "My Title", + "description": "Hello world!", + "version": "1.0.0" + }, + "paths": { + "/api/Values": { + "get": { + "tags": [ + "Values" + ], + "operationId": "Values_GetAll", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Person" + } + } + } + } + } + } + }, + "post": { + "tags": [ + "Values" + ], + "operationId": "Values_Post", + "requestBody": { + "x-name": "value", + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + }, + "required": true, + "x-position": 1 + }, + "responses": { + "200": { + "description": "" + } + } + } + }, + "/api/Values/{id}": { + "get": { + "tags": [ + "Values" + ], + "operationId": "Values_Get", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + }, + "x-position": 1 + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestEnum" + } + } + } + } + } + }, + "put": { + "tags": [ + "Values" + ], + "operationId": "Values_Put", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + }, + "x-position": 1 + } + ], + "requestBody": { + "x-name": "value", + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + }, + "required": true, + "x-position": 2 + }, + "responses": { + "200": { + "description": "" + } + } + }, + "delete": { + "tags": [ + "Values" + ], + "operationId": "Values_Delete", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + }, + "x-position": 1 + } + ], + "responses": { + "200": { + "description": "" + } + } + } + }, + "/api/Values/ToString({id})": { + "get": { + "tags": [ + "Values" + ], + "operationId": "Values_GetToString", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + }, + "x-position": 1 + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/api/Values/{id}/foo": { + "get": { + "tags": [ + "Values" + ], + "operationId": "Values_GetFooBar", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + }, + "x-position": 1 + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "Person": { + "type": "object", + "additionalProperties": false, + "properties": { + "firstName": { + "type": "string" + }, + "middleName": { + "type": "string", + "nullable": true + }, + "lastName": { + "type": "string" + }, + "dayOfBirth": { + "type": "string", + "format": "date-time" + } + } + }, + "TestEnum": { + "type": "string", + "description": "", + "x-enumNames": [ + "Foo", + "Bar" + ], + "enum": [ + "Foo", + "Bar" + ] + } + } + } +} \ No newline at end of file diff --git a/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.cs b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.cs index 41ca3a3d5f..77db1a102d 100644 --- a/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.cs +++ b/src/NSwag.ConsoleCore.Tests/GenerateSampleSpecificationTests.cs @@ -1,19 +1,14 @@ using System.Diagnostics; -using System.IO; -using System.Threading.Tasks; -using VerifyXunit; -using Xunit; namespace NSwag.ConsoleCore.Tests { - [UsesVerify] public class GenerateSampleSpecificationTests { [Theory] - [InlineData("NSwag.Sample.NET60", "net6.0", false)] - [InlineData("NSwag.Sample.NET60Minimal", "net6.0", false)] [InlineData("NSwag.Sample.NET80", "net8.0", false)] [InlineData("NSwag.Sample.NET80Minimal", "net8.0", true)] + [InlineData("NSwag.Sample.NET90", "net9.0", false)] + [InlineData("NSwag.Sample.NET90Minimal", "net9.0", true)] public async Task Should_generate_openapi_for_project(string projectName, string targetFramework, bool generatesCode) { // Arrange diff --git a/src/NSwag.ConsoleCore.Tests/NSwag.ConsoleCore.Tests.csproj b/src/NSwag.ConsoleCore.Tests/NSwag.ConsoleCore.Tests.csproj index 08ae2a5048..3f3a1f57af 100644 --- a/src/NSwag.ConsoleCore.Tests/NSwag.ConsoleCore.Tests.csproj +++ b/src/NSwag.ConsoleCore.Tests/NSwag.ConsoleCore.Tests.csproj @@ -1,19 +1,24 @@  - net8.0 + net9.0 + $(NoWarn);CA1707 + - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + - + diff --git a/src/NSwag.ConsoleCore/CoreConsoleHost.cs b/src/NSwag.ConsoleCore/CoreConsoleHost.cs index ebb474ee15..516d1b535c 100644 --- a/src/NSwag.ConsoleCore/CoreConsoleHost.cs +++ b/src/NSwag.ConsoleCore/CoreConsoleHost.cs @@ -1,5 +1,4 @@ -using System; -using NConsole; +using NConsole; namespace NSwag { diff --git a/src/NSwag.ConsoleCore/NSwag.ConsoleCore.csproj b/src/NSwag.ConsoleCore/NSwag.ConsoleCore.csproj index 2b08cb1eab..2988ad1055 100644 --- a/src/NSwag.ConsoleCore/NSwag.ConsoleCore.csproj +++ b/src/NSwag.ConsoleCore/NSwag.ConsoleCore.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0;net9.0 Exe dotnet-nswag NSwag.ConsoleCore @@ -13,16 +13,16 @@ - - - - - + + + + + diff --git a/src/NSwag.ConsoleCore/Program.cs b/src/NSwag.ConsoleCore/Program.cs index 7127cbb219..ad9b3fd461 100644 --- a/src/NSwag.ConsoleCore/Program.cs +++ b/src/NSwag.ConsoleCore/Program.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using NSwag.Commands; +using NSwag.Commands; namespace NSwag { diff --git a/src/NSwag.Core.Tests/DocumentLoadingTests.cs b/src/NSwag.Core.Tests/DocumentLoadingTests.cs index 345617aa91..bd5860902e 100644 --- a/src/NSwag.Core.Tests/DocumentLoadingTests.cs +++ b/src/NSwag.Core.Tests/DocumentLoadingTests.cs @@ -1,7 +1,4 @@ using System.Globalization; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using NJsonSchema; using Xunit; @@ -13,7 +10,7 @@ public class DocumentLoadingTests public async Task When_document_contains_readOnly_properties_then_they_are_correctly_loaded() { // Arrange - var json = _sampleServiceCode; + var json = SampleServiceCode; // Act var document = await OpenApiDocument.FromJsonAsync(json); @@ -33,7 +30,7 @@ public async Task When_document_contains_readOnly_properties_then_they_are_corre public async Task When_generating_operation_ids_then_missing_ids_are_generated() { // Arrange - var json = _sampleServiceCode; + var json = SampleServiceCode; // Act var document = await OpenApiDocument.FromJsonAsync(json); @@ -47,7 +44,7 @@ public async Task When_generating_operation_ids_then_missing_ids_are_generated() public async Task When_json_has_extension_data_then_it_is_loaded() { // Arrange - var json = _jsonVendorExtensionData; + var json = JsonVendorExtensionData; // Act var document = await OpenApiDocument.FromJsonAsync(json); @@ -68,18 +65,18 @@ public async Task When_locale_is_not_english_then_types_are_correctly_serialized CultureInfo.DefaultThreadCurrentCulture = ci; // Act - var json = _sampleServiceCode; + var json = SampleServiceCode; // Act var document = await OpenApiDocument.FromJsonAsync(json); var j = document.ToJson(); + Assert.NotNull(j); // Assert Assert.Equal(JsonObjectType.Integer, document.Definitions["Pet"].Properties["id"].Type); } - private string _sampleServiceCode = -@"{ + private const string SampleServiceCode = @"{ ""swagger"": ""2.0"", ""info"": { ""version"": ""1.0.0"", @@ -143,8 +140,7 @@ public async Task When_locale_is_not_english_then_types_are_correctly_serialized } }"; - private string _jsonVendorExtensionData = - @"{ + private const string JsonVendorExtensionData = @"{ ""swagger"": ""2.0"", ""info"": { ""title"": ""Swagger Test Sample"", diff --git a/src/NSwag.Core.Tests/DocumentReferenceTests.cs b/src/NSwag.Core.Tests/DocumentReferenceTests.cs index ffa54ffb7c..463b3155eb 100644 --- a/src/NSwag.Core.Tests/DocumentReferenceTests.cs +++ b/src/NSwag.Core.Tests/DocumentReferenceTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.Core.Tests { @@ -85,7 +83,7 @@ public async Task When_parameter_is_referenced_then_it_should_be_resolved() json = document.ToJson(); // Assert - Assert.Equal("foo", document.Operations.First().Operation.ActualParameters.First().Name); + Assert.Equal("foo", document.Operations.First().Operation.ActualParameters[0].Name); Assert.Contains(@"""$ref"": ""#/parameters/Foo""", json); } @@ -139,9 +137,10 @@ public async Task When_parameter_references_schema_then_it_is_resolved() // Act var document = await OpenApiDocument.FromJsonAsync(json); json = document.ToJson(); + Assert.NotNull(json); // Assert - Assert.Equal("secret", document.Operations.First().Operation.ActualParameters.First().ActualSchema.Format); + Assert.Equal("secret", document.Operations.First().Operation.ActualParameters[0].ActualSchema.Format); } [Fact] diff --git a/src/NSwag.Core.Tests/HttpLoadingTests.cs b/src/NSwag.Core.Tests/HttpLoadingTests.cs index 6da009c3ed..ba9fca391b 100644 --- a/src/NSwag.Core.Tests/HttpLoadingTests.cs +++ b/src/NSwag.Core.Tests/HttpLoadingTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.Core.Tests { diff --git a/src/NSwag.Core.Tests/NSwag.Core.Tests.csproj b/src/NSwag.Core.Tests/NSwag.Core.Tests.csproj index 0c5165d0a2..cc4c16e0a5 100644 --- a/src/NSwag.Core.Tests/NSwag.Core.Tests.csproj +++ b/src/NSwag.Core.Tests/NSwag.Core.Tests.csproj @@ -4,13 +4,17 @@ net8.0 false - $(NoWarn),618 + $(NoWarn),618;CA1707 + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/NSwag.Core.Tests/OperationIdTests.cs b/src/NSwag.Core.Tests/OperationIdTests.cs index 8d5af3423f..a31aa20466 100644 --- a/src/NSwag.Core.Tests/OperationIdTests.cs +++ b/src/NSwag.Core.Tests/OperationIdTests.cs @@ -1,5 +1,4 @@ -using System.Linq; -using Xunit; +using Xunit; namespace NSwag.Core.Tests { diff --git a/src/NSwag.Core.Tests/Serialization/ComponentsSerializationTests.cs b/src/NSwag.Core.Tests/Serialization/ComponentsSerializationTests.cs index 66b3dd9562..90447e56c7 100644 --- a/src/NSwag.Core.Tests/Serialization/ComponentsSerializationTests.cs +++ b/src/NSwag.Core.Tests/Serialization/ComponentsSerializationTests.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using NJsonSchema; using Xunit; diff --git a/src/NSwag.Core.Tests/Serialization/ExampleSerializationTests.cs b/src/NSwag.Core.Tests/Serialization/ExampleSerializationTests.cs index 12d656ad0b..17cba6c76f 100644 --- a/src/NSwag.Core.Tests/Serialization/ExampleSerializationTests.cs +++ b/src/NSwag.Core.Tests/Serialization/ExampleSerializationTests.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; -using System.Threading.Tasks; using NJsonSchema; using Xunit; diff --git a/src/NSwag.Core.Tests/Serialization/ExternalReferenceTests.cs b/src/NSwag.Core.Tests/Serialization/ExternalReferenceTests.cs index 03c0eabf3f..0f5f3e8962 100644 --- a/src/NSwag.Core.Tests/Serialization/ExternalReferenceTests.cs +++ b/src/NSwag.Core.Tests/Serialization/ExternalReferenceTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.Core.Tests.Serialization { diff --git a/src/NSwag.Core.Tests/Serialization/MediaTypesSerializationTests.cs b/src/NSwag.Core.Tests/Serialization/MediaTypesSerializationTests.cs index 88c3c6d917..ff598e624e 100644 --- a/src/NSwag.Core.Tests/Serialization/MediaTypesSerializationTests.cs +++ b/src/NSwag.Core.Tests/Serialization/MediaTypesSerializationTests.cs @@ -159,13 +159,13 @@ private static OpenApiDocument CreateDocument(JsonObjectType type) new OpenApiPathItem { { - OpenApiOperationMethod.Get, + OpenApiOperationMethod.Get, new OpenApiOperation { Responses = { { - "200", + "200", new OpenApiResponse { Examples = 123, diff --git a/src/NSwag.Core.Tests/Serialization/NullDefinitionTests.cs b/src/NSwag.Core.Tests/Serialization/NullDefinitionTests.cs index fbc96b8656..033ed970c6 100644 --- a/src/NSwag.Core.Tests/Serialization/NullDefinitionTests.cs +++ b/src/NSwag.Core.Tests/Serialization/NullDefinitionTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Xunit; +using Xunit; namespace NSwag.Core.Tests.Serialization { diff --git a/src/NSwag.Core.Tests/Serialization/PathItemTests.cs b/src/NSwag.Core.Tests/Serialization/PathItemTests.cs index acb89f1e43..00ea1a4f53 100644 --- a/src/NSwag.Core.Tests/Serialization/PathItemTests.cs +++ b/src/NSwag.Core.Tests/Serialization/PathItemTests.cs @@ -1,7 +1,4 @@ -using System; -using System.IO; -using System.Reflection; -using System.Threading.Tasks; +using System.Reflection; using Xunit; namespace NSwag.Core.Tests.Serialization @@ -24,7 +21,7 @@ public async Task PathItem_With_External_Ref_Can_Be_Serialized() Assert.True(getOperation.ActualResponses.ContainsKey("200")); } - private string GetTestDirectory() + private static string GetTestDirectory() { var codeBase = Assembly.GetExecutingAssembly().CodeBase; var uri = new UriBuilder(codeBase); diff --git a/src/NSwag.Core.Tests/Serialization/RequestBodySerializationTests.cs b/src/NSwag.Core.Tests/Serialization/RequestBodySerializationTests.cs index 8e27331c1d..bda4c131db 100644 --- a/src/NSwag.Core.Tests/Serialization/RequestBodySerializationTests.cs +++ b/src/NSwag.Core.Tests/Serialization/RequestBodySerializationTests.cs @@ -1,5 +1,3 @@ -using System.Linq; -using System.Threading.Tasks; using NJsonSchema; using Xunit; @@ -72,7 +70,7 @@ public async Task When_body_parameter_is_changed_then_request_body_Name_is_updat var parameter = document.Paths["/baz"][OpenApiOperationMethod.Get].Parameters .Single(p => p.Kind == OpenApiParameterKind.Body); - parameter.Name = parameter.Name + "123"; + parameter.Name += "123"; // Assert var requestBody = document.Paths["/baz"][OpenApiOperationMethod.Get].RequestBody; @@ -114,7 +112,7 @@ public async Task When_body_parameter_is_changed_then_request_body_Description_i var parameter = document.Paths["/baz"][OpenApiOperationMethod.Get].Parameters .Single(p => p.Kind == OpenApiParameterKind.Body); - parameter.Description = parameter.Description + "123"; + parameter.Description += "123"; // Assert var requestBody = document.Paths["/baz"][OpenApiOperationMethod.Get].RequestBody; @@ -134,7 +132,7 @@ public async Task When_request_body_is_changed_then_body_parameter_Name_is_updat var requestBody = document.Paths["/baz"][OpenApiOperationMethod.Get].RequestBody; - requestBody.Name = requestBody.Name + "123"; + requestBody.Name += "123"; // Assert var parameter = document.Paths["/baz"][OpenApiOperationMethod.Get].Parameters @@ -199,7 +197,7 @@ public async Task When_request_body_is_changed_then_body_parameter_Description_i document = await OpenApiDocument.FromJsonAsync(json); var requestBody = document.Paths["/baz"][OpenApiOperationMethod.Get].RequestBody; - requestBody.Description = requestBody.Description + "123"; + requestBody.Description += "123"; // Assert var parameter = document.Paths["/baz"][OpenApiOperationMethod.Get].Parameters diff --git a/src/NSwag.Core.Tests/Serialization/ServersSerializationTests.cs b/src/NSwag.Core.Tests/Serialization/ServersSerializationTests.cs index 6f6ed23ad4..0bc78d3215 100644 --- a/src/NSwag.Core.Tests/Serialization/ServersSerializationTests.cs +++ b/src/NSwag.Core.Tests/Serialization/ServersSerializationTests.cs @@ -1,5 +1,4 @@ -using System.Linq; -using NJsonSchema; +using NJsonSchema; using Xunit; namespace NSwag.Core.Tests.Serialization @@ -76,11 +75,12 @@ public void When_server_is_set_then_it_is_correctly_converted_to_Swagger() // Act var json = document.ToJson(SchemaType.Swagger2); + Assert.NotNull(json); // Assert Assert.Equal("localhost:12354", document.Host); Assert.Equal("/myapi", document.BasePath); - Assert.Equal(1, document.Schemes.Count); + Assert.Single(document.Schemes); Assert.Equal(OpenApiSchema.Http, document.Schemes.First()); } @@ -97,11 +97,12 @@ public void When_host_basePath_and_schemeas_are_set_then_it_is_correctly_convert // Act var json = document.ToJson(SchemaType.Swagger2); + Assert.NotNull(json); // Assert Assert.Equal("localhost:12354", document.Host); Assert.Equal("/myapi", document.BasePath); - Assert.Equal(1, document.Schemes.Count); + Assert.Single(document.Schemes); Assert.Equal(OpenApiSchema.Http, document.Schemes.First()); } @@ -120,6 +121,7 @@ public void When_scheme_without_host_is_added_then_servers_are_not_cleared() document.Host = "localhost:12354"; var json = document.ToJson(SchemaType.Swagger2); + Assert.NotNull(json); // Assert Assert.Equal(2, document.Servers.Count); @@ -139,6 +141,7 @@ public void When_host_is_removed_then_base_url_is_also_empty() // Act document.Host = string.Empty; var json = document.ToJson(SchemaType.Swagger2); + Assert.NotNull(json); // Assert Assert.True(string.IsNullOrEmpty(document.BaseUrl)); diff --git a/src/NSwag.Core.Tests/SwaggerResponseTests.cs b/src/NSwag.Core.Tests/SwaggerResponseTests.cs index a849deb39a..5130d0ccba 100644 --- a/src/NSwag.Core.Tests/SwaggerResponseTests.cs +++ b/src/NSwag.Core.Tests/SwaggerResponseTests.cs @@ -17,7 +17,7 @@ public void When_response_contains_produces_detect_if_binary_response(string con // Arrange var response = new OpenApiResponse(); var operation = new OpenApiOperation(); - operation.Produces = new System.Collections.Generic.List { contentType }; + operation.Produces = [contentType]; operation.Responses.Add("200", response); // Act diff --git a/src/NSwag.Core.Yaml.Tests/NSwag.Core.Yaml.Tests.csproj b/src/NSwag.Core.Yaml.Tests/NSwag.Core.Yaml.Tests.csproj index bce139d5d9..4c4f4251be 100644 --- a/src/NSwag.Core.Yaml.Tests/NSwag.Core.Yaml.Tests.csproj +++ b/src/NSwag.Core.Yaml.Tests/NSwag.Core.Yaml.Tests.csproj @@ -3,12 +3,17 @@ net8.0 false + $(NoWarn);CA1707 + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/NSwag.Core.Yaml.Tests/References/YamlReferencesTests.cs b/src/NSwag.Core.Yaml.Tests/References/YamlReferencesTests.cs index 3854da4eb3..dcab0bbc10 100644 --- a/src/NSwag.Core.Yaml.Tests/References/YamlReferencesTests.cs +++ b/src/NSwag.Core.Yaml.Tests/References/YamlReferencesTests.cs @@ -1,7 +1,4 @@ -using System; -using System.IO; -using System.Reflection; -using System.Threading.Tasks; +using System.Reflection; using NJsonSchema; using Xunit; @@ -23,13 +20,14 @@ public async Task When_yaml_schema_has_references_it_works(string relativePath) // Act var document = await OpenApiYamlDocument.FromFileAsync(path); var json = document.ToJson(); + Assert.NotNull(json); // Assert Assert.Equal(JsonObjectType.Integer, document.Definitions["ContractObject"].Properties["foo"].ActualTypeSchema.Type); Assert.Equal(JsonObjectType.Boolean, document.Definitions["ContractObject"].Properties["bar"].ActualTypeSchema.Type); } - private string GetTestDirectory() + private static string GetTestDirectory() { var codeBase = Assembly.GetExecutingAssembly().CodeBase; var uri = new UriBuilder(codeBase); diff --git a/src/NSwag.Core.Yaml.Tests/YamlDocumentTests.cs b/src/NSwag.Core.Yaml.Tests/YamlDocumentTests.cs index 42426884ae..6d09c0b636 100644 --- a/src/NSwag.Core.Yaml.Tests/YamlDocumentTests.cs +++ b/src/NSwag.Core.Yaml.Tests/YamlDocumentTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Linq; using Xunit; namespace NSwag.Core.Yaml.Tests @@ -61,8 +59,8 @@ public async Task When_yaml_with_custom_property_is_loaded_then_document_is_not_ [Fact] public async Task When_yaml_with_custom_property_which_is_an_object_is_loaded_then_document_is_not_null() { - // Arrange - var yaml = @"swagger: '2.0' + // Arrange + var yaml = @"swagger: '2.0' info: title: foo version: '1.0' @@ -75,15 +73,15 @@ public async Task When_yaml_with_custom_property_which_is_an_object_is_loaded_th '200': description: baz"; - // Act - var document = await OpenApiYamlDocument.FromYamlAsync(yaml); - yaml = document.ToYaml(); + // Act + var document = await OpenApiYamlDocument.FromYamlAsync(yaml); + yaml = document.ToYaml(); - // Assert - Assert.NotNull(document); - Assert.Equal(JObject.Parse(@"{""bar"": ""baz""}"), document.Paths.First().Value.ExtensionData["x-swagger-router-controller"]); - Assert.Equal("baz", document.Paths.First().Value["get"].Responses["200"].Description); - Assert.Contains("bar: baz", yaml); + // Assert + Assert.NotNull(document); + Assert.Equal(JObject.Parse(@"{""bar"": ""baz""}"), document.Paths.First().Value.ExtensionData["x-swagger-router-controller"]); + Assert.Equal("baz", document.Paths.First().Value["get"].Responses["200"].Description); + Assert.Contains("bar: baz", yaml); } } -} +} \ No newline at end of file diff --git a/src/NSwag.Core.Yaml/NSwag.Core.Yaml.csproj b/src/NSwag.Core.Yaml/NSwag.Core.Yaml.csproj index db48a3720e..752b49c87e 100644 --- a/src/NSwag.Core.Yaml/NSwag.Core.Yaml.csproj +++ b/src/NSwag.Core.Yaml/NSwag.Core.Yaml.csproj @@ -5,7 +5,7 @@ - + diff --git a/src/NSwag.Core.Yaml/OpenApiYamlDocument.cs b/src/NSwag.Core.Yaml/OpenApiYamlDocument.cs index 5a1ee26947..6f23050882 100644 --- a/src/NSwag.Core.Yaml/OpenApiYamlDocument.cs +++ b/src/NSwag.Core.Yaml/OpenApiYamlDocument.cs @@ -6,11 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; using System.Dynamic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using NJsonSchema; @@ -61,7 +57,7 @@ public static Task FromYamlAsync(string data, string documentPa /// The JSON reference resolver factory. /// The cancellation token. /// The . - public static async Task FromYamlAsync(string data, string documentPath, SchemaType expectedSchemaType, + public static async Task FromYamlAsync(string data, string documentPath, SchemaType expectedSchemaType, Func referenceResolverFactory, CancellationToken cancellationToken = default) { var deserializer = new DeserializerBuilder().Build(); @@ -72,7 +68,7 @@ public static async Task FromYamlAsync(string data, string docu var json = serializer.Serialize(yamlObject); - referenceResolverFactory = referenceResolverFactory ?? CreateReferenceResolverFactory(); + referenceResolverFactory ??= CreateReferenceResolverFactory(); return await OpenApiDocument.FromJsonAsync(json, documentPath, expectedSchemaType, referenceResolverFactory, cancellationToken).ConfigureAwait(false); } diff --git a/src/NSwag.Core/Collections/ObservableDictionary.cs b/src/NSwag.Core/Collections/ObservableDictionary.cs index bf024c67c3..7e27d4fd61 100644 --- a/src/NSwag.Core/Collections/ObservableDictionary.cs +++ b/src/NSwag.Core/Collections/ObservableDictionary.cs @@ -6,12 +6,9 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; using System.Collections; -using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; -using System.Linq; namespace NSwag.Collections { @@ -27,7 +24,7 @@ public class ObservableDictionary : /// Initializes a new instance of the class. public ObservableDictionary() { - _dictionary = new Dictionary(); + _dictionary = []; } /// Initializes a new instance of the class. @@ -76,7 +73,7 @@ public void AddRange(IDictionary items) { if (items == null) { - throw new ArgumentNullException("items"); + throw new ArgumentNullException(nameof(items)); } if (items.Count > 0) @@ -108,8 +105,7 @@ public void AddRange(IDictionary items) /// If true and key already exists then an exception is thrown. protected virtual void Insert(TKey key, TValue value, bool add) { - TValue item; - if (_dictionary.TryGetValue(key, out item)) + if (_dictionary.TryGetValue(key, out TValue item)) { if (add) { @@ -135,22 +131,14 @@ protected virtual void Insert(TKey key, TValue value, bool add) /// Name of the property. protected virtual void OnPropertyChanged(string propertyName) { - var copy = PropertyChanged; - if (copy != null) - { - copy(this, new PropertyChangedEventArgs(propertyName)); - } + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// Called when the collection has changed. protected void OnCollectionChanged() { OnPropertyChanged(); - var copy = CollectionChanged; - if (copy != null) - { - copy(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); - } + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } /// Called when the collection has changed. @@ -159,11 +147,7 @@ protected void OnCollectionChanged() protected void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValuePair changedItem) { OnPropertyChanged(); - var copy = CollectionChanged; - if (copy != null) - { - copy(this, new NotifyCollectionChangedEventArgs(action, changedItem, 0)); - } + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(action, changedItem, 0)); } /// Called when the collection has changed. @@ -173,11 +157,7 @@ protected void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValu protected void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValuePair newItem, KeyValuePair oldItem) { OnPropertyChanged(); - var copy = CollectionChanged; - if (copy != null) - { - copy(this, new NotifyCollectionChangedEventArgs(action, newItem, oldItem, 0)); - } + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(action, newItem, oldItem, 0)); } /// Called when the collection has changed. @@ -186,19 +166,15 @@ protected void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValu protected void OnCollectionChanged(NotifyCollectionChangedAction action, IList newItems) { OnPropertyChanged(); - var copy = CollectionChanged; - if (copy != null) - { - copy(this, new NotifyCollectionChangedEventArgs(action, newItems, 0)); - } + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(action, newItems, 0)); } private void OnPropertyChanged() { - OnPropertyChanged("Count"); + OnPropertyChanged(nameof(Count)); OnPropertyChanged("Item[]"); - OnPropertyChanged("Keys"); - OnPropertyChanged("Values"); + OnPropertyChanged(nameof(Keys)); + OnPropertyChanged(nameof(Values)); } #region IDictionary interface @@ -220,10 +196,7 @@ public bool ContainsKey(TKey key) } /// Gets an containing the keys of the . - public ICollection Keys - { - get { return _dictionary.Keys; } - } + public ICollection Keys => _dictionary.Keys; ICollection IDictionary.Values => _dictionary.Values; @@ -239,7 +212,7 @@ public virtual bool Remove(TKey key) { if (key == null) { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); } var removed = _dictionary.Remove(key); @@ -260,10 +233,7 @@ public bool TryGetValue(TKey key, out TValue value) return _dictionary.TryGetValue(key, out value); } - IEnumerable IReadOnlyDictionary.Keys - { - get { return Keys; } - } + IEnumerable IReadOnlyDictionary.Keys => Keys; /// Gets an containing the values in the . public ICollection Values => _dictionary.Values; @@ -339,7 +309,7 @@ public bool Contains(object key) IDictionaryEnumerator IDictionary.GetEnumerator() { - return ((IDictionary) _dictionary).GetEnumerator(); + return ((IDictionary)_dictionary).GetEnumerator(); } /// Removes the specified key. @@ -350,7 +320,7 @@ public void Remove(object key) } /// Gets a value indicating whether the object has a fixed size. - public bool IsFixedSize { get { return false; } } + public bool IsFixedSize => false; /// Determines whether [contains] [the specified item]. /// The item. @@ -365,7 +335,7 @@ public bool Contains(KeyValuePair item) /// Index of the array. public void CopyTo(KeyValuePair[] array, int arrayIndex) { - ((IDictionary) _dictionary).CopyTo(array, arrayIndex); + ((IDictionary)_dictionary).CopyTo(array, arrayIndex); } /// Copies to. @@ -386,12 +356,12 @@ public void CopyTo(Array array, int index) public object SyncRoot { get; private set; } /// Gets a value indicating whether the is read-only. - public bool IsReadOnly => ((IDictionary) _dictionary).IsReadOnly; + public bool IsReadOnly => ((IDictionary)_dictionary).IsReadOnly; object IDictionary.this[object key] { - get { return this[(TKey)key]; } - set { this[(TKey)key] = (TValue)value; } + get => this[(TKey)key]; + set => this[(TKey)key] = (TValue)value; } /// Removes the specified item. @@ -426,7 +396,7 @@ public Dictionary.Enumerator GetEnumerator() IEnumerator IEnumerable.GetEnumerator() { - return ((IDictionary) _dictionary).GetEnumerator(); + return ((IDictionary)_dictionary).GetEnumerator(); } #endregion diff --git a/src/NSwag.Core/HttpUtilities.cs b/src/NSwag.Core/HttpUtilities.cs index 2bb356ee4a..f814bb5c73 100644 --- a/src/NSwag.Core/HttpUtilities.cs +++ b/src/NSwag.Core/HttpUtilities.cs @@ -16,7 +16,7 @@ public static class HttpUtilities /// true if success. public static bool IsSuccessStatusCode(string statusCode) { - return statusCode.Length == 3 && statusCode.StartsWith("2"); + return statusCode.Length == 3 && statusCode.StartsWith('2'); } } } diff --git a/src/NSwag.Core/NSwag.Core.csproj b/src/NSwag.Core/NSwag.Core.csproj index d0eff34cbe..f51da79686 100644 --- a/src/NSwag.Core/NSwag.Core.csproj +++ b/src/NSwag.Core/NSwag.Core.csproj @@ -5,6 +5,6 @@ true - + \ No newline at end of file diff --git a/src/NSwag.Core/OpenApiCallback.cs b/src/NSwag.Core/OpenApiCallback.cs index 011984b28b..bd1a1ad0f7 100644 --- a/src/NSwag.Core/OpenApiCallback.cs +++ b/src/NSwag.Core/OpenApiCallback.cs @@ -9,7 +9,6 @@ using Newtonsoft.Json; using NJsonSchema.References; using System.Collections; -using System.Collections.Generic; namespace NSwag { @@ -18,7 +17,7 @@ public class OpenApiCallback : JsonReferenceBase, IJsonReferenc { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - private IDictionary _dictionary = new Dictionary(); + private readonly IDictionary _dictionary = new Dictionary(); /// Gets the actual callback, either this or the referenced example. [JsonIgnore] diff --git a/src/NSwag.Core/OpenApiComponents.cs b/src/NSwag.Core/OpenApiComponents.cs index 985c04f454..9e6fe57ca3 100644 --- a/src/NSwag.Core/OpenApiComponents.cs +++ b/src/NSwag.Core/OpenApiComponents.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using Newtonsoft.Json; using NJsonSchema; using NSwag.Collections; diff --git a/src/NSwag.Core/OpenApiDocument.Serialization.cs b/src/NSwag.Core/OpenApiDocument.Serialization.cs index 58498b2184..777d75930d 100644 --- a/src/NSwag.Core/OpenApiDocument.Serialization.cs +++ b/src/NSwag.Core/OpenApiDocument.Serialization.cs @@ -10,20 +10,17 @@ using Newtonsoft.Json.Converters; using NJsonSchema; using NJsonSchema.Infrastructure; -using System; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; -using System.Linq; namespace NSwag { public partial class OpenApiDocument { - private static Lazy Swagger2ContractResolver = + private static readonly Lazy Swagger2ContractResolver = new Lazy(() => CreateJsonSerializerContractResolver(SchemaType.Swagger2)); - private static Lazy OpenApi3ContractResolver = + private static readonly Lazy OpenApi3ContractResolver = new Lazy(() => CreateJsonSerializerContractResolver(SchemaType.OpenApi3)); /// Creates the serializer contract resolver based on the . @@ -116,14 +113,14 @@ private static PropertyRenameAndIgnoreSerializerContractResolver CreateJsonSeria return resolver; } - private ObservableCollection _schemes = new ObservableCollection(); + private ObservableCollection _schemes = []; /// Gets or sets the host (name or ip) serving the API (Swagger only). [JsonProperty(PropertyName = "host", Order = 5, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public string Host { - get { return Servers?.FirstOrDefault()?.Url?.Replace("http://", "").Replace("https://", "").Split('/')[0]; } - set { UpdateServers(Schemes, value, BasePath); } + get => Servers?.FirstOrDefault()?.Url?.Replace("http://", "").Replace("https://", "").Split('/')[0]; + set => UpdateServers(Schemes, value, BasePath); } /// Gets or sets the base path on which the API is served, which is relative to the . @@ -135,7 +132,7 @@ public string BasePath var segments = Servers?.FirstOrDefault()?.Url?.Replace("http://", "").Replace("https://", "").Split('/').Skip(1).ToArray(); return segments != null && segments.Length > 0 ? "/" + string.Join("/", segments) : null; } - set { UpdateServers(Schemes, Host, value); } + set => UpdateServers(Schemes, Host, value); } /// Gets or sets the schemes. @@ -151,14 +148,14 @@ public ICollection Schemes _schemes = new ObservableCollection(Servers? .Where(s => s.Url.Contains("://")) - .Select(s => s.Url.StartsWith("http://") ? OpenApiSchema.Http : OpenApiSchema.Https) - .Distinct() ?? new List()); + .Select(s => s.Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? OpenApiSchema.Http : OpenApiSchema.Https) + .Distinct() ?? []); _schemes.CollectionChanged += OnSchemesChanged; return _schemes; } - set { UpdateServers(value, Host, BasePath); } + set => UpdateServers(value, Host, BasePath); } private void OnSchemesChanged(object sender, NotifyCollectionChangedEventArgs e) @@ -170,30 +167,30 @@ private void UpdateServers(ICollection schemes, string host, stri { if ((schemes == null || schemes.Count == 0) && (!string.IsNullOrEmpty(host) || !string.IsNullOrEmpty(basePath))) { - Servers = new List - { + Servers = + [ new OpenApiServer { Url = host + basePath } - }; + ]; } else { Servers = schemes?.Select(s => new OpenApiServer { Url = s.ToString().ToLowerInvariant() + "://" + host + basePath - }).ToList() ?? new List(); + }).ToList() ?? []; } } /// Gets or sets a list of MIME types the operation can consume. [JsonProperty(PropertyName = "consumes", Order = 8, DefaultValueHandling = DefaultValueHandling.Ignore)] - public ICollection Consumes { get; set; } = new List(); + public ICollection Consumes { get; set; } = []; /// Gets or sets a list of MIME types the operation can produce. [JsonProperty(PropertyName = "produces", Order = 9, DefaultValueHandling = DefaultValueHandling.Ignore)] - public ICollection Produces { get; set; } = new List(); + public ICollection Produces { get; set; } = []; /// Gets or sets the types (Swagger only). [JsonProperty(PropertyName = "definitions", Order = 13, DefaultValueHandling = DefaultValueHandling.Ignore)] diff --git a/src/NSwag.Core/OpenApiDocument.cs b/src/NSwag.Core/OpenApiDocument.cs index b915a5c1ba..f664c5b4e7 100644 --- a/src/NSwag.Core/OpenApiDocument.cs +++ b/src/NSwag.Core/OpenApiDocument.cs @@ -6,15 +6,8 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.IO; -using System.Linq; using System.Reflection; using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; using Newtonsoft.Json; using NJsonSchema; using NJsonSchema.Generation; @@ -81,7 +74,7 @@ public OpenApiDocument() /// Gets or sets the servers (OpenAPI only). [JsonProperty(PropertyName = "servers", Order = 10, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public ICollection Servers { get; private set; } = new Collection(); + public ICollection Servers { get; private set; } = []; /// Gets or sets the operations. [JsonProperty(PropertyName = "paths", Order = 11, DefaultValueHandling = DefaultValueHandling.Ignore)] @@ -93,11 +86,11 @@ public OpenApiDocument() /// Gets or sets a security description. [JsonProperty(PropertyName = "security", Order = 17, DefaultValueHandling = DefaultValueHandling.Ignore)] - public ICollection Security { get; set; } = new Collection(); + public ICollection Security { get; set; } = []; /// Gets or sets the description. [JsonProperty(PropertyName = "tags", Order = 18, DefaultValueHandling = DefaultValueHandling.Ignore)] - public IList Tags { get; set; } = new Collection(); + public IList Tags { get; set; } = []; /// Gets the base URL of the web service. [JsonIgnore] @@ -182,14 +175,14 @@ public static async Task FromJsonAsync(string data, string docu var match = Regex.Match(data, pattern, RegexOptions.IgnoreCase); if (match.Success) { - var schemaType = match.Groups["schemaType"].Value.ToLower(); - var schemaVersion = match.Groups["schemaVersion"].Value.ToLower(); + var schemaType = match.Groups["schemaType"].Value.ToLowerInvariant(); + var schemaVersion = match.Groups["schemaVersion"].Value.ToLowerInvariant(); - if (schemaType == "swagger" && schemaVersion.StartsWith("2")) + if (schemaType == "swagger" && schemaVersion.StartsWith('2')) { expectedSchemaType = SchemaType.Swagger2; } - else if (schemaType == "openapi" && schemaVersion.StartsWith("3")) + else if (schemaType == "openapi" && schemaVersion.StartsWith('3')) { expectedSchemaType = SchemaType.OpenApi3; } @@ -279,7 +272,10 @@ public void GenerateOperationIds() HttpUtilities.IsSuccessStatusCode(r.Key) && r.Value.Schema?.ActualSchema.Type == JsonObjectType.Array)); // if we have just collections, adding All will not help in discrimination - if (collections.Count() == group.Count()) continue; + if (collections.Count() == group.Count()) + { + continue; + } foreach (var o in group) { @@ -300,12 +296,15 @@ public void GenerateOperationIds() { if (group.Count() > 1) { - var methods = group.Select(o => o.Method.ToUpper()).Distinct(); - if (methods.Count() == 1) continue; + var methods = group.Select(o => o.Method.ToUpperInvariant()).Distinct(); + if (methods.Count() == 1) + { + continue; + } foreach (var o in group) { - o.Operation.OperationId += o.Method.ToUpper(); + o.Operation.OperationId += o.Method.ToUpperInvariant(); } } } @@ -329,7 +328,7 @@ public void GenerateOperationIds() } } - private string GetOperationNameFromPath(OpenApiOperationDescription operation) + private static string GetOperationNameFromPath(OpenApiOperationDescription operation) { var pathSegments = operation.Path.Trim('/').Split('/'); var lastPathSegment = pathSegments.LastOrDefault(s => !s.Contains("{")); diff --git a/src/NSwag.Core/OpenApiEncoding.cs b/src/NSwag.Core/OpenApiEncoding.cs index 7a90322cf0..177d93bc05 100644 --- a/src/NSwag.Core/OpenApiEncoding.cs +++ b/src/NSwag.Core/OpenApiEncoding.cs @@ -19,7 +19,7 @@ public class OpenApiEncoding /// Gets or sets the headers. [JsonProperty(PropertyName = "headers", DefaultValueHandling = DefaultValueHandling.Ignore)] - public OpenApiHeaders Headers { get; } = new OpenApiHeaders(); + public OpenApiHeaders Headers { get; } = []; /// Gets or sets the encoding type. [JsonProperty(PropertyName = "style", DefaultValueHandling = DefaultValueHandling.Ignore)] diff --git a/src/NSwag.Core/OpenApiLink.cs b/src/NSwag.Core/OpenApiLink.cs index 919aa0e24c..6260608768 100644 --- a/src/NSwag.Core/OpenApiLink.cs +++ b/src/NSwag.Core/OpenApiLink.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; using Newtonsoft.Json; using NJsonSchema.References; diff --git a/src/NSwag.Core/OpenApiMediaType.cs b/src/NSwag.Core/OpenApiMediaType.cs index 3ed4e81735..5445bb53f8 100644 --- a/src/NSwag.Core/OpenApiMediaType.cs +++ b/src/NSwag.Core/OpenApiMediaType.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; using Newtonsoft.Json; using NJsonSchema; diff --git a/src/NSwag.Core/OpenApiOAuthFlow.cs b/src/NSwag.Core/OpenApiOAuthFlow.cs index 2b2ef2874b..a387f0dbef 100644 --- a/src/NSwag.Core/OpenApiOAuthFlow.cs +++ b/src/NSwag.Core/OpenApiOAuthFlow.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; using Newtonsoft.Json; namespace NSwag diff --git a/src/NSwag.Core/OpenApiOperation.cs b/src/NSwag.Core/OpenApiOperation.cs index a02a600433..beb123a6fb 100644 --- a/src/NSwag.Core/OpenApiOperation.cs +++ b/src/NSwag.Core/OpenApiOperation.cs @@ -6,10 +6,8 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; -using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using NJsonSchema; @@ -23,13 +21,13 @@ public class OpenApiOperation : JsonExtensionObject { private OpenApiRequestBody _requestBody; - private bool _disableRequestBodyUpdate = false; - private bool _disableBodyParameterUpdate = false; + private bool _disableRequestBodyUpdate; + private bool _disableBodyParameterUpdate; /// Initializes a new instance of the class. public OpenApiOperation() { - Tags = new List(); + Tags = []; var parameters = new ObservableCollection(); parameters.CollectionChanged += (sender, args) => @@ -154,7 +152,7 @@ public IReadOnlyList ActualParameters /// Gets or sets the servers (OpenAPI only). [JsonProperty(PropertyName = "servers", Order = 15, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public ICollection Servers { get; set; } = new Collection(); + public ICollection Servers { get; set; } = []; /// Gets the list of MIME types the operation can consume, either from the operation or from the . [JsonIgnore] @@ -186,7 +184,7 @@ public void TryAddConsumes(string mimeType) { if (Consumes == null) { - Consumes = new List { mimeType }; + Consumes = [mimeType]; } else if (!Consumes.Contains(mimeType)) { @@ -226,11 +224,7 @@ internal void UpdateRequestBody(OpenApiParameter parameter) if (parameter.Kind == OpenApiParameterKind.Body) { - if (RequestBody == null) - { - RequestBody = new OpenApiRequestBody(); - } - + RequestBody ??= new OpenApiRequestBody(); RequestBody.Name = parameter.Name; RequestBody.Position = parameter.Position; RequestBody.Description = parameter.Description; diff --git a/src/NSwag.Core/OpenApiOperationDescription.cs b/src/NSwag.Core/OpenApiOperationDescription.cs index 27fa19cdf2..fffee59d9f 100644 --- a/src/NSwag.Core/OpenApiOperationDescription.cs +++ b/src/NSwag.Core/OpenApiOperationDescription.cs @@ -15,7 +15,7 @@ public class OpenApiOperationDescription public string Path { get; set; } /// Gets or sets the HTTP method. - public string Method { get; set; } + public string Method { get; set; } /// Gets or sets the operation. public OpenApiOperation Operation { get; set; } diff --git a/src/NSwag.Core/OpenApiParameter.cs b/src/NSwag.Core/OpenApiParameter.cs index 316f4a5c30..176ff11ceb 100644 --- a/src/NSwag.Core/OpenApiParameter.cs +++ b/src/NSwag.Core/OpenApiParameter.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using System.Text.RegularExpressions; using Newtonsoft.Json; using NJsonSchema; @@ -21,7 +18,7 @@ public class OpenApiParameter : JsonSchema private string _name; private OpenApiParameterKind _kind; private OpenApiParameterStyle _style; - private bool _isRequired = false; + private bool _isRequired; private JsonSchema _schema; private IDictionary _examples; private bool _explode; @@ -29,8 +26,7 @@ public class OpenApiParameter : JsonSchema private static readonly Regex AppJsonRegex = new Regex(@"application\/(\S+?)?\+?json;?(\S+)?"); - [JsonIgnore] - internal OpenApiOperation ParentOperation => Parent as OpenApiOperation; + [JsonIgnore] internal OpenApiOperation ParentOperation => Parent as OpenApiOperation; /// Gets or sets the name. [JsonProperty(PropertyName = "name", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] @@ -187,7 +183,7 @@ public override bool IsNullable(SchemaType schemaType) { if (IsNullableRaw == null) { - return IsRequired == false; + return !IsRequired; } return IsNullableRaw.Value; @@ -223,13 +219,12 @@ public bool IsXmlBodyParameter } var parent = Parent as OpenApiOperation; - var consumes = parent?.ActualConsumes?.Any() == true ? - parent.ActualConsumes : - parent?.ActualRequestBody?.Content.Keys; + var consumes = parent?.ActualConsumes?.Count > 0 + ? parent.ActualConsumes + : parent?.ActualRequestBody?.Content.Keys; - return consumes?.Any() == true && - consumes.Any(p => p.Contains("application/xml")) && - consumes.Any(p => AppJsonRegex.IsMatch(p)) == false; + return consumes?.Count > 0 && consumes.Any(p => p.Contains("application/xml")) && + !consumes.Any(p => AppJsonRegex.IsMatch(p)); } } @@ -245,22 +240,20 @@ public bool IsBinaryBodyParameter } var parent = Parent as OpenApiOperation; - if (parent?.ActualConsumes?.Any() == true) + if (parent?.ActualConsumes?.Count > 0) { var consumes = parent.ActualConsumes; - return consumes?.Any() == true && - (Schema?.IsBinary != false || - consumes.Contains("multipart/form-data")) && - consumes?.Any(p => p.Contains("*/*")) == false && - consumes.Any(p => AppJsonRegex.IsMatch(p)) == false; + return consumes?.Count > 0 + && (Schema?.IsBinary != false || consumes.Contains("multipart/form-data")) + && consumes?.Any(p => p.Contains("*/*")) == false + && !consumes.Any(p => AppJsonRegex.IsMatch(p)); } else { var consumes = parent?.ActualRequestBody?.Content; - return (consumes?.Any(p => p.Key == "multipart/form-data") == true || - consumes?.Any(p => p.Value.Schema?.IsBinary != false) == true) && - consumes.Any(p => p.Key.Contains("*/*") && p.Value.Schema?.IsBinary != true) == false && - consumes.Any(p => AppJsonRegex.IsMatch(p.Key) && p.Value.Schema?.IsBinary != true) == false; + return (consumes?.Any(p => p.Key == "multipart/form-data") == true || consumes?.Any(p => p.Value.Schema?.IsBinary != false) == true) + && !consumes.Any(p => p.Key.Contains("*/*") && p.Value.Schema?.IsBinary != true) + && !consumes.Any(p => AppJsonRegex.IsMatch(p.Key) && p.Value.Schema?.IsBinary != true); } } } @@ -277,21 +270,21 @@ public bool HasBinaryBodyWithMultipleMimeTypes } var parent = Parent as OpenApiOperation; - if (parent?.ActualConsumes?.Any() == true) + if (parent?.ActualConsumes?.Count > 0) { var consumes = parent.ActualConsumes; - return consumes?.Any() == true && - (consumes.Count() > 1 || + return consumes?.Count > 0 && + (consumes.Count > 1 || consumes.Any(p => p.Contains("*"))); } else { var consumes = parent?.ActualRequestBody?.Content; return consumes?.Any() == true && - (consumes.Count() > 1 || + (consumes.Count > 1 || consumes.Any(p => p.Key.Contains("*"))); } } } } -} +} \ No newline at end of file diff --git a/src/NSwag.Core/OpenApiPathItem.cs b/src/NSwag.Core/OpenApiPathItem.cs index 5b5afa3c6d..d74ef60bc1 100644 --- a/src/NSwag.Core/OpenApiPathItem.cs +++ b/src/NSwag.Core/OpenApiPathItem.cs @@ -6,10 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Linq; using Newtonsoft.Json; using NJsonSchema.References; using NSwag.Collections; @@ -50,11 +47,11 @@ public OpenApiPathItem() /// Gets or sets the servers (OpenAPI only). [JsonProperty(PropertyName = "servers", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public ICollection Servers { get; set; } = new Collection(); + public ICollection Servers { get; set; } = []; /// Gets or sets the parameters. [JsonProperty(PropertyName = "parameters", DefaultValueHandling = DefaultValueHandling.Ignore)] - public ICollection Parameters { get; set; } = new Collection(); + public ICollection Parameters { get; set; } = []; /// Gets or sets the extension data (i.e. additional properties which are not directly defined by the JSON object). [JsonExtensionData] @@ -104,7 +101,7 @@ IJsonReference IJsonReferenceBase.Reference #endregion // Needed to convert dictionary keys to lower case - internal class OpenApiPathItemConverter : JsonConverter + internal sealed class OpenApiPathItemConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { @@ -132,13 +129,13 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s } } - if (operations.Parameters != null && operations.Parameters.Any()) + if (operations.Parameters != null && operations.Parameters.Count > 0) { writer.WritePropertyName("parameters"); serializer.Serialize(writer, operations.Parameters); } - if (operations.Servers != null && operations.Servers.Any()) + if (operations.Servers != null && operations.Servers.Count > 0) { writer.WritePropertyName("servers"); serializer.Serialize(writer, operations.Servers); @@ -184,11 +181,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist } else if (propertyName.StartsWith("x-", StringComparison.OrdinalIgnoreCase)) { - if (operations.ExtensionData == null) - { - operations.ExtensionData = new Dictionary(); - } - + operations.ExtensionData ??= new Dictionary(); operations.ExtensionData[propertyName] = serializer.Deserialize(reader); } else if (propertyName.Contains("$ref")) diff --git a/src/NSwag.Core/OpenApiRequestBody.cs b/src/NSwag.Core/OpenApiRequestBody.cs index 5663eb8f15..7fe5036df5 100644 --- a/src/NSwag.Core/OpenApiRequestBody.cs +++ b/src/NSwag.Core/OpenApiRequestBody.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; using Newtonsoft.Json; using NJsonSchema.References; using NSwag.Collections; @@ -102,7 +101,7 @@ public int? Position /// Gets the actual name of the request body parameter. [JsonIgnore] public string ActualName => string.IsNullOrEmpty(Name) ? "body" : Name; - + #region Implementation of IJsonReference [JsonIgnore] diff --git a/src/NSwag.Core/OpenApiResponse.cs b/src/NSwag.Core/OpenApiResponse.cs index 2c063fc019..3dce46813d 100644 --- a/src/NSwag.Core/OpenApiResponse.cs +++ b/src/NSwag.Core/OpenApiResponse.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using System.Text.RegularExpressions; using Newtonsoft.Json; using NJsonSchema; @@ -19,7 +17,7 @@ namespace NSwag public class OpenApiResponse : JsonReferenceBase, IJsonReference { // (RegexOptions) 0x0008 = Compiled - private static readonly Regex AppJsonRegex = new Regex(@"application\/(\S+?)?\+?json;?(\S+)?", (RegexOptions) 0x0008); + private static readonly Regex AppJsonRegex = new Regex(@"application\/(\S+?)?\+?json;?(\S+)?", (RegexOptions)0x0008); /// Gets or sets the extension data (i.e. additional properties which are not directly defined by the JSON object). [JsonExtensionData] @@ -39,7 +37,7 @@ public class OpenApiResponse : JsonReferenceBase, IJsonReferenc /// Gets or sets the headers. [JsonProperty(PropertyName = "headers", Order = 3, DefaultValueHandling = DefaultValueHandling.Ignore)] - public OpenApiHeaders Headers { get; } = new OpenApiHeaders(); + public OpenApiHeaders Headers { get; } = []; /// Sets a value indicating whether the response can be null (use IsNullable() to get a parameter's nullability). /// The Swagger spec does not support null in schemas, see https://github.com/OAI/OpenAPI-Specification/issues/229 diff --git a/src/NSwag.Core/OpenApiSchemaResolver.cs b/src/NSwag.Core/OpenApiSchemaResolver.cs index 4455fc5db8..9586874c63 100644 --- a/src/NSwag.Core/OpenApiSchemaResolver.cs +++ b/src/NSwag.Core/OpenApiSchemaResolver.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; using NJsonSchema; using NJsonSchema.Generation; diff --git a/src/NSwag.Core/OpenApiSecurityRequirement.cs b/src/NSwag.Core/OpenApiSecurityRequirement.cs index 2409e64f2e..3566c545e5 100644 --- a/src/NSwag.Core/OpenApiSecurityRequirement.cs +++ b/src/NSwag.Core/OpenApiSecurityRequirement.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; - namespace NSwag { /// The operation security requirements. diff --git a/src/NSwag.Core/OpenApiSecurityScheme.cs b/src/NSwag.Core/OpenApiSecurityScheme.cs index 416d002086..50f8206fde 100644 --- a/src/NSwag.Core/OpenApiSecurityScheme.cs +++ b/src/NSwag.Core/OpenApiSecurityScheme.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using NJsonSchema; diff --git a/src/NSwag.Core/OpenApiServer.cs b/src/NSwag.Core/OpenApiServer.cs index ca29dc6bc1..c48ee87ef1 100644 --- a/src/NSwag.Core/OpenApiServer.cs +++ b/src/NSwag.Core/OpenApiServer.cs @@ -7,7 +7,6 @@ //----------------------------------------------------------------------- using Newtonsoft.Json; -using System.Collections.Generic; namespace NSwag { diff --git a/src/NSwag.Core/OpenApiServerVariable.cs b/src/NSwag.Core/OpenApiServerVariable.cs index 0401e75483..436c6de2eb 100644 --- a/src/NSwag.Core/OpenApiServerVariable.cs +++ b/src/NSwag.Core/OpenApiServerVariable.cs @@ -7,8 +7,6 @@ //----------------------------------------------------------------------- using Newtonsoft.Json; -using System.Collections.Generic; -using System.Collections.ObjectModel; namespace NSwag { @@ -17,7 +15,7 @@ public class OpenApiServerVariable { /// Gets or sets the enum of the server. [JsonProperty(PropertyName = "enum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public ICollection Enum { get; } = new Collection(); + public ICollection Enum { get; } = []; /// Gets or sets the variables of the server. [JsonProperty(PropertyName = "default", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] diff --git a/src/NSwag.Core/Polyfills.cs b/src/NSwag.Core/Polyfills.cs new file mode 100644 index 0000000000..8453ce3f50 --- /dev/null +++ b/src/NSwag.Core/Polyfills.cs @@ -0,0 +1,10 @@ +namespace NSwag; + +internal static class Polyfills +{ +#if !NETCOREAPP + public static bool StartsWith(this string str, char c) => str.Length > 0 && str[0] == c; + public static bool EndsWith(this string str, char c) => str.Length > 0 && str[str.Length - 1] == c; + public static bool Contains(this string str, string s, StringComparison comparison) => str.IndexOf(s, comparison) != -1; +#endif +} \ No newline at end of file diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Inheritance/BaseController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Inheritance/BaseController.cs index 250cd1b359..1c1b6c5974 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Inheritance/BaseController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Inheritance/BaseController.cs @@ -8,7 +8,7 @@ public abstract class BaseController : Controller [HttpGet("response")] public TResponse GetResponse() { - return default(TResponse); + return default; } } } diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/LanguagesController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/LanguagesController.cs index 51709c90c0..c9271b87a5 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/LanguagesController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/LanguagesController.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers { diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/ComplexQueryParametersController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/ComplexQueryParametersController.cs index a800992058..2ba0c5b582 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/ComplexQueryParametersController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/ComplexQueryParametersController.cs @@ -8,7 +8,7 @@ public class ComplexQueryParametersController : Controller { /// Foo. [HttpGet] - public ActionResult GetList([FromQuery]GetListCommand getListCommand) + public ActionResult GetList([FromQuery] GetListCommand getListCommand) { return Ok(); } diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/DefaultParametersController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/DefaultParametersController.cs index e149224837..e77b72b9f8 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/DefaultParametersController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/DefaultParametersController.cs @@ -18,7 +18,9 @@ public ActionResult WithDefaultEnum(MyEnum parameter = MyEnum.Def) return Ok(); } +#pragma warning disable CA1711 public enum MyEnum +#pragma warning restore CA1711 { Abc, Def diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/EmptyPathController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/EmptyPathController.cs index bb9b66e912..b81922efd8 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/EmptyPathController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/EmptyPathController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters { @@ -10,7 +9,7 @@ public class EmptyPathController : ControllerBase [HttpGet] public IEnumerable Get() { - return new[] { "value1", "value2" }; + return ["value1", "value2"]; } } } \ No newline at end of file diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/FileUploadController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/FileUploadController.cs index 7ac69dd5dd..e946478ce6 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/FileUploadController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/FileUploadController.cs @@ -1,8 +1,6 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using NJsonSchema.Annotations; using System.ComponentModel.DataAnnotations; -using System.Threading.Tasks; namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters { @@ -11,13 +9,13 @@ namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters public class FileUploadController : Controller { [HttpPost("UploadFile")] - public ActionResult UploadFile([NotNull] IFormFile file, [FromForm, NotNull]string test) + public ActionResult UploadFile([NotNull] IFormFile file, [FromForm, NotNull] string test) { return Ok(); } [HttpPost("UploadFiles")] - public ActionResult UploadFiles([NotNull, FromForm] IFormFile[] files, [FromForm, NotNull]string test) + public ActionResult UploadFiles([NotNull, FromForm] IFormFile[] files, [FromForm, NotNull] string test) { return Ok(); } diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/PathParameterWithModelBinderController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/PathParameterWithModelBinderController.cs index 2c66cf60c6..032580d4f0 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/PathParameterWithModelBinderController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/PathParameterWithModelBinderController.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Requests/MultipartConsumesController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Requests/MultipartConsumesController.cs index 525b9b67b0..eeb297357a 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Requests/MultipartConsumesController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Requests/MultipartConsumesController.cs @@ -1,5 +1,4 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers.Requests { diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Responses/NullableResponseController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Responses/NullableResponseController.cs index 257361bacd..310dc01b9d 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Responses/NullableResponseController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Responses/NullableResponseController.cs @@ -1,5 +1,4 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers.Responses { diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Responses/WrappedResponseController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Responses/WrappedResponseController.cs index 1f9ac39d0e..59a641d42e 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Responses/WrappedResponseController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Responses/WrappedResponseController.cs @@ -1,57 +1,51 @@ -using System; -using System.Threading.Tasks; - -using Microsoft.AspNetCore.Mvc; - -using NSwag.Annotations; +using Microsoft.AspNetCore.Mvc; namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers.Responses { [ApiController] - [Route( "api/wrappedresponse" )] + [Route("api/wrappedresponse")] public class WrappedResponseController : Controller { - - [HttpGet( "task" )] - public async Task Task() + [HttpGet("task")] + public Task Task() { throw new NotImplementedException(); } - [HttpGet( "int" )] + [HttpGet("int")] public int Int() { throw new NotImplementedException(); } - [HttpGet( "taskofint" )] - public async Task TaskOfInt() + [HttpGet("taskofint")] + public Task TaskOfInt() { throw new NotImplementedException(); } - [HttpGet( "valuetaskofint" )] - public async ValueTask ValueTaskOfInt() + [HttpGet("valuetaskofint")] + public ValueTask ValueTaskOfInt() { throw new NotImplementedException(); } - [HttpGet( "actionresultofint" )] + [HttpGet("actionresultofint")] public ActionResult ActionResultOfInt() { throw new NotImplementedException(); } - [HttpGet( "taskofactionresultofint" )] - public async Task> TaskOfActionResultOfInt() + [HttpGet("taskofactionresultofint")] + public Task> TaskOfActionResultOfInt() { throw new NotImplementedException(); } - [HttpGet( "valuetaskofactionresultofint" )] - public async ValueTask> ValueTaskOfActionResultOfInt() + [HttpGet("valuetaskofactionresultofint")] + public ValueTask> ValueTaskOfActionResultOfInt() { throw new NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/ResponsesController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/ResponsesController.cs index e1294000d4..010eeea25e 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/ResponsesController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/ResponsesController.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using NSwag.Annotations; namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/VersionedV3ValuesController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/VersionedV3ValuesController.cs index d01d2bfbef..acda39d2e0 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/VersionedV3ValuesController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/VersionedV3ValuesController.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using NSwag.Annotations; diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/VersionedValuesController.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/VersionedValuesController.cs index 8d7f1d53f1..d172305e5b 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/VersionedValuesController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/VersionedValuesController.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using NSwag.Annotations; namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/CustomTextInputFormatter.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/CustomTextInputFormatter.cs index ff5f9381eb..fbd96454a7 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/CustomTextInputFormatter.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/CustomTextInputFormatter.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Mvc.Formatters; using System.Text; -using System.Threading.Tasks; using Microsoft.Net.Http.Headers; namespace NSwag.Generation.AspNetCore.Tests.Web diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/CustomTextOutputFormatter.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/CustomTextOutputFormatter.cs index f9d1022b8e..365f9c97c9 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/CustomTextOutputFormatter.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/CustomTextOutputFormatter.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Mvc.Formatters; using System.Text; -using System.Threading.Tasks; using Microsoft.Net.Http.Headers; namespace NSwag.Generation.AspNetCore.Tests.Web diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/NSwag.Generation.AspNetCore.Tests.Web.csproj b/src/NSwag.Generation.AspNetCore.Tests.Web/NSwag.Generation.AspNetCore.Tests.Web.csproj index d0e8b4d6bf..03bfe5b7c4 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/NSwag.Generation.AspNetCore.Tests.Web.csproj +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/NSwag.Generation.AspNetCore.Tests.Web.csproj @@ -1,9 +1,9 @@  - net6.0;net8.0 + net8.0;net9.0 true - $(NoWarn),618,1591 + $(NoWarn),618,1591;CS8603;CS8618;CS8625;CA1861 enable diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Program.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Program.cs index 4b0b7e3be2..b40c926c71 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Program.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Program.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Hosting; namespace NSwag.Generation.AspNetCore.Tests.Web { diff --git a/src/NSwag.Generation.AspNetCore.Tests.Web/Startup.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Startup.cs index 2308395f74..92f4804a51 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Startup.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Startup.cs @@ -1,8 +1,5 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.AspNetCore.Mvc.Versioning; +using Microsoft.AspNetCore.Mvc.Versioning; +using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment; namespace NSwag.Generation.AspNetCore.Tests.Web { @@ -39,17 +36,17 @@ public void ConfigureServices(IServiceCollection services) .AddSwaggerDocument(document => { document.DocumentName = "v1"; - document.ApiGroupNames = new[] { "1" }; + document.ApiGroupNames = ["1"]; }) .AddSwaggerDocument(document => { document.DocumentName = "v2"; - document.ApiGroupNames = new[] { "2" }; + document.ApiGroupNames = ["2"]; }) .AddSwaggerDocument(document => { document.DocumentName = "v3"; - document.ApiGroupNames = new[] { "3" }; + document.ApiGroupNames = ["3"]; }); } diff --git a/src/NSwag.Generation.AspNetCore.Tests/ApiVersionProcessorWithAspNetCoreTests.cs b/src/NSwag.Generation.AspNetCore.Tests/ApiVersionProcessorWithAspNetCoreTests.cs index 5ac487cac0..6a8480a37e 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/ApiVersionProcessorWithAspNetCoreTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/ApiVersionProcessorWithAspNetCoreTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers; using Xunit; @@ -14,7 +12,7 @@ public async Task When_api_version_parameter_should_be_ignored_then_it_is_ignore { // Arrange var settings = new AspNetCoreOpenApiDocumentGeneratorSettings { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 } }; - settings.ApiGroupNames = new[] { "1" }; + settings.ApiGroupNames = ["1"]; // Act var document = await GenerateDocumentAsync(settings, typeof(VersionedValuesController), typeof(VersionedV3ValuesController)); @@ -30,7 +28,7 @@ public async Task When_generating_v1_then_only_v1_operations_are_included() { // Arrange var settings = new AspNetCoreOpenApiDocumentGeneratorSettings { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 } }; - settings.ApiGroupNames = new[] { "1" }; + settings.ApiGroupNames = ["1"]; // Act var document = await GenerateDocumentAsync(settings, typeof(VersionedValuesController), typeof(VersionedV3ValuesController)); @@ -43,7 +41,7 @@ public async Task When_generating_v1_then_only_v1_operations_are_included() Assert.True(operations.All(o => o.Path.Contains("/v1/"))); // VersionedIgnoredValues tag should not be in json document - Assert.Equal(1, document.Tags.Count); + Assert.Single(document.Tags); } [Fact] @@ -51,7 +49,7 @@ public async Task When_generating_v2_then_only_v2_operations_are_included() { // Arrange var settings = new AspNetCoreOpenApiDocumentGeneratorSettings { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 } }; - settings.ApiGroupNames = new[] { "2" }; + settings.ApiGroupNames = ["2"]; // Act var document = await GenerateDocumentAsync(settings, typeof(VersionedValuesController), typeof(VersionedV3ValuesController)); @@ -64,7 +62,7 @@ public async Task When_generating_v2_then_only_v2_operations_are_included() Assert.True(operations.All(o => o.Operation.IsDeprecated)); // VersionedIgnoredValues tag should not be in json document - Assert.Equal(1, document.Tags.Count); + Assert.Single(document.Tags); } [Fact] @@ -72,7 +70,7 @@ public async Task When_generating_v3_then_only_v3_operations_are_included() { // Arrange var settings = new AspNetCoreOpenApiDocumentGeneratorSettings { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 } }; - settings.ApiGroupNames = new[] { "3" }; + settings.ApiGroupNames = ["3"]; // Act var document = await GenerateDocumentAsync(settings, typeof(VersionedValuesController), typeof(VersionedV3ValuesController)); @@ -84,7 +82,7 @@ public async Task When_generating_v3_then_only_v3_operations_are_included() Assert.True(operations.All(o => o.Path.Contains("/v3/"))); // VersionedIgnoredValues tag should not be in json document - Assert.Equal(1, document.Tags.Count); + Assert.Single(document.Tags); } [Fact] @@ -92,7 +90,7 @@ public async Task When_generating_versioned_controllers_then_version_path_parame { // Arrange var settings = new AspNetCoreOpenApiDocumentGeneratorSettings { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 } }; - settings.ApiGroupNames = new[] { "3" }; + settings.ApiGroupNames = ["3"]; // Act var document = await GenerateDocumentAsync(settings, typeof(VersionedValuesController), typeof(VersionedV3ValuesController)); diff --git a/src/NSwag.Generation.AspNetCore.Tests/AspNetCoreTestsBase.cs b/src/NSwag.Generation.AspNetCore.Tests/AspNetCoreTestsBase.cs index 4a3fb517af..9cd131756c 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/AspNetCoreTestsBase.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/AspNetCoreTestsBase.cs @@ -1,11 +1,6 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc.ApiExplorer; +using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; using NSwag.Generation.AspNetCore.Tests.Web; namespace NSwag.Generation.AspNetCore.Tests diff --git a/src/NSwag.Generation.AspNetCore.Tests/AspNetCoreToSwaggerGenerationTests.cs b/src/NSwag.Generation.AspNetCore.Tests/AspNetCoreToSwaggerGenerationTests.cs index 2144b83480..0a8db2edd0 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/AspNetCoreToSwaggerGenerationTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/AspNetCoreToSwaggerGenerationTests.cs @@ -907,11 +907,11 @@ private class ProblemDetails { } private class ApiResponseType2_1 : ApiResponseType { -#pragma warning disable 108,114 +#pragma warning disable 108, 114 public bool IsDefaultResponse { get; set; } -#pragma warning restore 108,114 +#pragma warning restore 108, 114 } #endregion } } -#endif +#endif \ No newline at end of file diff --git a/src/NSwag.Generation.AspNetCore.Tests/ExtensionDataTests.cs b/src/NSwag.Generation.AspNetCore.Tests/ExtensionDataTests.cs index 4e36332d21..8daaaa9c85 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/ExtensionDataTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/ExtensionDataTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers; using Xunit; diff --git a/src/NSwag.Generation.AspNetCore.Tests/Inheritance/InheritanceControllerTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Inheritance/InheritanceControllerTests.cs index 2658367569..4ed1faf482 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Inheritance/InheritanceControllerTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Inheritance/InheritanceControllerTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Inheritance; using Xunit; @@ -18,6 +16,7 @@ public async Task When_primitive_body_parameter_has_no_default_value_then_it_is_ // Act var document = await GenerateDocumentAsync(settings, typeof(ActualController)); var json = document.ToJson(); + Assert.NotNull(json); // Assert Assert.True(document.Operations.Any()); diff --git a/src/NSwag.Generation.AspNetCore.Tests/LanguageParameterTests.cs b/src/NSwag.Generation.AspNetCore.Tests/LanguageParameterTests.cs index d543071b9a..b11725993b 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/LanguageParameterTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/LanguageParameterTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers; using Xunit; diff --git a/src/NSwag.Generation.AspNetCore.Tests/NSwag.Generation.AspNetCore.Tests.csproj b/src/NSwag.Generation.AspNetCore.Tests/NSwag.Generation.AspNetCore.Tests.csproj index 8cf183c810..5a456219e2 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/NSwag.Generation.AspNetCore.Tests.csproj +++ b/src/NSwag.Generation.AspNetCore.Tests/NSwag.Generation.AspNetCore.Tests.csproj @@ -1,19 +1,19 @@  - net6.0;net8.0 - $(NoWarn),618,1591 + net8.0;net9.0 + $(NoWarn),618,1591;CA1707;CA1816 true + - - - - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -21,6 +21,11 @@ + + + + + diff --git a/src/NSwag.Generation.AspNetCore.Tests/Operations/PathTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Operations/PathTests.cs index 706115926e..7ebbe411db 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Operations/PathTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Operations/PathTests.cs @@ -1,8 +1,6 @@ using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters; -using System.Linq; -using System.Threading.Tasks; using Xunit; namespace NSwag.Generation.AspNetCore.Tests.Operations diff --git a/src/NSwag.Generation.AspNetCore.Tests/Parameters/BodyParametersTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Parameters/BodyParametersTests.cs index f42eb70114..e7f59ca47c 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Parameters/BodyParametersTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Parameters/BodyParametersTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters; using Xunit; @@ -21,7 +19,7 @@ public async Task When_primitive_body_parameter_has_no_default_value_then_it_is_ // Assert var operation = document.Operations.First(o => o.Operation.OperationId == "BodyParameters_RequiredPrimitive").Operation; - Assert.True(operation.ActualParameters.First().IsRequired); + Assert.True(operation.ActualParameters[0].IsRequired); } [Fact( @@ -46,7 +44,7 @@ public async Task When_primitive_body_parameter_has_default_value_then_it_is_opt // Assert var operation = document.Operations.First(o => o.Operation.OperationId == "BodyParameters_RequiredPrimitiveWithDefault").Operation; - Assert.False(operation.ActualParameters.First().IsRequired); + Assert.False(operation.ActualParameters[0].IsRequired); } [Fact( @@ -65,7 +63,7 @@ public async Task When_primitive_body_parameter_has_default_value_then_it_is_req // Assert var operation = document.Operations.First(o => o.Operation.OperationId == "BodyParameters_RequiredPrimitiveWithDefault").Operation; - Assert.True(operation.ActualParameters.First().IsRequired); + Assert.True(operation.ActualParameters[0].IsRequired); } [Fact] @@ -80,7 +78,7 @@ public async Task When_complex_body_parameter_has_no_default_value_then_it_is_re // Assert var operation = document.Operations.First(o => o.Operation.OperationId == "BodyParameters_RequiredComplex").Operation; - Assert.True(operation.ActualParameters.First().IsRequired); + Assert.True(operation.ActualParameters[0].IsRequired); } [Fact( @@ -99,7 +97,7 @@ public async Task When_complex_body_parameter_has_default_value_then_it_is_optio // Assert var operation = document.Operations.First(o => o.Operation.OperationId == "BodyParameters_RequiredComplexWithDefault").Operation; - Assert.False(operation.ActualParameters.First().IsRequired); + Assert.False(operation.ActualParameters[0].IsRequired); } [Fact( @@ -118,7 +116,7 @@ public async Task When_complex_body_parameter_has_default_value_then_it_is_requi // Assert var operation = document.Operations.First(o => o.Operation.OperationId == "BodyParameters_RequiredComplexWithDefault").Operation; - Assert.True(operation.ActualParameters.First().IsRequired); + Assert.True(operation.ActualParameters[0].IsRequired); } } } diff --git a/src/NSwag.Generation.AspNetCore.Tests/Parameters/DefaultParametersTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Parameters/DefaultParametersTests.cs index f2a78abe30..5f5620d396 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Parameters/DefaultParametersTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Parameters/DefaultParametersTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using Newtonsoft.Json; +using Newtonsoft.Json; using Newtonsoft.Json.Converters; using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; @@ -56,7 +54,7 @@ public async Task When_parameter_has_default_and_schema_type_is_OpenApi3_then_sc var operation = document.Operations.First(o => o.Path.Contains(nameof(DefaultParametersController.WithDefaultEnum))).Operation; Assert.Equal((int)MyEnum.Def, operation.Parameters.First().Schema.Default); - Assert.True(operation.Parameters.First().Schema.OneOf.Any()); + Assert.True(operation.Parameters[0].Schema.OneOf.Count > 0); } [Fact] diff --git a/src/NSwag.Generation.AspNetCore.Tests/Parameters/FormDataTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Parameters/FormDataTests.cs index 2a6ed9bf17..0222f6468e 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Parameters/FormDataTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Parameters/FormDataTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters; using Xunit; diff --git a/src/NSwag.Generation.AspNetCore.Tests/Parameters/HeaderParametersTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Parameters/HeaderParametersTests.cs index 2299b3d671..20f3059aba 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Parameters/HeaderParametersTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Parameters/HeaderParametersTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters; using Xunit; @@ -29,8 +27,8 @@ public async Task When_complex_query_parameters_are_nullable_and_set_to_null_the var operation = document.Operations.First().Operation; Assert.Equal(2, operation.ActualParameters.Count); - Assert.True(operation.ActualParameters.First().IsRequired); - Assert.False(operation.ActualParameters.Last().IsRequired); + Assert.True(operation.ActualParameters[0].IsRequired); + Assert.False(operation.ActualParameters[operation.ActualParameters.Count - 1].IsRequired); } } } \ No newline at end of file diff --git a/src/NSwag.Generation.AspNetCore.Tests/Parameters/NullablePathParameterTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Parameters/NullablePathParameterTests.cs index 5051439681..f843d7f8dc 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Parameters/NullablePathParameterTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Parameters/NullablePathParameterTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters; using Xunit; diff --git a/src/NSwag.Generation.AspNetCore.Tests/Parameters/PathParameterWithModelBinderTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Parameters/PathParameterWithModelBinderTests.cs index 0549f02b92..9ca2eca737 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Parameters/PathParameterWithModelBinderTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Parameters/PathParameterWithModelBinderTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters; using Xunit; diff --git a/src/NSwag.Generation.AspNetCore.Tests/Parameters/QueryParametersTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Parameters/QueryParametersTests.cs index ec61d0cbd4..2b7fa566f9 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Parameters/QueryParametersTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Parameters/QueryParametersTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Linq; using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters; @@ -23,19 +21,20 @@ public async Task When_complex_query_parameters_are_nullable_and_set_to_null_the // Act var document = await GenerateDocumentAsync(settings, typeof(ComplexQueryParametersController)); var json = document.ToJson(); + Assert.NotNull(json); // Assert var operation = document.Operations.First().Operation; - Assert.True(operation.ActualParameters.First().IsRequired); - Assert.True(operation.ActualParameters.Last().IsRequired); + Assert.True(operation.ActualParameters[0].IsRequired); + Assert.True(operation.ActualParameters[operation.ActualParameters.Count - 1].IsRequired); Assert.Equal(2, operation.ActualParameters.Count); - Assert.Equal("Bar.", operation.ActualParameters.First().Description); - Assert.Equal(JToken.Parse("42"), operation.ActualParameters.First().Example); + Assert.Equal("Bar.", operation.ActualParameters[0].Description); + Assert.Equal(JToken.Parse("42"), operation.ActualParameters[0].Example); - Assert.Equal("Baz.", operation.ActualParameters.Last().Description); + Assert.Equal("Baz.", operation.ActualParameters[operation.ActualParameters.Count - 1].Description); } [Fact] @@ -98,7 +97,7 @@ public async Task When_parameter_is_overwritten_then_original_name_is_set() var document = await GenerateDocumentAsync(settings, typeof(RenamedQueryParameterController)); // Assert - var parameter = document.Operations.First().Operation.ActualParameters.First(); + var parameter = document.Operations.First().Operation.ActualParameters[0]; Assert.Equal("month", parameter.Name); Assert.Equal("months", parameter.OriginalName); diff --git a/src/NSwag.Generation.AspNetCore.Tests/Processors/OperationResponseProcessorTest.cs b/src/NSwag.Generation.AspNetCore.Tests/Processors/OperationResponseProcessorTest.cs index 994f0ef7f8..b9bb6add41 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Processors/OperationResponseProcessorTest.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Processors/OperationResponseProcessorTest.cs @@ -9,7 +9,6 @@ using Microsoft.AspNetCore.Mvc.ApiExplorer; using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; -using System.Collections.Generic; using System.Reflection; using Xunit; @@ -141,15 +140,17 @@ private AspNetCoreOperationProcessorContext GetContext(ApiDescription apiDescrip generator, schemaResolver, settings, - new List()) + []) { ApiDescription = apiDescription, }; return context; } - private class TestModel { } + private sealed class TestModel { } +#pragma warning disable CA1822 private TestModel SomeAction() => null; +#pragma warning restore CA1822 } } diff --git a/src/NSwag.Generation.AspNetCore.Tests/Requests/ConsumesTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Requests/ConsumesTests.cs index 50f1ac3cc5..a410a6e504 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Requests/ConsumesTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Requests/ConsumesTests.cs @@ -1,8 +1,6 @@ using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Requests; -using System.Linq; -using System.Threading.Tasks; using Xunit; namespace NSwag.Generation.AspNetCore.Tests.Requests diff --git a/src/NSwag.Generation.AspNetCore.Tests/Requests/PostBodyTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Requests/PostBodyTests.cs index 08e308e949..87069962f6 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Requests/PostBodyTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Requests/PostBodyTests.cs @@ -1,8 +1,6 @@ using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Requests; -using System.Linq; -using System.Threading.Tasks; using Xunit; namespace NSwag.Generation.AspNetCore.Tests.Requests @@ -29,7 +27,7 @@ public async Task When_OpenApiBodyParameter_is_applied_with_JSON_then_request_bo var operation = document.Operations.First(o => o.Operation.OperationId == "PostBody_JsonPostBodyOperation").Operation; var parameter = operation.Parameters.Single(p => p.Kind == OpenApiParameterKind.Body); - Assert.Equal(1, operation.Parameters.Count); + Assert.Single(operation.Parameters); Assert.True(operation.RequestBody.Content["application/json"].Schema.IsAnyType); } @@ -53,7 +51,7 @@ public async Task When_OpenApiBodyParameter_is_applied_with_text_then_request_bo var operation = document.Operations.First(o => o.Operation.OperationId == "PostBody_FilePostBodyOperation").Operation; var parameter = operation.Parameters.Single(p => p.Kind == OpenApiParameterKind.Body); - Assert.Equal(1, operation.Parameters.Count); + Assert.Single(operation.Parameters); Assert.Equal(JsonObjectType.String, operation.RequestBody.Content["text/plain"].Schema.Type); Assert.Equal("binary", operation.RequestBody.Content["text/plain"].Schema.Format); } diff --git a/src/NSwag.Generation.AspNetCore.Tests/Responses/NullableResponseTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Responses/NullableResponseTests.cs index 6aa6273bc0..de152a7fc7 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Responses/NullableResponseTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Responses/NullableResponseTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers; diff --git a/src/NSwag.Generation.AspNetCore.Tests/Responses/ProducesTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Responses/ProducesTests.cs index 45a72ab53f..ed0e05de43 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Responses/ProducesTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Responses/ProducesTests.cs @@ -1,7 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; -using NJsonSchema.Generation; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Responses; using Xunit; @@ -27,7 +24,7 @@ public async Task When_produces_is_defined_on_all_operations_then_it_is_added_to Assert.Contains("text/html", operation.ActualProduces); Assert.Null(operation.Produces); } - + [Fact] public async Task When_operation_produces_is_different_in_several_controllers_then_they_are_added_to_the_operation() { diff --git a/src/NSwag.Generation.AspNetCore.Tests/Responses/ResponseAttributesTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Responses/ResponseAttributesTests.cs index 315e6f374a..8ee91c7d98 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Responses/ResponseAttributesTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Responses/ResponseAttributesTests.cs @@ -1,6 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers; using Xunit; @@ -24,6 +22,7 @@ public async Task When_operation_has_SwaggerResponseAttribute_with_description_i // Act var document = await GenerateDocumentAsync(settings, typeof(ResponsesController)); var json = document.ToJson(); + Assert.NotNull(json); // Assert var operation = document.Operations.First().Operation; diff --git a/src/NSwag.Generation.AspNetCore.Tests/Responses/WrappedResponseTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Responses/WrappedResponseTests.cs index 57c61ec5bc..22c4a640fe 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Responses/WrappedResponseTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Responses/WrappedResponseTests.cs @@ -1,14 +1,7 @@ -using System; -using System.Linq; -using System.Threading.Tasks; - -using Xunit; - +using Xunit; using NJsonSchema; - using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Responses; using NJsonSchema.NewtonsoftJson.Generation; -using NJsonSchema.Generation; namespace NSwag.Generation.AspNetCore.Tests.Responses { @@ -30,23 +23,27 @@ public async Task When_response_is_wrapped_in_certain_generic_result_types_then_ var document = await GenerateDocumentAsync(settings, typeof(WrappedResponseController)); // Assert - OpenApiResponse GetOperationResponse(string actionName) => document.Operations - .Where(op => op.Operation.OperationId == $"{nameof(WrappedResponseController) - .Substring(0, nameof(WrappedResponseController).Length - "Controller".Length)}_{actionName}") - .Single().Operation.ActualResponses.Single().Value; + OpenApiResponse GetOperationResponse(string actionName) + { + return document.Operations + .Single(op => op.Operation.OperationId == $"{nameof(WrappedResponseController) + .Substring(0, nameof(WrappedResponseController).Length - "Controller".Length)}_{actionName}").Operation.ActualResponses.Single().Value; + } - JsonObjectType GetOperationResponseSchemaType(string actionName) => - GetOperationResponse(actionName).Schema.Type; + JsonObjectType GetOperationResponseSchemaType(string actionName) + { + return GetOperationResponse(actionName).Schema.Type; + } var intType = NewtonsoftJsonSchemaGenerator.FromType().Type; Assert.Null(GetOperationResponse(nameof(WrappedResponseController.Task)).Schema); - Assert.Equal(intType, GetOperationResponseSchemaType(nameof( WrappedResponseController.Int))); - Assert.Equal(intType, GetOperationResponseSchemaType(nameof( WrappedResponseController.TaskOfInt))); - Assert.Equal(intType, GetOperationResponseSchemaType(nameof( WrappedResponseController.ValueTaskOfInt))); - Assert.Equal(intType, GetOperationResponseSchemaType(nameof( WrappedResponseController.ActionResultOfInt))); - Assert.Equal(intType, GetOperationResponseSchemaType(nameof( WrappedResponseController.TaskOfActionResultOfInt))); - Assert.Equal(intType, GetOperationResponseSchemaType(nameof( WrappedResponseController.ValueTaskOfActionResultOfInt))); + Assert.Equal(intType, GetOperationResponseSchemaType(nameof(WrappedResponseController.Int))); + Assert.Equal(intType, GetOperationResponseSchemaType(nameof(WrappedResponseController.TaskOfInt))); + Assert.Equal(intType, GetOperationResponseSchemaType(nameof(WrappedResponseController.ValueTaskOfInt))); + Assert.Equal(intType, GetOperationResponseSchemaType(nameof(WrappedResponseController.ActionResultOfInt))); + Assert.Equal(intType, GetOperationResponseSchemaType(nameof(WrappedResponseController.TaskOfActionResultOfInt))); + Assert.Equal(intType, GetOperationResponseSchemaType(nameof(WrappedResponseController.ValueTaskOfActionResultOfInt))); } } } \ No newline at end of file diff --git a/src/NSwag.Generation.AspNetCore.Tests/Responses/XmlDocsTests.cs b/src/NSwag.Generation.AspNetCore.Tests/Responses/XmlDocsTests.cs index c756ea112c..05598e1090 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/Responses/XmlDocsTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/Responses/XmlDocsTests.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using NJsonSchema; +using NJsonSchema; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Generation.AspNetCore.Tests.Web.Controllers; using Xunit; diff --git a/src/NSwag.Generation.AspNetCore.Tests/SystemTextJsonTests.cs b/src/NSwag.Generation.AspNetCore.Tests/SystemTextJsonTests.cs index 3805b6a4e0..8f5e8dbbda 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/SystemTextJsonTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/SystemTextJsonTests.cs @@ -1,8 +1,5 @@ #if NETCOREAPP3_1_OR_GREATER -using Microsoft.Extensions.DependencyInjection; using System.Text.Json.Serialization; -using System.Threading.Tasks; -using Newtonsoft.Json.Converters; using NSwag.AspNetCore; using Xunit; using NJsonSchema.Generation; @@ -28,7 +25,7 @@ public async Task WhenSystemTextOptionsIsUsed_ThenOptionsAreConverted() var registration = serviceProvider.GetRequiredService(); var generator = new AspNetCoreOpenApiDocumentGenerator(registration.Settings); await generator.GenerateAsync(serviceProvider); - + var settings = generator.Settings; // Assert diff --git a/src/NSwag.Generation.AspNetCore/AspNetCoreOpenApiDocumentGenerator.cs b/src/NSwag.Generation.AspNetCore/AspNetCoreOpenApiDocumentGenerator.cs index b9fa02ff52..cb017ae61e 100644 --- a/src/NSwag.Generation.AspNetCore/AspNetCoreOpenApiDocumentGenerator.cs +++ b/src/NSwag.Generation.AspNetCore/AspNetCoreOpenApiDocumentGenerator.cs @@ -6,15 +6,13 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; +#pragma warning disable IDE0005 + using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; +using System.Globalization; using System.Reflection; using System.Text; using System.Text.Json; -using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ApiExplorer; @@ -25,9 +23,7 @@ using Microsoft.Extensions.Options; using Namotion.Reflection; using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; using NJsonSchema; -using NJsonSchema.Generation; using NSwag.Generation.Processors; using NSwag.Generation.Processors.Contexts; @@ -61,7 +57,7 @@ public Task GenerateAsync(object serviceProvider) /// The settings. public static JsonSerializerSettings GetJsonSerializerSettings(IServiceProvider serviceProvider) { - dynamic GetJsonOptionsWithReflection(IServiceProvider sp) + static dynamic GetJsonOptionsWithReflection(IServiceProvider sp) { try { @@ -220,18 +216,14 @@ private List GenerateApiGroups( } var path = apiDescription.RelativePath; - if (!path.StartsWith("/", StringComparison.Ordinal)) + if (!path.StartsWith('/')) { path = "/" + path; } - var httpMethod = apiDescription.HttpMethod?.ToLowerInvariant(); - if (httpMethod == null) - { - httpMethod = apiDescription.ParameterDescriptions.Any(p => p.Source == BindingSource.Body) - ? OpenApiOperationMethod.Post - : OpenApiOperationMethod.Get; - } + var httpMethod = apiDescription.HttpMethod?.ToLowerInvariant() ?? (apiDescription.ParameterDescriptions.Any(p => p.Source == BindingSource.Body) + ? OpenApiOperationMethod.Post + : OpenApiOperationMethod.Get); var operation = new OpenApiOperation(); #if NETCOREAPP3_1_OR_GREATER @@ -251,7 +243,7 @@ private List GenerateApiGroups( operation = JsonConvert.DeserializeObject(stringBuilder.ToString()); operation.Parameters.Clear(); // clear because parameters are added by the generator - } + } #endif operation.IsDeprecated = IsOperationDeprecated(item.Item1, apiDescription.ActionDescriptor, method); @@ -277,7 +269,7 @@ private List GenerateApiGroups( } var addedOperations = AddOperationDescriptionsToDocument(document, controllerType, operations, generator, schemaResolver); - if (addedOperations.Any() && apiGroup.Key != null) + if (addedOperations.Count > 0 && apiGroup.Key != null) { usedControllerTypes.Add(apiGroup.Key); } @@ -290,7 +282,7 @@ private List GenerateApiGroups( return usedControllerTypes; } - private bool IsOperationDeprecated(ApiDescription apiDescription, ActionDescriptor actionDescriptor, MethodInfo methodInfo) + private static bool IsOperationDeprecated(ApiDescription apiDescription, ActionDescriptor actionDescriptor, MethodInfo methodInfo) { if (methodInfo?.GetCustomAttribute() != null) { @@ -339,7 +331,7 @@ private List> Add var path = operation.Path.Replace("//", "/"); if (!document.Paths.TryGetValue(path, out var pathItem)) { - document.Paths[path] = pathItem = new OpenApiPathItem(); + document.Paths[path] = pathItem = []; } if (pathItem.ContainsKey(operation.Method)) @@ -411,10 +403,7 @@ await OpenApiDocument.FromJsonAsync(Settings.DocumentTemplate).ConfigureAwait(fa document.Generator = $"NSwag{version}"; document.SchemaType = Settings.SchemaSettings.SchemaType; - if (document.Info == null) - { - document.Info = new OpenApiInfo(); - } + document.Info ??= new OpenApiInfo(); if (string.IsNullOrEmpty(Settings.DocumentTemplate)) { @@ -447,7 +436,7 @@ private bool RunOperationProcessors(OpenApiDocument document, ApiDescription api foreach (var operationProcessor in Settings.OperationProcessors) { - if (operationProcessor.Process(operationProcessorContext) == false) + if (!operationProcessor.Process(operationProcessorContext)) { return false; } @@ -468,7 +457,7 @@ private bool RunOperationProcessors(OpenApiDocument document, ApiDescription api (IOperationProcessor)Activator.CreateInstance(attribute.Type, attribute.Parameters) : (IOperationProcessor)Activator.CreateInstance(attribute.Type); - if (operationProcessor.Process(operationProcessorContext) == false) + if (!operationProcessor.Process(operationProcessorContext)) { return false; } @@ -490,7 +479,7 @@ private string GetOperationId(OpenApiDocument document, ApiDescription apiDescri if (!string.IsNullOrWhiteSpace(httpMethod)) { var attributeName = Char.ToUpperInvariant(httpMethod[0]) + httpMethod.Substring(1).ToLowerInvariant(); - var typeName = string.Format("Microsoft.AspNetCore.Mvc.Http{0}Attribute", attributeName); + var typeName = string.Format(CultureInfo.InvariantCulture, "Microsoft.AspNetCore.Mvc.Http{0}Attribute", attributeName); httpAttribute = method? .GetCustomAttributes() .FirstAssignableToTypeNameOrDefault(typeName); @@ -543,8 +532,8 @@ private string GetOperationId(OpenApiDocument document, ApiDescription apiDescri httpMethod[0].ToString().ToUpperInvariant() + httpMethod.Substring(1) + string.Join("", apiDescription.RelativePath .Split('/', '\\', '}', ']', '-', '_') - .Where(t => !t.StartsWith("{")) - .Where(t => !t.StartsWith("[")) + .Where(t => !t.StartsWith('{')) + .Where(t => !t.StartsWith('[')) .Select(t => t.Length > 1 ? t[0].ToString().ToUpperInvariant() + t.Substring(1) : t.ToUpperInvariant())); } @@ -554,12 +543,12 @@ private string GetOperationId(OpenApiDocument document, ApiDescription apiDescri number++; } - return operationId + (number > 1 ? number.ToString() : string.Empty); + return operationId + (number > 1 ? number.ToString(CultureInfo.InvariantCulture) : string.Empty); } private static string GetActionName(string actionName) { - if (actionName.EndsWith("Async")) + if (actionName.EndsWith("Async", StringComparison.Ordinal)) { actionName = actionName.Substring(0, actionName.Length - 5); } diff --git a/src/NSwag.Generation.AspNetCore/AspNetCoreOpenApiDocumentGeneratorSettings.cs b/src/NSwag.Generation.AspNetCore/AspNetCoreOpenApiDocumentGeneratorSettings.cs index 2822af25af..664480b2c7 100644 --- a/src/NSwag.Generation.AspNetCore/AspNetCoreOpenApiDocumentGeneratorSettings.cs +++ b/src/NSwag.Generation.AspNetCore/AspNetCoreOpenApiDocumentGeneratorSettings.cs @@ -8,7 +8,6 @@ using NSwag.Generation.Processors; using NSwag.Generation.AspNetCore.Processors; -using System; namespace NSwag.Generation.AspNetCore { diff --git a/src/NSwag.Generation.AspNetCore/AspNetCoreOperationProcessorContext.cs b/src/NSwag.Generation.AspNetCore/AspNetCoreOperationProcessorContext.cs index 0049fd6540..ac4855e4dd 100644 --- a/src/NSwag.Generation.AspNetCore/AspNetCoreOperationProcessorContext.cs +++ b/src/NSwag.Generation.AspNetCore/AspNetCoreOperationProcessorContext.cs @@ -6,11 +6,8 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; using System.Reflection; using Microsoft.AspNetCore.Mvc.ApiExplorer; -using NJsonSchema; using NJsonSchema.Generation; using NSwag.Generation.Processors; using NSwag.Generation.Processors.Contexts; diff --git a/src/NSwag.Generation.AspNetCore/NSwag.Generation.AspNetCore.csproj b/src/NSwag.Generation.AspNetCore/NSwag.Generation.AspNetCore.csproj index bceac8d52c..47b2dad663 100644 --- a/src/NSwag.Generation.AspNetCore/NSwag.Generation.AspNetCore.csproj +++ b/src/NSwag.Generation.AspNetCore/NSwag.Generation.AspNetCore.csproj @@ -1,6 +1,6 @@ - net462;netstandard2.0;net6.0;net8.0 + net462;netstandard2.0;net8.0;net9.0 Swagger Documentation AspNetCore $(DefineConstants);ASPNETCORE true @@ -12,19 +12,24 @@ - - - - - - + + + + + + + + + + + diff --git a/src/NSwag.Generation.AspNetCore/Processors/AspNetCoreOperationSecurityScopeProcessor.cs b/src/NSwag.Generation.AspNetCore/Processors/AspNetCoreOperationSecurityScopeProcessor.cs index b433f9d42f..a52bfe1e0b 100644 --- a/src/NSwag.Generation.AspNetCore/Processors/AspNetCoreOperationSecurityScopeProcessor.cs +++ b/src/NSwag.Generation.AspNetCore/Processors/AspNetCoreOperationSecurityScopeProcessor.cs @@ -6,13 +6,9 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using NSwag.Generation.Processors.Contexts; using Microsoft.AspNetCore.Authorization; using NSwag.Generation.AspNetCore; -using NJsonSchema.Infrastructure; using Namotion.Reflection; namespace NSwag.Generation.Processors.Security @@ -51,14 +47,14 @@ public bool Process(OperationProcessorContext context) } var authorizeAttributes = endpointMetadata.OfType().ToList(); - if (!authorizeAttributes.Any()) + if (authorizeAttributes.Count == 0) { return true; } if (context.OperationDescription.Operation.Security == null) { - context.OperationDescription.Operation.Security = new List(); + context.OperationDescription.Operation.Security = []; } var scopes = GetScopes(authorizeAttributes); diff --git a/src/NSwag.Generation.AspNetCore/Processors/AspNetCoreOperationTagsProcessor.cs b/src/NSwag.Generation.AspNetCore/Processors/AspNetCoreOperationTagsProcessor.cs index 82bef45442..6cae7bb802 100644 --- a/src/NSwag.Generation.AspNetCore/Processors/AspNetCoreOperationTagsProcessor.cs +++ b/src/NSwag.Generation.AspNetCore/Processors/AspNetCoreOperationTagsProcessor.cs @@ -6,12 +6,13 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- +#pragma warning disable IDE0005 + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Controllers; using Namotion.Reflection; using NSwag.Generation.Processors; using NSwag.Generation.Processors.Contexts; -using System.Linq; using NJsonSchema.Generation; namespace NSwag.Generation.AspNetCore.Processors diff --git a/src/NSwag.Generation.AspNetCore/Processors/OperationParameterProcessor.cs b/src/NSwag.Generation.AspNetCore/Processors/OperationParameterProcessor.cs index 53dbd391f9..cdec82e469 100644 --- a/src/NSwag.Generation.AspNetCore/Processors/OperationParameterProcessor.cs +++ b/src/NSwag.Generation.AspNetCore/Processors/OperationParameterProcessor.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Microsoft.AspNetCore.Mvc.Abstractions; @@ -24,7 +21,7 @@ namespace NSwag.Generation.AspNetCore.Processors { - internal class OperationParameterProcessor : IOperationProcessor + internal sealed class OperationParameterProcessor : IOperationProcessor { private const string MultipartFormData = "multipart/form-data"; @@ -47,7 +44,7 @@ public bool Process(OperationProcessorContext operationProcessorContext) var httpPath = context.OperationDescription.Path; var parameters = context.ApiDescription.ParameterDescriptions; - var methodParameters = context.MethodInfo?.GetParameters() ?? Array.Empty(); + var methodParameters = context.MethodInfo?.GetParameters() ?? []; var position = operationProcessorContext.Parameters.Count(x => x.Value.Kind is not OpenApiParameterKind.Body) + 1; foreach (var apiParameter in parameters.Where(p => @@ -70,7 +67,7 @@ public bool Process(OperationProcessorContext operationProcessorContext) var extendedApiParameter = new ExtendedApiParameterDescription(_settings.SchemaSettings) { ApiParameter = apiParameter, - Attributes = Enumerable.Empty(), + Attributes = [], ParameterType = apiParameter.Type }; @@ -90,7 +87,7 @@ public bool Process(OperationProcessorContext operationProcessorContext) { var parameterDescriptor = apiParameter.TryGetPropertyValue("ParameterDescriptor"); var parameterName = parameterDescriptor?.Name ?? apiParameter.Name; - parameter = methodParameters.FirstOrDefault(m => m.Name.ToLowerInvariant() == parameterName.ToLowerInvariant()); + parameter = methodParameters.FirstOrDefault(m => m.Name.Equals(parameterName, StringComparison.OrdinalIgnoreCase)); if (parameter != null) { extendedApiParameter.ParameterInfo = parameter; @@ -115,13 +112,13 @@ public bool Process(OperationProcessorContext operationProcessorContext) if (apiParameter.Source == BindingSource.Path) { // ignore unused implicit path parameters - if (!httpPath.ToLowerInvariant().Contains("{" + apiParameter.Name.ToLowerInvariant() + ":") && - !httpPath.ToLowerInvariant().Contains("{" + apiParameter.Name.ToLowerInvariant() + "}")) + if (!httpPath.Contains("{" + apiParameter.Name + ":", StringComparison.OrdinalIgnoreCase) && + !httpPath.Contains("{" + apiParameter.Name + "}", StringComparison.OrdinalIgnoreCase)) { continue; } - extendedApiParameter.Attributes = extendedApiParameter.Attributes.Concat(new[] { new NotNullAttribute() }); + extendedApiParameter.Attributes = extendedApiParameter.Attributes.Concat([new NotNullAttribute()]); } } @@ -178,7 +175,7 @@ public bool Process(OperationProcessorContext operationProcessorContext) } else { - if (TryAddFileParameter(context, extendedApiParameter) == false) + if (!TryAddFileParameter(context, extendedApiParameter)) { operationParameter = CreatePrimitiveParameter(context, extendedApiParameter); operationParameter.Kind = OpenApiParameterKind.Query; @@ -247,7 +244,7 @@ private void ApplyOpenApiBodyParameterAttribute(OpenApiOperationDescription oper } } - private void EnsureSingleBodyParameter(OpenApiOperationDescription operationDescription) + private static void EnsureSingleBodyParameter(OpenApiOperationDescription operationDescription) { if (operationDescription.Operation.ActualParameters.Count(p => p.Kind == OpenApiParameterKind.Body) > 1) { @@ -255,7 +252,7 @@ private void EnsureSingleBodyParameter(OpenApiOperationDescription operationDesc } } - private void UpdateConsumedTypes(OpenApiOperationDescription operationDescription) + private static void UpdateConsumedTypes(OpenApiOperationDescription operationDescription) { if (operationDescription.Operation.ActualParameters.Any(p => p.IsBinary || p.ActualSchema.IsBinary)) { @@ -263,7 +260,7 @@ private void UpdateConsumedTypes(OpenApiOperationDescription operationDescriptio } } - private void RemoveUnusedPathParameters(OpenApiOperationDescription operationDescription, string httpPath) + private static void RemoveUnusedPathParameters(OpenApiOperationDescription operationDescription, string httpPath) { operationDescription.Path = "/" + Regex.Replace(httpPath, "{(.*?)(:(([^/]*)?))?}", match => { @@ -324,7 +321,7 @@ private void AddFileParameter(OperationProcessorContext context, ExtendedApiPara } } - private JsonSchema CreateOrGetFormDataSchema(OperationProcessorContext context) + private static JsonSchema CreateOrGetFormDataSchema(OperationProcessorContext context) { if (context.OperationDescription.Operation.RequestBody == null) { @@ -332,20 +329,16 @@ private JsonSchema CreateOrGetFormDataSchema(OperationProcessorContext context) } var requestBody = context.OperationDescription.Operation.RequestBody; - if (!requestBody.Content.ContainsKey(MultipartFormData)) + if (!requestBody.Content.TryGetValue(MultipartFormData, out OpenApiMediaType value)) { - requestBody.Content[MultipartFormData] = new OpenApiMediaType + value = new OpenApiMediaType { Schema = new JsonSchema() }; + requestBody.Content[MultipartFormData] = value; } - if (requestBody.Content[MultipartFormData].Schema == null) - { - requestBody.Content[MultipartFormData].Schema = new JsonSchema(); - } - - return requestBody.Content[MultipartFormData].Schema; + return value.Schema ??= new JsonSchema(); } private JsonSchemaProperty CreateFormDataProperty(OperationProcessorContext context, ExtendedApiParameterDescription extendedApiParameter, JsonSchema schema) @@ -370,7 +363,7 @@ private bool IsFileArray(Type type, JsonTypeDescription typeInfo) return true; } - if (typeInfo.Type == JsonObjectType.Array && type.GenericTypeArguments.Any()) + if (typeInfo.Type == JsonObjectType.Array && type.GenericTypeArguments.Length > 0) { var description = _settings.SchemaSettings.ReflectionService.GetDescription(type.GenericTypeArguments[0].ToContextualType(), _settings.SchemaSettings); if (description.Type == JsonObjectType.File || description.Format == JsonFormatStrings.Binary) @@ -509,7 +502,7 @@ private OpenApiParameter CreatePrimitiveParameter( return operationParameter; } - private class ExtendedApiParameterDescription + private sealed class ExtendedApiParameterDescription { private readonly IXmlDocsSettings _xmlDocsSettings; @@ -521,7 +514,7 @@ private class ExtendedApiParameterDescription public Type ParameterType { get; set; } - public IEnumerable Attributes { get; set; } = Enumerable.Empty(); + public IEnumerable Attributes { get; set; } = []; public ExtendedApiParameterDescription(IXmlDocsSettings xmlDocsSettings) { @@ -544,14 +537,11 @@ public bool IsRequired(bool requireParametersWithoutDefault) { isRequired = true; } - else if (ApiParameter.ModelMetadata != null && - ApiParameter.ModelMetadata.IsBindingRequired) + else if (ApiParameter.ModelMetadata != null && ApiParameter.ModelMetadata.IsBindingRequired) { isRequired = true; } - else if (ApiParameter.Source == BindingSource.Path && - ApiParameter.RouteInfo != null && - ApiParameter.RouteInfo.IsOptional == false) + else if (ApiParameter.Source == BindingSource.Path && ApiParameter.RouteInfo != null && !ApiParameter.RouteInfo.IsOptional) { isRequired = true; } diff --git a/src/NSwag.Generation.AspNetCore/Processors/OperationResponseProcessor.cs b/src/NSwag.Generation.AspNetCore/Processors/OperationResponseProcessor.cs index 1252c54564..d2e7573884 100644 --- a/src/NSwag.Generation.AspNetCore/Processors/OperationResponseProcessor.cs +++ b/src/NSwag.Generation.AspNetCore/Processors/OperationResponseProcessor.cs @@ -6,9 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; using System.Globalization; -using System.Linq; using System.Reflection; using Namotion.Reflection; using NJsonSchema; @@ -35,7 +33,7 @@ public OperationResponseProcessor(AspNetCoreOpenApiDocumentGeneratorSettings set /// true if the operation should be added to the Swagger specification. public bool Process(OperationProcessorContext operationProcessorContext) { - if (!(operationProcessorContext is AspNetCoreOperationProcessorContext context)) + if (operationProcessorContext is not AspNetCoreOperationProcessorContext context) { return false; } @@ -48,7 +46,7 @@ public bool Process(OperationProcessorContext operationProcessorContext) .Concat(context.MethodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes() .Where(a => a.GetType().IsAssignableToTypeName("SwaggerResponseAttribute", TypeNameStyle.Name) || a.GetType().IsAssignableToTypeName("SwaggerDefaultResponseAttribute", TypeNameStyle.Name))) - .ToArray() ?? new Attribute[0]; + .ToArray() ?? []; if (responseTypeAttributes.Length > 0) { @@ -76,14 +74,14 @@ public bool Process(OperationProcessorContext operationProcessorContext) httpStatusCode = apiResponse.StatusCode.ToString(CultureInfo.InvariantCulture); } - if (IsVoidResponse(returnType) == false) + if (!IsVoidResponse(returnType)) { var returnTypeAttributes = context.MethodInfo?.ReturnParameter?.GetCustomAttributes(false).OfType(); var contextualReturnType = returnType.ToContextualType(returnTypeAttributes); var nullableXmlAttribute = GetResponseXmlDocsElement(context.MethodInfo, httpStatusCode)?.Attribute("nullable"); var isResponseNullable = nullableXmlAttribute != null ? - nullableXmlAttribute.Value.ToLowerInvariant() == "true" : + nullableXmlAttribute.Value.Equals("true", StringComparison.OrdinalIgnoreCase) : _settings.SchemaSettings.ReflectionService.GetDescription(contextualReturnType, _settings.DefaultResponseReferenceTypeNullHandling, _settings.SchemaSettings).IsNullable; response.IsNullableRaw = isResponseNullable; @@ -119,7 +117,7 @@ protected override string GetVoidResponseStatusCode() return "200"; } - private bool IsVoidResponse(Type returnType) + private static bool IsVoidResponse(Type returnType) { return returnType == null || returnType.FullName == "System.Void"; } diff --git a/src/NSwag.Generation.Tests/NSwag.Generation.Tests.csproj b/src/NSwag.Generation.Tests/NSwag.Generation.Tests.csproj index 3a93ba738c..22e0a58e57 100644 --- a/src/NSwag.Generation.Tests/NSwag.Generation.Tests.csproj +++ b/src/NSwag.Generation.Tests/NSwag.Generation.Tests.csproj @@ -4,13 +4,17 @@ net8.0 false true - $(NoWarn);1591 + $(NoWarn);1591;CA1707;CA1822; + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/NSwag.Generation.Tests/OpenApiDocumentGeneratorTests.cs b/src/NSwag.Generation.Tests/OpenApiDocumentGeneratorTests.cs index 022384d349..4c83b7999d 100644 --- a/src/NSwag.Generation.Tests/OpenApiDocumentGeneratorTests.cs +++ b/src/NSwag.Generation.Tests/OpenApiDocumentGeneratorTests.cs @@ -1,5 +1,4 @@ -using System.Linq; -using Namotion.Reflection; +using Namotion.Reflection; using NJsonSchema; using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; diff --git a/src/NSwag.Generation.Tests/Processors/OperationSummaryAndDescriptionProcessorTests.cs b/src/NSwag.Generation.Tests/Processors/OperationSummaryAndDescriptionProcessorTests.cs index 7db1f34acd..18d17220f9 100644 --- a/src/NSwag.Generation.Tests/Processors/OperationSummaryAndDescriptionProcessorTests.cs +++ b/src/NSwag.Generation.Tests/Processors/OperationSummaryAndDescriptionProcessorTests.cs @@ -1,7 +1,5 @@ -using System; -using System.ComponentModel; +using System.ComponentModel; using System.Reflection; -using NJsonSchema.Generation; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Annotations; using NSwag.Generation.Processors; @@ -18,7 +16,7 @@ public class DocumentedController public void DocumentedMethodWithOpenApiOperationAttribute() { } - + [Description("\r\n\t This method has a description. \r\n\t")] public void DocumentedMethodWithDescriptionAttribute() { @@ -34,7 +32,7 @@ public void DocumentedMethodWithSummary() { } } - + [Fact] public void Process_TrimsWhitespaceFromOpenApiOperationSummary() { @@ -55,7 +53,7 @@ public void Process_TrimsWhitespaceFromOpenApiOperationSummary() var description = context.OperationDescription.Operation.Description; Assert.Equal("This method has a description.", description); } - + [Fact] public void Process_TrimsWhitespaceFromDescription() { @@ -76,7 +74,7 @@ public void Process_TrimsWhitespaceFromDescription() var description = context.OperationDescription.Operation.Description; Assert.Null(description); } - + [Fact] public void Process_TrimsWhitespaceFromSummary() { @@ -97,7 +95,7 @@ public void Process_TrimsWhitespaceFromSummary() var description = context.OperationDescription.Operation.Description; Assert.Equal("This method has a description.", description); } - + private OperationProcessorContext GetContext(Type controllerType, MethodInfo methodInfo) { var document = new OpenApiDocument(); @@ -106,7 +104,7 @@ private OperationProcessorContext GetContext(Type controllerType, MethodInfo met { SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings() }; - + return new OperationProcessorContext(document, operationDescription, controllerType, methodInfo, null, null, settings, null); } } diff --git a/src/NSwag.Generation.Tests/Processors/OperationTagsProcessorTests.cs b/src/NSwag.Generation.Tests/Processors/OperationTagsProcessorTests.cs index c16ecfbf3b..d3768d493a 100644 --- a/src/NSwag.Generation.Tests/Processors/OperationTagsProcessorTests.cs +++ b/src/NSwag.Generation.Tests/Processors/OperationTagsProcessorTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Reflection; -using NJsonSchema.Generation; +using System.Reflection; using NJsonSchema.NewtonsoftJson.Generation; using NSwag.Annotations; using NSwag.Generation.Processors; diff --git a/src/NSwag.Generation.WebApi/Infrastructure/RouteAttributeFacade.cs b/src/NSwag.Generation.WebApi/Infrastructure/RouteAttributeFacade.cs index 149dfaf94f..50baecf788 100644 --- a/src/NSwag.Generation.WebApi/Infrastructure/RouteAttributeFacade.cs +++ b/src/NSwag.Generation.WebApi/Infrastructure/RouteAttributeFacade.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Linq; using System.Reflection; namespace NSwag.Generation.WebApi.Infrastructure @@ -18,7 +16,7 @@ namespace NSwag.Generation.WebApi.Infrastructure /// * IHttpRouteInfoProvider /// * IRouteTemplateProvider /// - internal class RouteAttributeFacade + internal sealed class RouteAttributeFacade { private readonly PropertyInfo _template; diff --git a/src/NSwag.Generation.WebApi/Infrastructure/RoutePrefixAttributeFacade.cs b/src/NSwag.Generation.WebApi/Infrastructure/RoutePrefixAttributeFacade.cs index faadfb0c51..c46213fdbd 100644 --- a/src/NSwag.Generation.WebApi/Infrastructure/RoutePrefixAttributeFacade.cs +++ b/src/NSwag.Generation.WebApi/Infrastructure/RoutePrefixAttributeFacade.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Linq; using System.Reflection; namespace NSwag.Generation.WebApi.Infrastructure @@ -17,7 +15,7 @@ namespace NSwag.Generation.WebApi.Infrastructure /// * RoutePrefixAttribute /// * IRoutePrefix /// - internal class RoutePrefixAttributeFacade + internal sealed class RoutePrefixAttributeFacade { private readonly PropertyInfo _prefix; diff --git a/src/NSwag.Generation.WebApi/NSwag.Generation.WebApi.csproj b/src/NSwag.Generation.WebApi/NSwag.Generation.WebApi.csproj index 892addd70c..5872457624 100644 --- a/src/NSwag.Generation.WebApi/NSwag.Generation.WebApi.csproj +++ b/src/NSwag.Generation.WebApi/NSwag.Generation.WebApi.csproj @@ -9,4 +9,8 @@ + + + + diff --git a/src/NSwag.Generation.WebApi/Processors/OperationConsumesProcessor.cs b/src/NSwag.Generation.WebApi/Processors/OperationConsumesProcessor.cs index 10788265fc..d8e284aab3 100644 --- a/src/NSwag.Generation.WebApi/Processors/OperationConsumesProcessor.cs +++ b/src/NSwag.Generation.WebApi/Processors/OperationConsumesProcessor.cs @@ -6,10 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; using System.Reflection; -using System.Threading.Tasks; -using System.Linq; using NSwag.Generation.Processors; using NSwag.Generation.Processors.Contexts; @@ -28,14 +25,11 @@ public bool Process(OperationProcessorContext context) .GetCustomAttributes() .SingleOrDefault(a => a.GetType().Name == "ConsumesAttribute"); - if (consumesAttribute == null) - { - // If the action method does not have a Consumes Attribute we'll try with its containing class - consumesAttribute = context.MethodInfo.DeclaringType - .GetTypeInfo() - .GetCustomAttributes() - .SingleOrDefault(a => a.GetType().Name == "ConsumesAttribute"); - } + // If the action method does not have a Consumes Attribute we'll try with its containing class + consumesAttribute ??= context.MethodInfo.DeclaringType + .GetTypeInfo() + .GetCustomAttributes() + .SingleOrDefault(a => a.GetType().Name == "ConsumesAttribute"); if (consumesAttribute != null && consumesAttribute.ContentTypes != null) { diff --git a/src/NSwag.Generation.WebApi/Processors/OperationParameterProcessor.cs b/src/NSwag.Generation.WebApi/Processors/OperationParameterProcessor.cs index cdd877c54a..419b3b64f5 100644 --- a/src/NSwag.Generation.WebApi/Processors/OperationParameterProcessor.cs +++ b/src/NSwag.Generation.WebApi/Processors/OperationParameterProcessor.cs @@ -6,12 +6,8 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; using System.Text.RegularExpressions; -using System.Threading; using Namotion.Reflection; using NJsonSchema; using NJsonSchema.Generation; @@ -125,7 +121,7 @@ public bool Process(OperationProcessorContext context) if (context.OperationDescription.Method == OpenApiOperationMethod.Get) { operationParameter = AddPrimitiveParameter(uriParameterName, context, contextualParameter); - } + } else { // Try to find a [WillReadBody] attribute on either the action parameter or the bindingAttribute's class @@ -155,7 +151,7 @@ public bool Process(OperationProcessorContext context) } } } - else if (fromBodyAttribute != null || (fromUriAttribute == null && _settings.IsAspNetCore == false)) + else if (fromBodyAttribute != null || (fromUriAttribute == null && !_settings.IsAspNetCore)) { operationParameter = AddBodyParameter(context, bodyParameterName, contextualParameter); } @@ -194,7 +190,7 @@ public bool Process(OperationProcessorContext context) { operationParameter.OriginalName = contextualParameter.ParameterInfo.Name; } - + ((Dictionary)context.Parameters)[contextualParameter.ParameterInfo] = operationParameter; } } @@ -258,7 +254,7 @@ private void ApplyOpenApiBodyParameterAttribute(OpenApiOperationDescription oper /// /// Operation to check. /// Schema type. - private void UpdateNullableRawOperationParameters(OpenApiOperationDescription operationDescription, SchemaType schemaType) + private static void UpdateNullableRawOperationParameters(OpenApiOperationDescription operationDescription, SchemaType schemaType) { if (schemaType == SchemaType.OpenApi3) { @@ -269,7 +265,7 @@ private void UpdateNullableRawOperationParameters(OpenApiOperationDescription op } } - private void EnsureSingleBodyParameter(OpenApiOperationDescription operationDescription) + private static void EnsureSingleBodyParameter(OpenApiOperationDescription operationDescription) { if (operationDescription.Operation.ActualParameters.Count(p => p.Kind == OpenApiParameterKind.Body) > 1) { @@ -277,7 +273,7 @@ private void EnsureSingleBodyParameter(OpenApiOperationDescription operationDesc } } - private void UpdateConsumedTypes(OpenApiOperationDescription operationDescription) + private static void UpdateConsumedTypes(OpenApiOperationDescription operationDescription) { if (operationDescription.Operation.ActualParameters.Any(p => p.IsBinary || p.ActualSchema.IsBinary)) { @@ -285,7 +281,7 @@ private void UpdateConsumedTypes(OpenApiOperationDescription operationDescriptio } } - private void RemoveUnusedPathParameters(OpenApiOperationDescription operationDescription, string httpPath) + private static void RemoveUnusedPathParameters(OpenApiOperationDescription operationDescription, string httpPath) { operationDescription.Path = Regex.Replace(httpPath, "{(.*?)(:(([^/]*)?))?}", match => { @@ -337,7 +333,7 @@ private bool IsFileArray(Type type, JsonTypeDescription typeInfo) return true; } - if (typeInfo.Type == JsonObjectType.Array && type.GenericTypeArguments.Any()) + if (typeInfo.Type == JsonObjectType.Array && type.GenericTypeArguments.Length > 0) { var description = _settings.SchemaSettings.ReflectionService.GetDescription(type.GenericTypeArguments[0].ToContextualType(), _settings.SchemaSettings); if (description.Type == JsonObjectType.File || @@ -355,8 +351,8 @@ private OpenApiParameter AddBodyParameter(OperationProcessorContext context, str OpenApiParameter operationParameter; var typeDescription = _settings.SchemaSettings.ReflectionService.GetDescription(contextualParameter.ParameterType, _settings.SchemaSettings); - var isRequired = _settings.AllowNullableBodyParameters == false || contextualParameter.GetAttributes(true).FirstAssignableToTypeNameOrDefault("RequiredAttribute", TypeNameStyle.Name) != null; - var isNullable = _settings.AllowNullableBodyParameters && (typeDescription.IsNullable && !isRequired); + var isRequired = !_settings.AllowNullableBodyParameters || contextualParameter.GetAttributes(true).FirstAssignableToTypeNameOrDefault("RequiredAttribute", TypeNameStyle.Name) != null; + var isNullable = _settings.AllowNullableBodyParameters && typeDescription.IsNullable && !isRequired; var operation = context.OperationDescription.Operation; if (contextualParameter.ParameterType.Name == "XmlDocument" || contextualParameter.ParameterType.Type.InheritsFromTypeName("XmlDocument", TypeNameStyle.Name)) @@ -466,8 +462,8 @@ private OpenApiParameter AddPrimitiveParametersFromUri( InitializeFileParameter(operationParameter, isFileArray); } else if (fromRouteAttribute != null - || httpPath.ToLowerInvariant().Contains("{" + propertyName.ToLower() + "}") - || httpPath.ToLowerInvariant().Contains("{" + propertyName.ToLower() + ":")) + || httpPath.Contains("{" + propertyName + "}", StringComparison.OrdinalIgnoreCase) + || httpPath.Contains("{" + propertyName + ":", StringComparison.OrdinalIgnoreCase)) { operationParameter.Kind = OpenApiParameterKind.Path; operationParameter.IsNullableRaw = false; @@ -495,7 +491,7 @@ private OpenApiParameter AddPrimitiveParameter( { var operationParameter = context.DocumentGenerator.CreatePrimitiveParameter(name, contextualParameter); operationParameter.Kind = OpenApiParameterKind.Query; - operationParameter.IsRequired = operationParameter.IsRequired || contextualParameter.ParameterInfo.HasDefaultValue == false; + operationParameter.IsRequired = operationParameter.IsRequired || !contextualParameter.ParameterInfo.HasDefaultValue; if (contextualParameter.ParameterInfo.HasDefaultValue) { @@ -524,7 +520,7 @@ private OpenApiParameter AddPrimitiveParameter( return operationParameter; } - private void InitializeFileParameter(OpenApiParameter operationParameter, bool isFileArray) + private static void InitializeFileParameter(OpenApiParameter operationParameter, bool isFileArray) { operationParameter.Type = JsonObjectType.File; operationParameter.Kind = OpenApiParameterKind.FormData; diff --git a/src/NSwag.Generation.WebApi/Processors/OperationResponseProcessor.cs b/src/NSwag.Generation.WebApi/Processors/OperationResponseProcessor.cs index 17e75dca53..a1133f1218 100644 --- a/src/NSwag.Generation.WebApi/Processors/OperationResponseProcessor.cs +++ b/src/NSwag.Generation.WebApi/Processors/OperationResponseProcessor.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Linq; using System.Reflection; using Namotion.Reflection; using NSwag.Generation.Processors; diff --git a/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGenerator.cs b/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGenerator.cs index b38dc0a418..c62b03446e 100644 --- a/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGenerator.cs +++ b/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGenerator.cs @@ -6,12 +6,9 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; using System.Collections; -using System.Collections.Generic; -using System.Linq; +using System.Globalization; using System.Reflection; -using System.Threading.Tasks; using Namotion.Reflection; using NJsonSchema; using NSwag.Generation.Processors; @@ -37,8 +34,8 @@ public static IEnumerable GetControllerClasses(Assembly assembly) { // TODO: Move to IControllerClassLoader interface return assembly.ExportedTypes - .Where(t => t.GetTypeInfo().IsAbstract == false) - .Where(t => t.Name.EndsWith("Controller") || + .Where(t => !t.GetTypeInfo().IsAbstract) + .Where(t => t.Name.EndsWith("Controller", StringComparison.Ordinal) || t.InheritsFromTypeName("ApiController", TypeNameStyle.Name) || t.InheritsFromTypeName("ControllerBase", TypeNameStyle.Name)) // in ASP.NET Core, a Web API controller inherits from Controller .Where(t => t.GetTypeInfo().ImplementedInterfaces.All(i => i.FullName != "System.Web.Mvc.IController")) // no MVC controllers (legacy ASP.NET) @@ -60,7 +57,7 @@ public static IEnumerable GetControllerClasses(Assembly assembly) /// The operation has more than one body parameter. public Task GenerateForControllerAsync() { - return GenerateForControllersAsync(new[] { typeof(TController) }); + return GenerateForControllersAsync([typeof(TController)]); } /// Generates a Swagger specification for the given controller type. @@ -69,7 +66,7 @@ public Task GenerateForControllerAsync() /// The operation has more than one body parameter. public Task GenerateForControllerAsync(Type controllerType) { - return GenerateForControllersAsync(new[] { controllerType }); + return GenerateForControllersAsync([controllerType]); } /// Generates a Swagger specification for the given controller types. @@ -119,13 +116,10 @@ await OpenApiDocument.FromJsonAsync(Settings.DocumentTemplate).ConfigureAwait(fa document.Generator = $"NSwag{version}"; document.SchemaType = Settings.SchemaSettings.SchemaType; - document.Consumes = new List { "application/json" }; - document.Produces = new List { "application/json" }; + document.Consumes = ["application/json"]; + document.Produces = ["application/json"]; - if (document.Info == null) - { - document.Info = new OpenApiInfo(); - } + document.Info ??= new OpenApiInfo(); if (string.IsNullOrEmpty(Settings.DocumentTemplate)) { @@ -181,7 +175,7 @@ private bool GenerateForController(OpenApiDocument document, Type controllerType o.Item2.DeclaringType != currentControllerType && o.Item2.DeclaringType.IsAssignableToTypeName(currentControllerType.FullName, TypeNameStyle.FullName)); - if (isPathAlreadyDefinedInInheritanceHierarchy == false) + if (!isPathAlreadyDefinedInInheritanceHierarchy) { var operationDescription = new OpenApiOperationDescription { @@ -220,18 +214,19 @@ private bool AddOperationDescriptionsToDocument(OpenApiDocument document, Type c { var path = operation.Path.Replace("//", "/"); - if (!document.Paths.ContainsKey(path)) + if (!document.Paths.TryGetValue(path, out OpenApiPathItem value)) { - document.Paths[path] = new OpenApiPathItem(); + value = []; + document.Paths[path] = value; } - if (document.Paths[path].ContainsKey(operation.Method)) + if (value.ContainsKey(operation.Method)) { throw new InvalidOperationException("The method '" + operation.Method + "' on path '" + path + "' is registered multiple times " + "(check the DefaultUrlTemplate setting [default for Web API: 'api/{controller}/{id}'; for MVC projects: '{controller}/{action}/{id?}'])."); } - document.Paths[path][operation.Method] = operation.Operation; + value[operation.Method] = operation.Operation; addedOperations++; } } @@ -239,7 +234,7 @@ private bool AddOperationDescriptionsToDocument(OpenApiDocument document, Type c return addedOperations > 0; } - private bool RunOperationProcessors(OpenApiDocument document, Type controllerType, MethodInfo methodInfo, OpenApiOperationDescription operationDescription, + private bool RunOperationProcessors(OpenApiDocument document, Type controllerType, MethodInfo methodInfo, OpenApiOperationDescription operationDescription, List allOperations, OpenApiDocumentGenerator generator, OpenApiSchemaResolver schemaResolver) { var context = new OperationProcessorContext(document, operationDescription, controllerType, @@ -248,7 +243,7 @@ private bool RunOperationProcessors(OpenApiDocument document, Type controllerTyp // 1. Run from settings foreach (var operationProcessor in Settings.OperationProcessors) { - if (operationProcessor.Process(context) == false) + if (!operationProcessor.Process(context)) { return false; } @@ -267,7 +262,7 @@ private bool RunOperationProcessors(OpenApiDocument document, Type controllerTyp (IOperationProcessor)Activator.CreateInstance(attribute.Type, attribute.Parameters) : (IOperationProcessor)Activator.CreateInstance(attribute.Type); - if (operationProcessor.Process(context) == false) + if (!operationProcessor.Process(context)) { return false; } @@ -280,14 +275,14 @@ private static IEnumerable GetActionMethods(Type controllerType) { var methods = controllerType.GetRuntimeMethods().Where(m => m.IsPublic); return methods.Where(m => - m.IsSpecialName == false && // avoid property methods + !m.IsSpecialName && // avoid property methods m.DeclaringType == controllerType && // no inherited methods (handled in GenerateForControllerAsync) m.DeclaringType != typeof(object) && - m.IsStatic == false && + !m.IsStatic && m.GetCustomAttributes().Select(a => a.GetType()).All(a => !a.IsAssignableToTypeName("SwaggerIgnoreAttribute", TypeNameStyle.Name) && !a.IsAssignableToTypeName("NonActionAttribute", TypeNameStyle.Name)) && - m.DeclaringType.FullName.StartsWith("Microsoft.AspNet") == false && // .NET Core (Web API & MVC) + !m.DeclaringType.FullName.StartsWith("Microsoft.AspNet", StringComparison.Ordinal) && // .NET Core (Web API & MVC) m.DeclaringType.FullName != "System.Web.Http.ApiController" && m.DeclaringType.FullName != "System.Web.Mvc.Controller") .Where(m => @@ -310,7 +305,7 @@ private string GetOperationId(OpenApiDocument document, string controllerName, M if (!string.IsNullOrWhiteSpace(httpMethod)) { var attributeName = Char.ToUpperInvariant(httpMethod[0]) + httpMethod.Substring(1).ToLowerInvariant(); - var typeName = string.Format("Microsoft.AspNetCore.Mvc.Http{0}Attribute", attributeName); + var typeName = string.Format(CultureInfo.InvariantCulture, "Microsoft.AspNetCore.Mvc.Http{0}Attribute", attributeName); httpAttribute = method .GetCustomAttributes() .FirstAssignableToTypeNameOrDefault(typeName); @@ -326,7 +321,7 @@ private string GetOperationId(OpenApiDocument document, string controllerName, M } else { - if (controllerName.EndsWith("Controller")) + if (controllerName.EndsWith("Controller", StringComparison.Ordinal)) { controllerName = controllerName.Substring(0, controllerName.Length - 10); } @@ -340,10 +335,10 @@ private string GetOperationId(OpenApiDocument document, string controllerName, M number++; } - return operationId + (number > 1 ? number.ToString() : string.Empty); + return operationId + (number > 1 ? number.ToString(CultureInfo.InvariantCulture) : string.Empty); } - private IEnumerable GetHttpPaths(Type controllerType, MethodInfo method) + private List GetHttpPaths(Type controllerType, MethodInfo method) { var httpPaths = new List(); var controllerName = controllerType.Name.Replace("Controller", string.Empty); @@ -354,11 +349,11 @@ private IEnumerable GetHttpPaths(Type controllerType, MethodInfo method) var routeAttributesOnClass = GetAllRouteAttributes(controllerType); var routePrefixAttribute = GetRoutePrefixAttribute(controllerType); - if (routeAttributes.Any()) + if (routeAttributes.Count > 0) { foreach (var attribute in routeAttributes) { - if (attribute.Template.StartsWith("~/")) // ignore route prefixes + if (attribute.Template.StartsWith("~/", StringComparison.Ordinal)) // ignore route prefixes { httpPaths.Add(attribute.Template.Substring(1)); } @@ -368,7 +363,7 @@ private IEnumerable GetHttpPaths(Type controllerType, MethodInfo method) } else if (routeAttributesOnClass != null) { - if (attribute.Template.StartsWith("/")) + if (attribute.Template.StartsWith('/')) { httpPaths.Add(attribute.Template); } @@ -424,18 +419,18 @@ private IEnumerable GetHttpPaths(Type controllerType, MethodInfo method) .ToList(); } - private IEnumerable ExpandOptionalHttpPathParameters(string path, MethodInfo method) + private static IEnumerable ExpandOptionalHttpPathParameters(string path, MethodInfo method) { - var segments = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + var segments = path.Split(['/'], StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < segments.Length; i++) { var segment = segments[i]; - if (segment.EndsWith("?}")) + if (segment.EndsWith("?}", StringComparison.Ordinal)) { // Only expand if optional parameter is available in action method - if (method.GetParameters().Any(p => segment.StartsWith("{" + p.Name + ":") || segment.StartsWith("{" + p.Name + "?"))) + if (method.GetParameters().Any(p => segment.StartsWith("{" + p.Name + ":", StringComparison.Ordinal) || segment.StartsWith("{" + p.Name + "?", StringComparison.Ordinal))) { - foreach (var p in ExpandOptionalHttpPathParameters(string.Join("/", segments.Take(i).Concat(new[] { segment.Replace("?", "") }).Concat(segments.Skip(i + 1))), method)) + foreach (var p in ExpandOptionalHttpPathParameters(string.Join("/", segments.Take(i).Concat([segment.Replace("?", "")]).Concat(segments.Skip(i + 1))), method)) { yield return p; } @@ -455,7 +450,7 @@ private IEnumerable ExpandOptionalHttpPathParameters(string path, Method yield return path; } - private IEnumerable GetAllRouteAttributes(Type type) + private static IEnumerable GetAllRouteAttributes(Type type) { do { @@ -473,7 +468,7 @@ private IEnumerable GetAllRouteAttributes(Type type) return null; } - private RoutePrefixAttributeFacade GetRoutePrefixAttribute(Type type) + private static RoutePrefixAttributeFacade GetRoutePrefixAttribute(Type type) { do { @@ -491,17 +486,17 @@ private RoutePrefixAttributeFacade GetRoutePrefixAttribute(Type type) return null; } - private IEnumerable GetRouteAttributes(IEnumerable attributes) + private static IEnumerable GetRouteAttributes(IEnumerable attributes) { return attributes.Select(RouteAttributeFacade.TryMake).Where(a => a?.Template != null); } - private IEnumerable GetRoutePrefixAttributes(IEnumerable attributes) + private static IEnumerable GetRoutePrefixAttributes(IEnumerable attributes) { return attributes.Select(RoutePrefixAttributeFacade.TryMake).Where(a => a != null); } - private string GetActionName(MethodInfo method) + private static string GetActionName(MethodInfo method) { dynamic actionNameAttribute = method.GetCustomAttributes() .SingleOrDefault(a => a.GetType().Name == "ActionNameAttribute"); @@ -512,7 +507,7 @@ private string GetActionName(MethodInfo method) } var methodName = method.Name; - if (methodName.EndsWith("Async")) + if (methodName.EndsWith("Async", StringComparison.Ordinal)) { methodName = methodName.Substring(0, methodName.Length - 5); } @@ -520,7 +515,7 @@ private string GetActionName(MethodInfo method) return methodName; } - private IEnumerable GetSupportedHttpMethods(MethodInfo method) + private static IEnumerable GetSupportedHttpMethods(MethodInfo method) { // See http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api @@ -569,7 +564,7 @@ private IEnumerable GetSupportedHttpMethods(MethodInfo method) } } - private IEnumerable GetSupportedHttpMethodsFromAttributes(MethodInfo method) + private static IEnumerable GetSupportedHttpMethodsFromAttributes(MethodInfo method) { if (method.GetCustomAttributes().Any(a => a.GetType().Name == "HttpGetAttribute")) { @@ -611,7 +606,7 @@ private IEnumerable GetSupportedHttpMethodsFromAttributes(MethodInfo met if (acceptVerbsAttribute != null) { - IEnumerable httpMethods = new List(); + IEnumerable httpMethods = []; if (ObjectExtensions.HasProperty(acceptVerbsAttribute, "HttpMethods")) { diff --git a/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGeneratorSettings.cs b/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGeneratorSettings.cs index a451b26600..725c68bc27 100644 --- a/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGeneratorSettings.cs +++ b/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGeneratorSettings.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using NJsonSchema.Generation; using NSwag.Generation.Processors; using NSwag.Generation.WebApi.Processors; diff --git a/src/NSwag.Generation/Collections/CollectionExtensions.cs b/src/NSwag.Generation/Collections/CollectionExtensions.cs index 62ae745105..27047211b6 100644 --- a/src/NSwag.Generation/Collections/CollectionExtensions.cs +++ b/src/NSwag.Generation/Collections/CollectionExtensions.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace NSwag.Generation.Collections +namespace NSwag.Generation.Collections { internal static class CollectionExtensions { diff --git a/src/NSwag.Generation/GenericResultWrapperTypes.cs b/src/NSwag.Generation/GenericResultWrapperTypes.cs index 8207e3d11e..7dc170906e 100644 --- a/src/NSwag.Generation/GenericResultWrapperTypes.cs +++ b/src/NSwag.Generation/GenericResultWrapperTypes.cs @@ -1,13 +1,8 @@ -using System; -namespace NSwag.Generation +namespace NSwag.Generation { internal static class GenericResultWrapperTypes { - internal static bool IsGenericWrapperType(string typeName) => - typeName == "Task`1" || - typeName == "ValueTask`1" || - typeName == "JsonResult`1" || - typeName == "ActionResult`1"; + private static bool IsGenericWrapperType(string typeName) => typeName is "Task`1" or "ValueTask`1" or "JsonResult`1" or "ActionResult`1"; internal static T RemoveGenericWrapperTypes(T type, Func getName, Func unwrap) { @@ -20,4 +15,4 @@ internal static T RemoveGenericWrapperTypes(T type, Func getName, return type; } } -} +} \ No newline at end of file diff --git a/src/NSwag.Generation/IOpenApiDocumentGenerator.cs b/src/NSwag.Generation/IOpenApiDocumentGenerator.cs index f0f75abcfc..ad17a61286 100644 --- a/src/NSwag.Generation/IOpenApiDocumentGenerator.cs +++ b/src/NSwag.Generation/IOpenApiDocumentGenerator.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Threading.Tasks; - namespace NSwag.Generation { /// The interface. diff --git a/src/NSwag.Generation/NSwag.Generation.csproj b/src/NSwag.Generation/NSwag.Generation.csproj index 286169061c..6006a82408 100644 --- a/src/NSwag.Generation/NSwag.Generation.csproj +++ b/src/NSwag.Generation/NSwag.Generation.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/NSwag.Generation/OpenApiDocumentGenerator.cs b/src/NSwag.Generation/OpenApiDocumentGenerator.cs index 424a5c501f..e1c9a5055b 100644 --- a/src/NSwag.Generation/OpenApiDocumentGenerator.cs +++ b/src/NSwag.Generation/OpenApiDocumentGenerator.cs @@ -57,11 +57,11 @@ public OpenApiParameter CreateUntypedPathParameter(string parameterName, string parameter.Type = JsonObjectType.String; parameter.Format = JsonFormatStrings.Guid; } - else if (parameterType == "int" || parameterType == "integer" || parameterType == "short" || parameterType == "long") + else if (parameterType is "int" or "integer" or "short" or "long") { parameter.Type = JsonObjectType.Integer; } - else if (parameterType == "number" || parameterType == "decimal" || parameterType == "double") + else if (parameterType is "number" or "decimal" or "double") { parameter.Type = JsonObjectType.Number; } @@ -96,7 +96,7 @@ public OpenApiParameter CreatePrimitiveParameter(string name, string description _settings.SchemaSettings.DefaultReferenceTypeNullHandling, _settings.SchemaSettings); - typeDescription.IsNullable = enforceNotNull == false && typeDescription.IsNullable; + typeDescription.IsNullable = !enforceNotNull && typeDescription.IsNullable; var operationParameter = _settings.SchemaSettings.SchemaType == SchemaType.Swagger2 ? CreatePrimitiveSwaggerParameter(contextualParameter, typeDescription) diff --git a/src/NSwag.Generation/OpenApiDocumentGeneratorSettings.cs b/src/NSwag.Generation/OpenApiDocumentGeneratorSettings.cs index 94fabeb217..6330bd9e76 100644 --- a/src/NSwag.Generation/OpenApiDocumentGeneratorSettings.cs +++ b/src/NSwag.Generation/OpenApiDocumentGeneratorSettings.cs @@ -13,7 +13,6 @@ using NSwag.Generation.Processors; using NSwag.Generation.Processors.Collections; using NSwag.Generation.Processors.Contexts; -using System; namespace NSwag.Generation { @@ -56,20 +55,20 @@ public OpenApiDocumentGeneratorSettings() /// Gets the operation processors. [JsonIgnore] - public OperationProcessorCollection OperationProcessors { get; } = new OperationProcessorCollection - { + public OperationProcessorCollection OperationProcessors { get; } = + [ new OperationSummaryAndDescriptionProcessor(), new OperationTagsProcessor(), - new OperationExtensionDataProcessor(), - }; + new OperationExtensionDataProcessor() + ]; /// Gets the document processors. [JsonIgnore] - public DocumentProcessorCollection DocumentProcessors { get; } = new DocumentProcessorCollection - { + public DocumentProcessorCollection DocumentProcessors { get; } = + [ new DocumentTagsProcessor(), - new DocumentExtensionDataProcessor(), - }; + new DocumentExtensionDataProcessor() + ]; /// Gets or sets the document template representing the initial Swagger specification (JSON data). public string DocumentTemplate { get; set; } @@ -80,7 +79,7 @@ public OpenApiDocumentGeneratorSettings() public bool UseControllerSummaryAsTagDescription { get; set; } /// Gets or sets a value indicating whether the HttpMethodAttribute Name property shall be used as OperationId. - public bool UseHttpAttributeNameAsOperationId { get; set; } = false; + public bool UseHttpAttributeNameAsOperationId { get; set; } /// Inserts a function based operation processor at the beginning of the pipeline to be used to filter operations. /// The processor filter. diff --git a/src/NSwag.Generation/OpenApiSchemaGenerator.cs b/src/NSwag.Generation/OpenApiSchemaGenerator.cs index eb1ebc906f..0ab6530882 100644 --- a/src/NSwag.Generation/OpenApiSchemaGenerator.cs +++ b/src/NSwag.Generation/OpenApiSchemaGenerator.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; using Namotion.Reflection; using NJsonSchema; using NJsonSchema.Generation; @@ -21,7 +20,7 @@ public class OpenApiSchemaGenerator : JsonSchemaGenerator /// Initializes a new instance of the class. /// The settings. - public OpenApiSchemaGenerator(OpenApiDocumentGeneratorSettings settings) + public OpenApiSchemaGenerator(OpenApiDocumentGeneratorSettings settings) : base(settings.SchemaSettings) { } @@ -81,7 +80,7 @@ public override TSchemaType GenerateWithReferenceAndNullability( return base.GenerateWithReferenceAndNullability(contextualType, isNullable, schemaResolver, transformation); } - private bool IsFileResponse(Type returnType) + private static bool IsFileResponse(Type returnType) { return returnType.IsAssignableToTypeName("FileResult", TypeNameStyle.Name) || returnType.Name == "IActionResult" || diff --git a/src/NSwag.Generation/Processors/ActionDocumentProcessor.cs b/src/NSwag.Generation/Processors/ActionDocumentProcessor.cs index 4c4984b14e..aed3ba439e 100644 --- a/src/NSwag.Generation/Processors/ActionDocumentProcessor.cs +++ b/src/NSwag.Generation/Processors/ActionDocumentProcessor.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; using NSwag.Generation.Processors.Contexts; namespace NSwag.Generation.Processors diff --git a/src/NSwag.Generation/Processors/ApiVersionProcessor.cs b/src/NSwag.Generation/Processors/ApiVersionProcessor.cs index f917259d95..b08ca276b1 100644 --- a/src/NSwag.Generation/Processors/ApiVersionProcessor.cs +++ b/src/NSwag.Generation/Processors/ApiVersionProcessor.cs @@ -7,8 +7,6 @@ //----------------------------------------------------------------------- using System.Collections; -using System.Collections.Generic; -using System.Linq; using System.Reflection; using Namotion.Reflection; using NSwag.Generation.Processors.Contexts; @@ -45,7 +43,7 @@ public bool Process(OperationProcessorContext context) else { var versions = GetVersions(context, "ApiVersionAttribute"); - if (versions.Any()) + if (versions.Length > 0) { if (versions.Any(v => IncludedVersions == null || IncludedVersions.Length == 0 || IncludedVersions.Contains(v))) { @@ -54,7 +52,7 @@ public bool Process(OperationProcessorContext context) var version = mappedVersions.FirstOrDefault(v => IncludedVersions == null || IncludedVersions.Length == 0 || IncludedVersions.Contains(v)); if (version == null && mappedVersions.Length == 0) { - version = IncludedVersions != null && IncludedVersions.Any() ? IncludedVersions[0] : versions[0]; + version = IncludedVersions != null && IncludedVersions.Length > 0 ? IncludedVersions[0] : versions[0]; } if (version != null) @@ -75,7 +73,7 @@ public bool Process(OperationProcessorContext context) } } - private bool UseVersionedApiExplorer(OperationProcessorContext context) + private static bool UseVersionedApiExplorer(OperationProcessorContext context) { if (context.HasProperty("ApiDescription")) { @@ -89,14 +87,14 @@ private bool UseVersionedApiExplorer(OperationProcessorContext context) return false; } - private void RemoveApiVersionPathParameter(OperationProcessorContext context, string version) + private static void RemoveApiVersionPathParameter(OperationProcessorContext context, string version) { var operationDescription = context.OperationDescription; operationDescription.Path = operationDescription.Path.Replace("{version:apiVersion}", version); operationDescription.Path = operationDescription.Path.Replace("{version}", version); } - private string[] GetVersions(OperationProcessorContext context, string attributeType) + private static string[] GetVersions(OperationProcessorContext context, string attributeType) { var versionAttributes = context.MethodInfo.GetCustomAttributes() .Concat(context.MethodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes()) diff --git a/src/NSwag.Generation/Processors/Collections/DocumentProcessorCollection.cs b/src/NSwag.Generation/Processors/Collections/DocumentProcessorCollection.cs index c9a09e340b..04084712b8 100644 --- a/src/NSwag.Generation/Processors/Collections/DocumentProcessorCollection.cs +++ b/src/NSwag.Generation/Processors/Collections/DocumentProcessorCollection.cs @@ -7,7 +7,6 @@ //----------------------------------------------------------------------- using System.Collections.ObjectModel; -using System.Linq; namespace NSwag.Generation.Processors.Collections { diff --git a/src/NSwag.Generation/Processors/Collections/OperationProcessorCollection.cs b/src/NSwag.Generation/Processors/Collections/OperationProcessorCollection.cs index 1eec9dc36b..877fb80713 100644 --- a/src/NSwag.Generation/Processors/Collections/OperationProcessorCollection.cs +++ b/src/NSwag.Generation/Processors/Collections/OperationProcessorCollection.cs @@ -7,7 +7,6 @@ //----------------------------------------------------------------------- using System.Collections.ObjectModel; -using System.Linq; namespace NSwag.Generation.Processors.Collections { diff --git a/src/NSwag.Generation/Processors/Contexts/DocumentProcessorContext.cs b/src/NSwag.Generation/Processors/Contexts/DocumentProcessorContext.cs index 5220941ca5..41dbbd8a65 100644 --- a/src/NSwag.Generation/Processors/Contexts/DocumentProcessorContext.cs +++ b/src/NSwag.Generation/Processors/Contexts/DocumentProcessorContext.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; using NJsonSchema.Generation; namespace NSwag.Generation.Processors.Contexts diff --git a/src/NSwag.Generation/Processors/Contexts/OperationProcessorContext.cs b/src/NSwag.Generation/Processors/Contexts/OperationProcessorContext.cs index 5254d51eae..a0b81f8f08 100644 --- a/src/NSwag.Generation/Processors/Contexts/OperationProcessorContext.cs +++ b/src/NSwag.Generation/Processors/Contexts/OperationProcessorContext.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; using System.Reflection; using NJsonSchema.Generation; diff --git a/src/NSwag.Generation/Processors/DocumentExtensionDataProcessor.cs b/src/NSwag.Generation/Processors/DocumentExtensionDataProcessor.cs index 3759998086..f4248978bb 100644 --- a/src/NSwag.Generation/Processors/DocumentExtensionDataProcessor.cs +++ b/src/NSwag.Generation/Processors/DocumentExtensionDataProcessor.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using System.Reflection; using Namotion.Reflection; using NSwag.Generation.Processors.Contexts; diff --git a/src/NSwag.Generation/Processors/DocumentTagsProcessor.cs b/src/NSwag.Generation/Processors/DocumentTagsProcessor.cs index 6a01591ccd..c0fca20669 100644 --- a/src/NSwag.Generation/Processors/DocumentTagsProcessor.cs +++ b/src/NSwag.Generation/Processors/DocumentTagsProcessor.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using Namotion.Reflection; using NSwag.Generation.Collections; using NSwag.Generation.Processors.Contexts; @@ -42,13 +39,9 @@ private static void ProcessTagsAttribute(OpenApiDocument document, Type controll .Select(t => new OpenApiTag { Name = t }) .ToList(); - if (tags.Any()) + if (tags.Count > 0) { - if (document.Tags == null) - { - document.Tags = new List(); - } - + document.Tags ??= []; foreach (var tag in tags) { if (document.Tags.All(t => t.Name != tag.Name)) @@ -69,12 +62,9 @@ private static void ProcessTagAttributes(OpenApiDocument document, Type controll .Select(a => (dynamic)a) .ToArray(); - if (tagAttributes.Any()) + foreach (var tagAttribute in tagAttributes) { - foreach (var tagAttribute in tagAttributes) - { - ProcessTagAttribute(document, tagAttribute); - } + ProcessTagAttribute(document, tagAttribute); } } diff --git a/src/NSwag.Generation/Processors/IDocumentProcessor.cs b/src/NSwag.Generation/Processors/IDocumentProcessor.cs index 7e15d9e4d8..04cd97e401 100644 --- a/src/NSwag.Generation/Processors/IDocumentProcessor.cs +++ b/src/NSwag.Generation/Processors/IDocumentProcessor.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Threading.Tasks; using NSwag.Generation.Processors.Contexts; namespace NSwag.Generation.Processors diff --git a/src/NSwag.Generation/Processors/OperationExtensionDataProcessor.cs b/src/NSwag.Generation/Processors/OperationExtensionDataProcessor.cs index 2357dcd4e7..19f9664a47 100644 --- a/src/NSwag.Generation/Processors/OperationExtensionDataProcessor.cs +++ b/src/NSwag.Generation/Processors/OperationExtensionDataProcessor.cs @@ -6,10 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using System.Reflection; -using System.Threading.Tasks; using Namotion.Reflection; using NSwag.Generation.Processors.Contexts; @@ -26,10 +23,7 @@ public class OperationExtensionDataProcessor : IOperationProcessor public bool Process(OperationProcessorContext context) { var operation = context.OperationDescription.Operation; - if (operation.ExtensionData == null) - { - operation.ExtensionData = new Dictionary(); - } + operation.ExtensionData ??= new Dictionary(); if (context.MethodInfo != null) { diff --git a/src/NSwag.Generation/Processors/OperationProcessor.cs b/src/NSwag.Generation/Processors/OperationProcessor.cs index c5d08b24e3..fe65a91190 100644 --- a/src/NSwag.Generation/Processors/OperationProcessor.cs +++ b/src/NSwag.Generation/Processors/OperationProcessor.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Threading.Tasks; using NSwag.Generation.Processors.Contexts; namespace NSwag.Generation.Processors diff --git a/src/NSwag.Generation/Processors/OperationResponseDescription.cs b/src/NSwag.Generation/Processors/OperationResponseDescription.cs index 03acdc03ae..fca2eb31a0 100644 --- a/src/NSwag.Generation/Processors/OperationResponseDescription.cs +++ b/src/NSwag.Generation/Processors/OperationResponseDescription.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; - namespace NSwag.Generation.Processors { /// Describes an operation response. diff --git a/src/NSwag.Generation/Processors/OperationResponseProcessorBase.cs b/src/NSwag.Generation/Processors/OperationResponseProcessorBase.cs index 9e6ee3a29e..a979aa64c8 100644 --- a/src/NSwag.Generation/Processors/OperationResponseProcessorBase.cs +++ b/src/NSwag.Generation/Processors/OperationResponseProcessorBase.cs @@ -6,11 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; -using System.Threading.Tasks; using System.Xml.Linq; using Namotion.Reflection; using NJsonSchema; @@ -188,14 +184,14 @@ private void ProcessOperationDescriptions(IEnumerable r.IsNullable) && _settings.SchemaSettings.ReflectionService.GetDescription(contextualReturnType, _settings.DefaultResponseReferenceTypeNullHandling, _settings.SchemaSettings).IsNullable; @@ -233,7 +229,7 @@ private void ProcessOperationDescriptions(IEnumerable GenerateExpectedSchemas( + private List GenerateExpectedSchemas( IGrouping group, OperationProcessorContext context) { if (group.Count() > 1) @@ -281,7 +277,7 @@ private void LoadDefaultSuccessResponse(ParameterInfo returnParameter, string su } else { - var returnParameterAttributes = returnParameter?.GetCustomAttributes(false)?.OfType() ?? Enumerable.Empty(); + var returnParameterAttributes = returnParameter?.GetCustomAttributes(false)?.OfType() ?? []; var contextualReturnParameter = returnType.ToContextualType(returnParameterAttributes); var typeDescription = _settings.SchemaSettings.ReflectionService.GetDescription(contextualReturnParameter, _settings.SchemaSettings); @@ -297,7 +293,7 @@ private void LoadDefaultSuccessResponse(ParameterInfo returnParameter, string su } } - private bool IsVoidResponse(Type returnType) + private static bool IsVoidResponse(Type returnType) { return returnType == null || returnType.FullName == "System.Void"; } diff --git a/src/NSwag.Generation/Processors/OperationSummaryAndDescriptionProcessor.cs b/src/NSwag.Generation/Processors/OperationSummaryAndDescriptionProcessor.cs index 7b69b38ca5..cae8f1026f 100644 --- a/src/NSwag.Generation/Processors/OperationSummaryAndDescriptionProcessor.cs +++ b/src/NSwag.Generation/Processors/OperationSummaryAndDescriptionProcessor.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; using Namotion.Reflection; using NJsonSchema.Generation; @@ -24,7 +21,7 @@ public class OperationSummaryAndDescriptionProcessor : IOperationProcessor /// true if the operation should be added to the Swagger specification. public bool Process(OperationProcessorContext context) { - var attributes = context.MethodInfo?.GetCustomAttributes().ToArray() ?? new Attribute[0]; + var attributes = context.MethodInfo?.GetCustomAttributes().ToArray() ?? []; ProcessSummary(context, attributes); ProcessDescription(context, attributes); @@ -32,7 +29,7 @@ public bool Process(OperationProcessorContext context) return true; } - private void ProcessSummary(OperationProcessorContext context, Attribute[] attributes) + private static void ProcessSummary(OperationProcessorContext context, Attribute[] attributes) { dynamic openApiOperationAttribute = attributes .SingleOrDefault(a => a.GetType().Name == "OpenApiOperationAttribute"); @@ -58,7 +55,7 @@ private void ProcessSummary(OperationProcessorContext context, Attribute[] attri } } - private void ProcessDescription(OperationProcessorContext context, Attribute[] attributes) + private static void ProcessDescription(OperationProcessorContext context, Attribute[] attributes) { dynamic openApiOperationAttribute = attributes .SingleOrDefault(a => a.GetType().Name == "OpenApiOperationAttribute"); diff --git a/src/NSwag.Generation/Processors/OperationTagsProcessor.cs b/src/NSwag.Generation/Processors/OperationTagsProcessor.cs index b652f8a3ad..f92d1a5bc7 100644 --- a/src/NSwag.Generation/Processors/OperationTagsProcessor.cs +++ b/src/NSwag.Generation/Processors/OperationTagsProcessor.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using System.Reflection; using Namotion.Reflection; using NJsonSchema.Generation; @@ -32,7 +30,7 @@ public virtual bool Process(OperationProcessorContext context) if (context.ControllerType != null) { - if (!context.OperationDescription.Operation.Tags.Any()) + if (context.OperationDescription.Operation.Tags.Count == 0) { var typeInfo = context.ControllerType.GetTypeInfo(); @@ -40,7 +38,7 @@ public virtual bool Process(OperationProcessorContext context) ProcessControllerSwaggerTagAttributes(context.OperationDescription, typeInfo); } - if (!context.OperationDescription.Operation.Tags.Any()) + if (context.OperationDescription.Operation.Tags.Count == 0) { AddControllerNameTag(context); } @@ -54,7 +52,7 @@ public virtual bool Process(OperationProcessorContext context) protected virtual void AddControllerNameTag(OperationProcessorContext context) { var controllerName = context.ControllerType.Name; - if (controllerName.EndsWith("Controller")) + if (controllerName.EndsWith("Controller", StringComparison.Ordinal)) { controllerName = controllerName.Substring(0, controllerName.Length - 10); } @@ -70,7 +68,7 @@ protected virtual void AddControllerNameTag(OperationProcessorContext context) /// The context. /// The tag name. /// The description. - protected void UpdateDocumentTagDescription(OperationProcessorContext context, string tagName, string description) + protected static void UpdateDocumentTagDescription(OperationProcessorContext context, string tagName, string description) { if (!context.Settings.UseControllerSummaryAsTagDescription || string.IsNullOrEmpty(description)) { @@ -82,7 +80,7 @@ protected void UpdateDocumentTagDescription(OperationProcessorContext context, s documentTag.Description = description; } - private void ProcessSwaggerTagAttributes(OpenApiDocument document, OpenApiOperationDescription operationDescription, MethodInfo methodInfo) + private static void ProcessSwaggerTagAttributes(OpenApiDocument document, OpenApiOperationDescription operationDescription, MethodInfo methodInfo) { foreach (var tagAttribute in methodInfo.GetCustomAttributes() .GetAssignableToTypeName("SwaggerTagAttribute", TypeNameStyle.Name) @@ -100,7 +98,7 @@ private void ProcessSwaggerTagAttributes(OpenApiDocument document, OpenApiOperat } } - private void ProcessSwaggerTagsAttribute(OpenApiDocument document, OpenApiOperationDescription operationDescription, MethodInfo methodInfo) + private static void ProcessSwaggerTagsAttribute(OpenApiDocument document, OpenApiOperationDescription operationDescription, MethodInfo methodInfo) { dynamic tagsAttribute = methodInfo .GetCustomAttributes() @@ -118,11 +116,7 @@ private void ProcessSwaggerTagsAttribute(OpenApiDocument document, OpenApiOperat if (ObjectExtensions.HasProperty(tagsAttribute, "AddToDocument") && tagsAttribute.AddToDocument) { - if (document.Tags == null) - { - document.Tags = new List(); - } - + document.Tags ??= []; if (document.Tags.All(t => t.Name != tag)) { document.Tags.Add(new OpenApiTag { Name = tag }); @@ -132,7 +126,7 @@ private void ProcessSwaggerTagsAttribute(OpenApiDocument document, OpenApiOperat } } - private void ProcessControllerSwaggerTagsAttribute(OpenApiOperationDescription operationDescription, TypeInfo typeInfo) + private static void ProcessControllerSwaggerTagsAttribute(OpenApiOperationDescription operationDescription, TypeInfo typeInfo) { dynamic tagsAttribute = typeInfo .GetCustomAttributes() @@ -151,7 +145,7 @@ private void ProcessControllerSwaggerTagsAttribute(OpenApiOperationDescription o } } - private void ProcessControllerSwaggerTagAttributes(OpenApiOperationDescription operationDescription, TypeInfo typeInfo) + private static void ProcessControllerSwaggerTagAttributes(OpenApiOperationDescription operationDescription, TypeInfo typeInfo) { foreach (var tagAttribute in typeInfo.GetCustomAttributes() .GetAssignableToTypeName("OpenApiTagAttribute", TypeNameStyle.Name) diff --git a/src/NSwag.Generation/Processors/Security/OperationSecurityScopeProcessor.cs b/src/NSwag.Generation/Processors/Security/OperationSecurityScopeProcessor.cs index 667d9efe80..86f5c7a078 100644 --- a/src/NSwag.Generation/Processors/Security/OperationSecurityScopeProcessor.cs +++ b/src/NSwag.Generation/Processors/Security/OperationSecurityScopeProcessor.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Collections.Generic; -using System.Linq; using System.Reflection; using NSwag.Generation.Processors.Contexts; @@ -37,7 +35,7 @@ public bool Process(OperationProcessorContext context) { if (context.OperationDescription.Operation.Security == null) { - context.OperationDescription.Operation.Security = new List(); + context.OperationDescription.Operation.Security = []; } var scopes = GetScopes(context.OperationDescription, context.MethodInfo); @@ -59,9 +57,9 @@ protected virtual IEnumerable GetScopes(OpenApiOperationDescription oper methodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes()); var authorizeAttributes = allAttributes.Where(a => a.GetType().Name == "AuthorizeAttribute").ToList(); - if (!authorizeAttributes.Any()) + if (authorizeAttributes.Count == 0) { - return Enumerable.Empty(); + return []; } return authorizeAttributes diff --git a/src/NSwag.Generation/Processors/Security/SecurityDefinitionAppender.cs b/src/NSwag.Generation/Processors/Security/SecurityDefinitionAppender.cs index cbb8c36de1..8274358f04 100644 --- a/src/NSwag.Generation/Processors/Security/SecurityDefinitionAppender.cs +++ b/src/NSwag.Generation/Processors/Security/SecurityDefinitionAppender.cs @@ -6,9 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; using NSwag.Generation.Processors.Contexts; namespace NSwag.Generation.Processors.Security @@ -50,7 +47,7 @@ public void Process(DocumentProcessorContext context) { if (context.Document.Security == null) { - context.Document.Security = new Collection(); + context.Document.Security = []; } context.Document.Security.Add(new OpenApiSecurityRequirement diff --git a/src/NSwag.MSBuild/NSwag.MSBuild.nuspec b/src/NSwag.MSBuild/NSwag.MSBuild.nuspec index b438e64b3d..542cc1952f 100644 --- a/src/NSwag.MSBuild/NSwag.MSBuild.nuspec +++ b/src/NSwag.MSBuild/NSwag.MSBuild.nuspec @@ -28,7 +28,7 @@ - + diff --git a/src/NSwag.MSBuild/NSwag.MSBuild.props b/src/NSwag.MSBuild/NSwag.MSBuild.props index 20efc1c697..8b9d3e65ec 100644 --- a/src/NSwag.MSBuild/NSwag.MSBuild.props +++ b/src/NSwag.MSBuild/NSwag.MSBuild.props @@ -3,11 +3,11 @@ "$(MSBuildThisFileDirectory)../tools/Win/NSwag.exe" "$(MSBuildThisFileDirectory)../tools/Win/NSwag.x86.exe" - dotnet "$(MSBuildThisFileDirectory)../tools/Net60/dotnet-nswag.dll" dotnet "$(MSBuildThisFileDirectory)../tools/Net80/dotnet-nswag.dll" + dotnet "$(MSBuildThisFileDirectory)../tools/Net90/dotnet-nswag.dll" $(MSBuildThisFileDirectory)../tools/Win/ - $(MSBuildThisFileDirectory)../tools/Net60/ $(MSBuildThisFileDirectory)../tools/Net80/ + $(MSBuildThisFileDirectory)../tools/Net90/ diff --git a/src/NSwag.NoInstaller.slnf b/src/NSwag.NoInstaller.slnf index 22d6de4ff5..27cd432f64 100644 --- a/src/NSwag.NoInstaller.slnf +++ b/src/NSwag.NoInstaller.slnf @@ -30,10 +30,10 @@ "NSwag.Generation.Tests\\NSwag.Generation.Tests.csproj", "NSwag.Generation.WebApi\\NSwag.Generation.WebApi.csproj", "NSwag.Generation\\NSwag.Generation.csproj", - "NSwag.Sample.NET60Minimal\\NSwag.Sample.NET60Minimal.csproj", - "NSwag.Sample.NET60\\NSwag.Sample.NET60.csproj", "NSwag.Sample.NET80Minimal\\NSwag.Sample.NET80Minimal.csproj", - "NSwag.Sample.NET80\\NSwag.Sample.NET80.csproj" + "NSwag.Sample.NET80\\NSwag.Sample.NET80.csproj", + "NSwag.Sample.NET90Minimal\\NSwag.Sample.NET90Minimal.csproj", + "NSwag.Sample.NET90\\NSwag.Sample.NET90.csproj" ] } } \ No newline at end of file diff --git a/src/NSwag.Npm/README.md b/src/NSwag.Npm/README.md index 083db8b3db..efb43cdc0a 100644 --- a/src/NSwag.Npm/README.md +++ b/src/NSwag.Npm/README.md @@ -39,11 +39,11 @@ Add the switch `/runtime:NetCore*` to the command to execute one of the .NET Cor To specify what .NET Core binaries to execute, either use (default) - nswag version /runtime:Net60 + nswag version /runtime:Net80 or - nswag version /runtime:Net80 + nswag version /runtime:Net90 ## Development diff --git a/src/NSwag.Npm/bin/nswag.js b/src/NSwag.Npm/bin/nswag.js index 16add27913..c1446d91fe 100644 --- a/src/NSwag.Npm/bin/nswag.js +++ b/src/NSwag.Npm/bin/nswag.js @@ -3,8 +3,8 @@ var defaultCoreVersion = "Net80"; var supportedCoreVersions = [ - { ver: '6.0', dir: "Net60", }, { ver: '8.0', dir: "Net80", }, + { ver: '9.0', dir: "Net90", }, ]; // Initialize @@ -15,8 +15,8 @@ var args = process.argv.splice(2, process.argv.length - 2).map(function (a) { re // Legacy support args = args.replace("--x86", "/runtime:WinX86"); args = args.replace("/runtime:x86", "/runtime:WinX86"); -args = args.replace("--core 6.0", "/runtime:Net60"); args = args.replace("--core 8.0", "/runtime:Net80"); +args = args.replace("--core 9.0", "/runtime:Net90"); args = args.replace("--core", "/runtime:" + defaultCoreVersion); // Search for full .NET installation diff --git a/src/NSwag.Npm/package.json b/src/NSwag.Npm/package.json index 2893c0fa53..ff985ebb23 100644 --- a/src/NSwag.Npm/package.json +++ b/src/NSwag.Npm/package.json @@ -1,6 +1,6 @@ { "name": "nswag", - "version": "14.0.0", + "version": "14.2.0", "optionalDependencies": {}, "repository": { "type": "git", diff --git a/src/NSwag.Sample.NET60/NSwag.Sample.NET60.csproj b/src/NSwag.Sample.NET60/NSwag.Sample.NET60.csproj deleted file mode 100644 index 0890a7bd8c..0000000000 --- a/src/NSwag.Sample.NET60/NSwag.Sample.NET60.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - net6.0 - enable - - - - - - - - - - - diff --git a/src/NSwag.Sample.NET60Minimal/nswag.json b/src/NSwag.Sample.NET60Minimal/nswag.json deleted file mode 100644 index c00a25bfe7..0000000000 --- a/src/NSwag.Sample.NET60Minimal/nswag.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "runtime": "Net60", - "defaultVariables": null, - "documentGenerator": { - "aspNetCoreToOpenApi": { - "project": "NSwag.Sample.NET60Minimal.csproj", - "msBuildProjectExtensionsPath": null, - "configuration": null, - "runtime": null, - "targetFramework": null, - "noBuild": false, - "verbose": true, - "workingDirectory": null, - "requireParametersWithoutDefault": false, - "apiGroupNames": null, - "defaultPropertyNameHandling": "Default", - "defaultReferenceTypeNullHandling": "Null", - "defaultDictionaryValueReferenceTypeNullHandling": "NotNull", - "defaultResponseReferenceTypeNullHandling": "NotNull", - "defaultEnumHandling": "Integer", - "flattenInheritanceHierarchy": false, - "generateKnownTypes": true, - "generateEnumMappingDescription": false, - "generateXmlObjects": false, - "generateAbstractProperties": false, - "generateAbstractSchemas": true, - "ignoreObsoleteProperties": false, - "allowReferencesWithProperties": false, - "excludedTypeNames": [], - "serviceHost": null, - "serviceBasePath": null, - "serviceSchemes": [], - "infoTitle": "My Title", - "infoDescription": null, - "infoVersion": "1.0.0", - "documentTemplate": null, - "documentProcessorTypes": [], - "operationProcessorTypes": [], - "typeNameGeneratorType": null, - "schemaNameGeneratorType": null, - "contractResolverType": null, - "serializerSettingsType": null, - "documentName": "v1", - "aspNetCoreEnvironment": null, - "createWebHostBuilderMethod": null, - "startupType": null, - "allowNullableBodyParameters": true, - "output": "openapi.json", - "outputType": "Swagger2", - "assemblyPaths": [], - "assemblyConfig": null, - "referencePaths": [], - "useNuGetCache": false - } - }, - "codeGenerators": {} -} \ No newline at end of file diff --git a/src/NSwag.Sample.NET80/Controllers/ValuesController.cs b/src/NSwag.Sample.NET80/Controllers/ValuesController.cs index 1629cced31..81b47c9db6 100644 --- a/src/NSwag.Sample.NET80/Controllers/ValuesController.cs +++ b/src/NSwag.Sample.NET80/Controllers/ValuesController.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; namespace NSwag.Sample.NET80.Controllers { @@ -19,7 +17,9 @@ public class Person public DateTime DayOfBirth { get; set; } } +#pragma warning disable CA1711 public enum TestEnum +#pragma warning restore CA1711 { Foo, Bar @@ -28,7 +28,7 @@ public enum TestEnum [HttpGet] public ActionResult> Get() { - return new Person[] { }; + return Array.Empty(); } // GET api/values/5 diff --git a/src/NSwag.Sample.NET80/Program.cs b/src/NSwag.Sample.NET80/Program.cs index 3a722a0021..54ec290542 100644 --- a/src/NSwag.Sample.NET80/Program.cs +++ b/src/NSwag.Sample.NET80/Program.cs @@ -1,6 +1,3 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - namespace NSwag.Sample.NET80 { public class Program diff --git a/src/NSwag.Sample.NET80/Startup.cs b/src/NSwag.Sample.NET80/Startup.cs index 081b29c39a..9fa60a6def 100644 --- a/src/NSwag.Sample.NET80/Startup.cs +++ b/src/NSwag.Sample.NET80/Startup.cs @@ -1,8 +1,3 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; using NJsonSchema.Generation; using System.Text.Json.Serialization; diff --git a/src/NSwag.Sample.NET80Minimal/NSwag.Sample.NET80Minimal.csproj b/src/NSwag.Sample.NET80Minimal/NSwag.Sample.NET80Minimal.csproj index fda6332495..fc28ef357c 100644 --- a/src/NSwag.Sample.NET80Minimal/NSwag.Sample.NET80Minimal.csproj +++ b/src/NSwag.Sample.NET80Minimal/NSwag.Sample.NET80Minimal.csproj @@ -1,6 +1,7 @@ net8.0 + $(NoWarn);CA1050;ASP0014 diff --git a/src/NSwag.Sample.NET80Minimal/Program.cs b/src/NSwag.Sample.NET80Minimal/Program.cs index c3d03cbad1..5a9ef2d243 100644 --- a/src/NSwag.Sample.NET80Minimal/Program.cs +++ b/src/NSwag.Sample.NET80Minimal/Program.cs @@ -1,8 +1,4 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.DependencyInjection; -using System; var builder = WebApplication.CreateBuilder(args); @@ -22,14 +18,14 @@ app.UseOpenApi(); app.UseSwaggerUi(); -app.MapGet("/", (Func)(() => "Hello World!")) +app.MapGet("/", () => "Hello World!") .WithTags("General"); -app.MapGet("/sum/{a}/{b}", (Func)((a, b) => a + b)) +app.MapGet("/sum/{a}/{b}", (int a, int b) => a + b) .WithName("CalculateSum") .WithTags("Calculator"); -app.MapGet("/abs({a})", (Func)(a => Math.Abs(a))) +app.MapGet("/abs({a})", (int a) => Math.Abs(a)) .WithName("AbsoluteValue") .WithTags("Calculator"); @@ -48,9 +44,9 @@ [Route("examples")] public class ExampleController : ControllerBase { - [HttpGet] - public IActionResult Get() - { - return Ok("Get Method"); - } + [HttpGet] + public IActionResult Get() + { + return Ok("Get Method"); + } } \ No newline at end of file diff --git a/src/NSwag.Sample.NET60/Controllers/ValuesController.cs b/src/NSwag.Sample.NET90/Controllers/ValuesController.cs similarity index 88% rename from src/NSwag.Sample.NET60/Controllers/ValuesController.cs rename to src/NSwag.Sample.NET90/Controllers/ValuesController.cs index 59bfda3282..9ae2613dbb 100644 --- a/src/NSwag.Sample.NET60/Controllers/ValuesController.cs +++ b/src/NSwag.Sample.NET90/Controllers/ValuesController.cs @@ -1,8 +1,6 @@ -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; -namespace NSwag.Sample.NET60.Controllers +namespace NSwag.Sample.NET80.Controllers { [Route("api/[controller]")] [ApiController] @@ -19,7 +17,9 @@ public class Person public DateTime DayOfBirth { get; set; } } +#pragma warning disable CA1711 public enum TestEnum +#pragma warning restore CA1711 { Foo, Bar @@ -28,7 +28,7 @@ public enum TestEnum [HttpGet] public ActionResult> Get() { - return new Person[] { }; + return Array.Empty(); } // GET api/values/5 diff --git a/src/NSwag.Sample.NET60Minimal/NSwag.Sample.NET60Minimal.csproj b/src/NSwag.Sample.NET90/NSwag.Sample.NET90.csproj similarity index 70% rename from src/NSwag.Sample.NET60Minimal/NSwag.Sample.NET60Minimal.csproj rename to src/NSwag.Sample.NET90/NSwag.Sample.NET90.csproj index 38bdd60b5a..f09aba7f8a 100644 --- a/src/NSwag.Sample.NET60Minimal/NSwag.Sample.NET60Minimal.csproj +++ b/src/NSwag.Sample.NET90/NSwag.Sample.NET90.csproj @@ -1,8 +1,12 @@  + - net6.0 + net9.0 + enable + + diff --git a/src/NSwag.Sample.NET60/Program.cs b/src/NSwag.Sample.NET90/Program.cs similarity index 76% rename from src/NSwag.Sample.NET60/Program.cs rename to src/NSwag.Sample.NET90/Program.cs index 0fe6db3c92..063b013ba7 100644 --- a/src/NSwag.Sample.NET60/Program.cs +++ b/src/NSwag.Sample.NET90/Program.cs @@ -1,8 +1,4 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; -using NSwag.Sample.NET60; - -namespace NSwag.Sample.NET60 +namespace NSwag.Sample.NET90 { public class Program { diff --git a/src/NSwag.Sample.NET60/Properties/launchSettings.json b/src/NSwag.Sample.NET90/Properties/launchSettings.json similarity index 92% rename from src/NSwag.Sample.NET60/Properties/launchSettings.json rename to src/NSwag.Sample.NET90/Properties/launchSettings.json index 715b9fe7fc..8ae276e366 100644 --- a/src/NSwag.Sample.NET60/Properties/launchSettings.json +++ b/src/NSwag.Sample.NET90/Properties/launchSettings.json @@ -1,7 +1,7 @@ { "$schema": "http://json.schemastore.org/launchsettings.json", "profiles": { - "NSwag.Sample.NET60": { + "NSwag.Sample.NET90": { "commandName": "Project", "launchBrowser": true, "launchUrl": "swagger", diff --git a/src/NSwag.Sample.NET60/Startup.cs b/src/NSwag.Sample.NET90/Startup.cs similarity index 89% rename from src/NSwag.Sample.NET60/Startup.cs rename to src/NSwag.Sample.NET90/Startup.cs index d7e3dd7c48..582a351fe2 100644 --- a/src/NSwag.Sample.NET60/Startup.cs +++ b/src/NSwag.Sample.NET90/Startup.cs @@ -1,12 +1,7 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; using NJsonSchema.Generation; using System.Text.Json.Serialization; -namespace NSwag.Sample.NET60 +namespace NSwag.Sample.NET90 { public class Startup { diff --git a/src/NSwag.Sample.NET60/appsettings.Development.json b/src/NSwag.Sample.NET90/appsettings.Development.json similarity index 100% rename from src/NSwag.Sample.NET60/appsettings.Development.json rename to src/NSwag.Sample.NET90/appsettings.Development.json diff --git a/src/NSwag.Sample.NET60/appsettings.json b/src/NSwag.Sample.NET90/appsettings.json similarity index 100% rename from src/NSwag.Sample.NET60/appsettings.json rename to src/NSwag.Sample.NET90/appsettings.json diff --git a/src/NSwag.Sample.NET60/nswag.json b/src/NSwag.Sample.NET90/nswag.json similarity index 96% rename from src/NSwag.Sample.NET60/nswag.json rename to src/NSwag.Sample.NET90/nswag.json index 948c460162..d2a7177a91 100644 --- a/src/NSwag.Sample.NET60/nswag.json +++ b/src/NSwag.Sample.NET90/nswag.json @@ -1,9 +1,9 @@ { - "runtime": "Net60", + "runtime": "Net90", "defaultVariables": null, "documentGenerator": { "aspNetCoreToOpenApi": { - "project": "NSwag.Sample.NET60.csproj", + "project": "NSwag.Sample.NET90.csproj", "msBuildProjectExtensionsPath": null, "configuration": null, "runtime": null, diff --git a/src/NSwag.Sample.NET60/openapi.json b/src/NSwag.Sample.NET90/openapi.json similarity index 100% rename from src/NSwag.Sample.NET60/openapi.json rename to src/NSwag.Sample.NET90/openapi.json diff --git a/src/NSwag.Sample.NET90Minimal/NSwag.Sample.NET90Minimal.csproj b/src/NSwag.Sample.NET90Minimal/NSwag.Sample.NET90Minimal.csproj new file mode 100644 index 0000000000..25fed2272e --- /dev/null +++ b/src/NSwag.Sample.NET90Minimal/NSwag.Sample.NET90Minimal.csproj @@ -0,0 +1,9 @@ + + + net9.0 + $(NoWarn);CA1050;ASP0014 + + + + + diff --git a/src/NSwag.Sample.NET60Minimal/Program.cs b/src/NSwag.Sample.NET90Minimal/Program.cs similarity index 76% rename from src/NSwag.Sample.NET60Minimal/Program.cs rename to src/NSwag.Sample.NET90Minimal/Program.cs index 5e1b3882aa..acd42cc296 100644 --- a/src/NSwag.Sample.NET60Minimal/Program.cs +++ b/src/NSwag.Sample.NET90Minimal/Program.cs @@ -1,8 +1,4 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.DependencyInjection; -using System; var builder = WebApplication.CreateBuilder(args); @@ -33,16 +29,13 @@ .WithName("AbsoluteValue") .WithTags("Calculator"); -app.MapGet("/id:{id}", (int id) =>id) +app.MapGet("/id:{id}", (int id) => id) .WithName("Identity") .WithTags("Calculator"); // Optional: Use controllers app.UseRouting(); -app.UseEndpoints(x => -{ - x.MapControllers(); -}); +app.UseEndpoints(x => { x.MapControllers(); }); app.Run(); @@ -51,9 +44,9 @@ [Route("examples")] public class ExampleController : ControllerBase { - [HttpGet] - public IActionResult Get() - { - return Ok("Get Method"); - } + [HttpGet] + public IActionResult Get() + { + return Ok("Get Method"); + } } \ No newline at end of file diff --git a/src/NSwag.Sample.NET60Minimal/Properties/launchSettings.json b/src/NSwag.Sample.NET90Minimal/Properties/launchSettings.json similarity index 90% rename from src/NSwag.Sample.NET60Minimal/Properties/launchSettings.json rename to src/NSwag.Sample.NET90Minimal/Properties/launchSettings.json index 6aa10cff13..5ca81b5de1 100644 --- a/src/NSwag.Sample.NET60Minimal/Properties/launchSettings.json +++ b/src/NSwag.Sample.NET90Minimal/Properties/launchSettings.json @@ -1,7 +1,7 @@ { "$schema": "http://json.schemastore.org/launchsettings.json", "profiles": { - "NSwag.Sample.NET60Minimal": { + "NSwag.Sample.NET90Minimal": { "commandName": "Project", "launchBrowser": true, "launchUrl": "swagger", diff --git a/src/NSwag.Sample.NET90Minimal/nswag.json b/src/NSwag.Sample.NET90Minimal/nswag.json new file mode 100644 index 0000000000..720f576a37 --- /dev/null +++ b/src/NSwag.Sample.NET90Minimal/nswag.json @@ -0,0 +1,231 @@ +{ + "runtime": "Net90", + "defaultVariables": null, + "documentGenerator": { + "aspNetCoreToOpenApi": { + "project": "NSwag.Sample.NET90Minimal.csproj", + "documentName": "v1", + "msBuildProjectExtensionsPath": null, + "configuration": null, + "runtime": null, + "targetFramework": null, + "noBuild": false, + "msBuildOutputPath": null, + "verbose": true, + "workingDirectory": null, + "aspNetCoreEnvironment": null, + "output": "openapi.json", + "newLineBehavior": "Auto" + } + }, + "codeGenerators": { + "openApiToTypeScriptClient": { + "className": "{controller}Client", + "moduleName": "", + "namespace": "", + "typeScriptVersion": 2.7, + "template": "Fetch", + "promiseType": "Promise", + "httpClass": "HttpClient", + "withCredentials": false, + "useSingletonProvider": false, + "injectionTokenType": "OpaqueToken", + "rxJsVersion": 6.0, + "dateTimeType": "Date", + "nullValue": "Undefined", + "generateClientClasses": true, + "generateClientInterfaces": false, + "generateOptionalParameters": false, + "exportTypes": true, + "wrapDtoExceptions": false, + "exceptionClass": "ApiException", + "clientBaseClass": null, + "wrapResponses": false, + "wrapResponseMethods": [], + "generateResponseClasses": true, + "responseClass": "SwaggerResponse", + "protectedMethods": [], + "configurationClass": null, + "useTransformOptionsMethod": false, + "useTransformResultMethod": false, + "generateDtoTypes": true, + "operationGenerationMode": "MultipleClientsFromOperationId", + "markOptionalProperties": true, + "generateCloneMethod": false, + "typeStyle": "Class", + "enumStyle": "Enum", + "useLeafType": false, + "classTypes": [], + "extendedClasses": [], + "extensionCode": null, + "generateDefaultValues": true, + "excludedTypeNames": [], + "excludedParameterNames": [], + "handleReferences": false, + "generateTypeCheckFunctions": false, + "generateConstructorInterface": true, + "convertConstructorInterfaceData": false, + "importRequiredTypes": true, + "useGetBaseUrlMethod": false, + "baseUrlTokenName": "API_BASE_URL", + "queryNullValue": "", + "useAbortSignal": false, + "inlineNamedDictionaries": false, + "inlineNamedAny": false, + "includeHttpContext": false, + "templateDirectory": null, + "serviceHost": null, + "serviceSchemes": null, + "output": "GeneratedClientsTs.gen", + "newLineBehavior": "Auto" + }, + "openApiToCSharpClient": { + "clientBaseClass": null, + "configurationClass": null, + "generateClientClasses": true, + "suppressClientClassesOutput": false, + "generateClientInterfaces": false, + "suppressClientInterfacesOutput": false, + "clientBaseInterface": null, + "injectHttpClient": true, + "disposeHttpClient": true, + "protectedMethods": [], + "generateExceptionClasses": true, + "exceptionClass": "ApiException", + "wrapDtoExceptions": true, + "useHttpClientCreationMethod": false, + "httpClientType": "System.Net.Http.HttpClient", + "useHttpRequestMessageCreationMethod": false, + "useBaseUrl": true, + "generateBaseUrlProperty": true, + "generateSyncMethods": false, + "generatePrepareRequestAndProcessResponseAsAsyncMethods": false, + "exposeJsonSerializerSettings": false, + "clientClassAccessModifier": "public", + "typeAccessModifier": "public", + "propertySetterAccessModifier": "", + "generateNativeRecords": false, + "generateContractsOutput": false, + "contractsNamespace": null, + "contractsOutputFilePath": null, + "parameterDateTimeFormat": "s", + "parameterDateFormat": "yyyy-MM-dd", + "generateUpdateJsonSerializerSettingsMethod": true, + "useRequestAndResponseSerializationSettings": false, + "serializeTypeInformation": false, + "queryNullValue": "", + "className": "{controller}Client", + "operationGenerationMode": "MultipleClientsFromOperationId", + "additionalNamespaceUsages": [], + "additionalContractNamespaceUsages": [], + "generateOptionalParameters": false, + "generateJsonMethods": false, + "enforceFlagEnums": false, + "parameterArrayType": "System.Collections.Generic.IEnumerable", + "parameterDictionaryType": "System.Collections.Generic.IDictionary", + "responseArrayType": "System.Collections.Generic.ICollection", + "responseDictionaryType": "System.Collections.Generic.IDictionary", + "wrapResponses": false, + "wrapResponseMethods": [], + "generateResponseClasses": true, + "responseClass": "SwaggerResponse", + "namespace": "MyNamespace", + "requiredPropertiesMustBeDefined": true, + "dateType": "System.DateTimeOffset", + "jsonConverters": null, + "anyType": "object", + "dateTimeType": "System.DateTimeOffset", + "timeType": "System.TimeSpan", + "timeSpanType": "System.TimeSpan", + "arrayType": "System.Collections.Generic.ICollection", + "arrayInstanceType": "System.Collections.ObjectModel.Collection", + "dictionaryType": "System.Collections.Generic.IDictionary", + "dictionaryInstanceType": "System.Collections.Generic.Dictionary", + "arrayBaseType": "System.Collections.ObjectModel.Collection", + "dictionaryBaseType": "System.Collections.Generic.Dictionary", + "classStyle": "Poco", + "jsonLibrary": "NewtonsoftJson", + "generateDefaultValues": true, + "generateDataAnnotations": true, + "excludedTypeNames": [], + "excludedParameterNames": [], + "handleReferences": false, + "generateImmutableArrayProperties": false, + "generateImmutableDictionaryProperties": false, + "jsonSerializerSettingsTransformationMethod": null, + "inlineNamedArrays": false, + "inlineNamedDictionaries": false, + "inlineNamedTuples": true, + "inlineNamedAny": false, + "generateDtoTypes": true, + "generateOptionalPropertiesAsNullable": false, + "generateNullableReferenceTypes": false, + "templateDirectory": null, + "serviceHost": null, + "serviceSchemes": null, + "output": "GeneratedClientsCs.gen", + "newLineBehavior": "Auto" + }, + "openApiToCSharpController": { + "controllerBaseClass": null, + "controllerStyle": "Partial", + "controllerTarget": "AspNetCore", + "useCancellationToken": false, + "useActionResultType": false, + "generateModelValidationAttributes": false, + "routeNamingStrategy": "None", + "basePath": null, + "className": "{controller}", + "operationGenerationMode": "MultipleClientsFromOperationId", + "additionalNamespaceUsages": [], + "additionalContractNamespaceUsages": [], + "generateOptionalParameters": false, + "generateJsonMethods": false, + "enforceFlagEnums": false, + "parameterArrayType": "System.Collections.Generic.IEnumerable", + "parameterDictionaryType": "System.Collections.Generic.IDictionary", + "responseArrayType": "System.Collections.Generic.ICollection", + "responseDictionaryType": "System.Collections.Generic.IDictionary", + "wrapResponses": false, + "wrapResponseMethods": [], + "generateResponseClasses": true, + "responseClass": "SwaggerResponse", + "namespace": "MyNamespace", + "requiredPropertiesMustBeDefined": true, + "dateType": "System.DateTimeOffset", + "jsonConverters": null, + "anyType": "object", + "dateTimeType": "System.DateTimeOffset", + "timeType": "System.TimeSpan", + "timeSpanType": "System.TimeSpan", + "arrayType": "System.Collections.Generic.List", + "arrayInstanceType": "System.Collections.Generic.List", + "dictionaryType": "System.Collections.Generic.IDictionary", + "dictionaryInstanceType": "System.Collections.Generic.Dictionary", + "arrayBaseType": "System.Collections.ObjectModel.Collection", + "dictionaryBaseType": "System.Collections.Generic.Dictionary", + "classStyle": "Poco", + "jsonLibrary": "NewtonsoftJson", + "generateDefaultValues": true, + "generateDataAnnotations": true, + "excludedTypeNames": [], + "excludedParameterNames": [], + "handleReferences": false, + "generateImmutableArrayProperties": false, + "generateImmutableDictionaryProperties": false, + "jsonSerializerSettingsTransformationMethod": null, + "inlineNamedArrays": false, + "inlineNamedDictionaries": false, + "inlineNamedTuples": true, + "inlineNamedAny": false, + "generateDtoTypes": true, + "generateOptionalPropertiesAsNullable": false, + "generateNullableReferenceTypes": false, + "templateDirectory": null, + "serviceHost": null, + "serviceSchemes": null, + "output": "GeneratedControllersCs.gen", + "newLineBehavior": "Auto" + } + } +} \ No newline at end of file diff --git a/src/NSwag.Sample.NET60Minimal/openapi.json b/src/NSwag.Sample.NET90Minimal/openapi.json similarity index 100% rename from src/NSwag.Sample.NET60Minimal/openapi.json rename to src/NSwag.Sample.NET90Minimal/openapi.json diff --git a/src/NSwag.sln b/src/NSwag.sln index bc33f5f241..254f7791fd 100644 --- a/src/NSwag.sln +++ b/src/NSwag.sln @@ -117,16 +117,16 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "00 Build", "00 Build", "{6F EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "_build", "..\build\_build.csproj", "{AC3D8125-AE21-49FC-A217-D96C7B585FF9}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NSwag.Sample.NET60", "NSwag.Sample.NET60\NSwag.Sample.NET60.csproj", "{DE82965A-6935-43E0-A9A1-F3F35B4487EB}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NSwag.Sample.NET60Minimal", "NSwag.Sample.NET60Minimal\NSwag.Sample.NET60Minimal.csproj", "{24693FBC-445E-4360-A1E8-B6F136C563FB}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NSwag.ConsoleCore.Tests", "NSwag.ConsoleCore.Tests\NSwag.ConsoleCore.Tests.csproj", "{CF6112E5-20FD-4B22-A6C0-20AF6B3396F3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NSwag.Sample.NET80", "NSwag.Sample.NET80\NSwag.Sample.NET80.csproj", "{2A166077-2189-4376-A38B-8E362A319028}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NSwag.Sample.NET80Minimal", "NSwag.Sample.NET80Minimal\NSwag.Sample.NET80Minimal.csproj", "{F0569608-BD55-4316-94F0-E85A14D7FE14}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NSwag.Sample.NET90", "NSwag.Sample.NET90\NSwag.Sample.NET90.csproj", "{DE82965A-6935-43E0-A9A1-F3F35B4487EB}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NSwag.Sample.NET90Minimal", "NSwag.Sample.NET90Minimal\NSwag.Sample.NET90Minimal.csproj", "{24693FBC-445E-4360-A1E8-B6F136C563FB}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/src/NSwagStudio/Controls/AvalonEditBehavior.cs b/src/NSwagStudio/Controls/AvalonEditBehavior.cs index 5eb54b7d73..a79567e35e 100644 --- a/src/NSwagStudio/Controls/AvalonEditBehavior.cs +++ b/src/NSwagStudio/Controls/AvalonEditBehavior.cs @@ -1,4 +1,3 @@ -using System; using System.Windows; using System.Windows.Interactivity; using ICSharpCode.AvalonEdit; @@ -13,8 +12,8 @@ public sealed class AvalonEditBehavior : Behavior public string Text { - get { return (string)GetValue(TextProperty); } - set { SetValue(TextProperty, value); } + get => (string)GetValue(TextProperty); + set => SetValue(TextProperty, value); } protected override void OnAttached() diff --git a/src/NSwagStudio/Controls/TabContent.cs b/src/NSwagStudio/Controls/TabContent.cs index cc0033224a..f6f0bc140d 100644 --- a/src/NSwagStudio/Controls/TabContent.cs +++ b/src/NSwagStudio/Controls/TabContent.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; diff --git a/src/NSwagStudio/Converters/IsValueToVisibilityConverter.cs b/src/NSwagStudio/Converters/IsValueToVisibilityConverter.cs index 86545e3864..fdbd3126cf 100644 --- a/src/NSwagStudio/Converters/IsValueToVisibilityConverter.cs +++ b/src/NSwagStudio/Converters/IsValueToVisibilityConverter.cs @@ -1,5 +1,4 @@ -using System; -using System.Globalization; +using System.Globalization; using System.Windows; using System.Windows.Data; using System.Windows.Markup; diff --git a/src/NSwagStudio/Converters/NumberAdditionConverter.cs b/src/NSwagStudio/Converters/NumberAdditionConverter.cs index 002bd57ca4..1d76bad520 100644 --- a/src/NSwagStudio/Converters/NumberAdditionConverter.cs +++ b/src/NSwagStudio/Converters/NumberAdditionConverter.cs @@ -1,5 +1,4 @@ -using System; -using System.Globalization; +using System.Globalization; using System.Windows.Data; namespace NSwagStudio.Converters diff --git a/src/NSwagStudio/Converters/StringArrayConverter.cs b/src/NSwagStudio/Converters/StringArrayConverter.cs index f42f71124b..0a921b9c0b 100644 --- a/src/NSwagStudio/Converters/StringArrayConverter.cs +++ b/src/NSwagStudio/Converters/StringArrayConverter.cs @@ -1,6 +1,4 @@ -using System; -using System.Globalization; -using System.Linq; +using System.Globalization; using System.Windows.Data; namespace NSwagStudio.Converters diff --git a/src/NSwagStudio/ISwaggerGeneratorView.cs b/src/NSwagStudio/ISwaggerGeneratorView.cs index cb2998bc8f..8ee8472700 100644 --- a/src/NSwagStudio/ISwaggerGeneratorView.cs +++ b/src/NSwagStudio/ISwaggerGeneratorView.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Threading.Tasks; using NSwag.Commands; namespace NSwagStudio diff --git a/src/NSwagStudio/NSwagStudio.csproj b/src/NSwagStudio/NSwagStudio.csproj index c62eb8d5f7..e28118b3cf 100644 --- a/src/NSwagStudio/NSwagStudio.csproj +++ b/src/NSwagStudio/NSwagStudio.csproj @@ -13,6 +13,7 @@ ApplicationIcon.ico false $(NoWarn);CS0618 + none @@ -61,7 +62,7 @@ - + diff --git a/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerOutputViewModel.cs b/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerOutputViewModel.cs index 463409732f..d0a60cad3d 100644 --- a/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerOutputViewModel.cs +++ b/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerOutputViewModel.cs @@ -6,7 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System.Threading.Tasks; using NSwag; namespace NSwagStudio.ViewModels.CodeGenerators @@ -26,8 +25,8 @@ public async Task GenerateClientAsync(OpenApiDocument document, string documentP /// Gets or sets the Swagger code. public string SwaggerCode { - get { return _swaggerCode; } - set { Set(ref _swaggerCode, value); } + get => _swaggerCode; + set => Set(ref _swaggerCode, value); } } } diff --git a/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToCSharpClientGeneratorViewModel.cs b/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToCSharpClientGeneratorViewModel.cs index 2c47873080..f8b624aef7 100644 --- a/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToCSharpClientGeneratorViewModel.cs +++ b/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToCSharpClientGeneratorViewModel.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Linq; using NJsonSchema.CodeGeneration.CSharp; using NSwag.Commands; using NSwag.Commands.CodeGeneration; @@ -22,7 +20,7 @@ public class SwaggerToCSharpClientGeneratorViewModel : ViewModelBase /// Gets the settings. public OpenApiToCSharpClientCommand Command { - get { return _command; } + get => _command; set { if (Set(ref _command, value)) @@ -53,8 +51,8 @@ public OpenApiToCSharpClientCommand Command /// Gets or sets the client code. public string ClientCode { - get { return _clientCode; } - set { Set(ref _clientCode, value); } + get => _clientCode; + set => Set(ref _clientCode, value); } } } diff --git a/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToCSharpControllerGeneratorViewModel.cs b/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToCSharpControllerGeneratorViewModel.cs index 7922e5b787..e149fbb82b 100644 --- a/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToCSharpControllerGeneratorViewModel.cs +++ b/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToCSharpControllerGeneratorViewModel.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Linq; using NJsonSchema.CodeGeneration.CSharp; using NSwag.CodeGeneration.CSharp.Models; using NSwag.Commands; @@ -23,7 +21,7 @@ public class SwaggerToCSharpControllerGeneratorViewModel : ViewModelBase /// Gets the settings. public OpenApiToCSharpControllerCommand Command { - get { return _command; } + get => _command; set { if (Set(ref _command, value)) @@ -64,8 +62,8 @@ public OpenApiToCSharpControllerCommand Command /// Gets or sets the client code. public string ClientCode { - get { return _clientCode; } - set { Set(ref _clientCode, value); } + get => _clientCode; + set => Set(ref _clientCode, value); } } } diff --git a/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToTypeScriptClientGeneratorViewModel.cs b/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToTypeScriptClientGeneratorViewModel.cs index 70a90c40eb..03419a3a9c 100644 --- a/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToTypeScriptClientGeneratorViewModel.cs +++ b/src/NSwagStudio/ViewModels/CodeGenerators/SwaggerToTypeScriptClientGeneratorViewModel.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Linq; using NJsonSchema.CodeGeneration.TypeScript; using NSwag.CodeGeneration.TypeScript; using NSwag.Commands; @@ -23,7 +21,7 @@ public class SwaggerToTypeScriptClientGeneratorViewModel : ViewModelBase /// Gets the settings. public OpenApiToTypeScriptClientCommand Command { - get { return _command; } + get => _command; set { if (Set(ref _command, value)) @@ -89,8 +87,8 @@ public OpenApiToTypeScriptClientCommand Command /// Gets or sets the client code. public string ClientCode { - get { return _clientCode; } - set { Set(ref _clientCode, value); } + get => _clientCode; + set => Set(ref _clientCode, value); } } } diff --git a/src/NSwagStudio/ViewModels/DocumentModel.cs b/src/NSwagStudio/ViewModels/DocumentModel.cs index caaca02933..b00fc808d1 100644 --- a/src/NSwagStudio/ViewModels/DocumentModel.cs +++ b/src/NSwagStudio/ViewModels/DocumentModel.cs @@ -1,9 +1,6 @@ -using System.Collections.Generic; using System.ComponentModel; -using System.Linq; using MyToolkit.Model; using NSwag.Commands; -using NSwag.Commands.Generation; using NSwagStudio.Views.CodeGenerators; using NSwagStudio.Views.SwaggerGenerators; diff --git a/src/NSwagStudio/ViewModels/DocumentViewModel.cs b/src/NSwagStudio/ViewModels/DocumentViewModel.cs index 39dfc4f69a..a3de6ef004 100644 --- a/src/NSwagStudio/ViewModels/DocumentViewModel.cs +++ b/src/NSwagStudio/ViewModels/DocumentViewModel.cs @@ -1,7 +1,4 @@ -using System; using System.Diagnostics; -using System.Linq; -using System.Threading.Tasks; using System.Windows; using MyToolkit.Command; using MyToolkit.Utilities; @@ -27,8 +24,8 @@ public DocumentViewModel() /// Gets or sets the settings. public DocumentModel Document { - get { return _document; } - set { Set(ref _document, value); } + get => _document; + set => Set(ref _document, value); } /// Gets the application version with build time. diff --git a/src/NSwagStudio/ViewModels/MainWindowModel.cs b/src/NSwagStudio/ViewModels/MainWindowModel.cs index b28047bbdb..dc68d58823 100644 --- a/src/NSwagStudio/ViewModels/MainWindowModel.cs +++ b/src/NSwagStudio/ViewModels/MainWindowModel.cs @@ -8,8 +8,6 @@ using System.Collections.ObjectModel; using System.IO; -using System.Linq; -using System.Threading.Tasks; using System.Windows.Forms; using MyToolkit.Command; using MyToolkit.Storage; @@ -50,7 +48,7 @@ public MainWindowModel() /// Gets or sets the selected document. public DocumentModel SelectedDocument { - get { return _selectedDocument; } + get => _selectedDocument; set { if (Set(ref _selectedDocument, value)) diff --git a/src/NSwagStudio/ViewModels/SwaggerGenerators/AspNetCoreToSwaggerGeneratorViewModel.cs b/src/NSwagStudio/ViewModels/SwaggerGenerators/AspNetCoreToSwaggerGeneratorViewModel.cs index eb25ad04f2..b1df1952af 100644 --- a/src/NSwagStudio/ViewModels/SwaggerGenerators/AspNetCoreToSwaggerGeneratorViewModel.cs +++ b/src/NSwagStudio/ViewModels/SwaggerGenerators/AspNetCoreToSwaggerGeneratorViewModel.cs @@ -6,10 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.Win32; using NJsonSchema; using NJsonSchema.Generation; using NSwag; @@ -39,7 +35,7 @@ public class AspNetCoreToSwaggerGeneratorViewModel : ViewModelBase /// Gets or sets the generator settings. public AspNetCoreToOpenApiCommand Command { - get { return _command; } + get => _command; set { if (Set(ref _command, value)) @@ -50,8 +46,8 @@ public AspNetCoreToOpenApiCommand Command /// Gets or sets the document. public NSwagDocument Document { - get { return _document; } - set { Set(ref _document, value); } + get => _document; + set => Set(ref _document, value); } public async Task GenerateSwaggerAsync() diff --git a/src/NSwagStudio/ViewModels/SwaggerGenerators/SwaggerInputViewModel.cs b/src/NSwagStudio/ViewModels/SwaggerGenerators/SwaggerInputViewModel.cs index c7b3aef600..adedee584e 100644 --- a/src/NSwagStudio/ViewModels/SwaggerGenerators/SwaggerInputViewModel.cs +++ b/src/NSwagStudio/ViewModels/SwaggerGenerators/SwaggerInputViewModel.cs @@ -1,7 +1,4 @@ -using System; using System.IO; -using System.Threading; -using System.Threading.Tasks; using System.Windows.Input; using MyToolkit.Command; using Newtonsoft.Json; diff --git a/src/NSwagStudio/ViewModels/ViewModelBase.cs b/src/NSwagStudio/ViewModels/ViewModelBase.cs index 683bc772f5..cf9228ce36 100644 --- a/src/NSwagStudio/ViewModels/ViewModelBase.cs +++ b/src/NSwagStudio/ViewModels/ViewModelBase.cs @@ -6,8 +6,6 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -using System; -using System.Linq; using System.Windows; using MyToolkit.Dialogs; diff --git a/src/NSwagStudio/Views/CodeGenerators/SwaggerOutputView.xaml.cs b/src/NSwagStudio/Views/CodeGenerators/SwaggerOutputView.xaml.cs index 6bdb592c48..151a9a9c7a 100644 --- a/src/NSwagStudio/Views/CodeGenerators/SwaggerOutputView.xaml.cs +++ b/src/NSwagStudio/Views/CodeGenerators/SwaggerOutputView.xaml.cs @@ -21,7 +21,7 @@ public override void UpdateOutput(OpenApiDocumentExecutionResult result) public override bool IsSelected { - get { return true; } + get => true; set { } } diff --git a/src/NSwagStudio/Views/CodeGenerators/SwaggerToCSharpClientGeneratorView.xaml.cs b/src/NSwagStudio/Views/CodeGenerators/SwaggerToCSharpClientGeneratorView.xaml.cs index cda8d7b608..7e90d2a155 100644 --- a/src/NSwagStudio/Views/CodeGenerators/SwaggerToCSharpClientGeneratorView.xaml.cs +++ b/src/NSwagStudio/Views/CodeGenerators/SwaggerToCSharpClientGeneratorView.xaml.cs @@ -31,7 +31,7 @@ public override void UpdateOutput(OpenApiDocumentExecutionResult result) public override bool IsSelected { - get { return _document.CodeGenerators.OpenApiToCSharpClientCommand != null; } + get => _document.CodeGenerators.OpenApiToCSharpClientCommand != null; set { if (value != IsSelected) diff --git a/src/NSwagStudio/Views/CodeGenerators/SwaggerToCSharpControllerGeneratorView.xaml.cs b/src/NSwagStudio/Views/CodeGenerators/SwaggerToCSharpControllerGeneratorView.xaml.cs index a53d4c7a02..2e48d82ce6 100644 --- a/src/NSwagStudio/Views/CodeGenerators/SwaggerToCSharpControllerGeneratorView.xaml.cs +++ b/src/NSwagStudio/Views/CodeGenerators/SwaggerToCSharpControllerGeneratorView.xaml.cs @@ -31,7 +31,7 @@ public override void UpdateOutput(OpenApiDocumentExecutionResult result) public override bool IsSelected { - get { return _document.CodeGenerators.OpenApiToCSharpControllerCommand != null; } + get => _document.CodeGenerators.OpenApiToCSharpControllerCommand != null; set { if (value != IsSelected) diff --git a/src/NSwagStudio/Views/CodeGenerators/SwaggerToTypeScriptClientGeneratorView.xaml.cs b/src/NSwagStudio/Views/CodeGenerators/SwaggerToTypeScriptClientGeneratorView.xaml.cs index ec4a310bae..d12ae5abea 100644 --- a/src/NSwagStudio/Views/CodeGenerators/SwaggerToTypeScriptClientGeneratorView.xaml.cs +++ b/src/NSwagStudio/Views/CodeGenerators/SwaggerToTypeScriptClientGeneratorView.xaml.cs @@ -31,7 +31,7 @@ public override void UpdateOutput(OpenApiDocumentExecutionResult result) public override bool IsSelected { - get { return _document.CodeGenerators.OpenApiToTypeScriptClientCommand != null; } + get => _document.CodeGenerators.OpenApiToTypeScriptClientCommand != null; set { if (value != IsSelected) diff --git a/src/NSwagStudio/Views/DocumentView.xaml.cs b/src/NSwagStudio/Views/DocumentView.xaml.cs index 42ecd60f28..4c4fb61b71 100644 --- a/src/NSwagStudio/Views/DocumentView.xaml.cs +++ b/src/NSwagStudio/Views/DocumentView.xaml.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; +using System.ComponentModel; using System.Windows; using System.Windows.Controls; using MyToolkit.Mvvm; @@ -68,8 +65,8 @@ private void UpdateCodeGeneratorTabs() public DocumentModel Document { - get { return (DocumentModel)GetValue(DocumentProperty); } - set { SetValue(DocumentProperty, value); } + get => (DocumentModel)GetValue(DocumentProperty); + set => SetValue(DocumentProperty, value); } private void OnGenerate(object sender, RoutedEventArgs e) diff --git a/src/NSwagStudio/Views/MainWindow.xaml.cs b/src/NSwagStudio/Views/MainWindow.xaml.cs index 1a5e274bfc..9654e8dee9 100644 --- a/src/NSwagStudio/Views/MainWindow.xaml.cs +++ b/src/NSwagStudio/Views/MainWindow.xaml.cs @@ -1,7 +1,5 @@ -using System; -using System.ComponentModel; +using System.ComponentModel; using System.Diagnostics; -using System.Linq; using System.Windows; using System.Windows.Documents; using System.Windows.Input; diff --git a/src/NSwagStudio/Views/SwaggerGenerators/AspNetCoreToSwaggerGeneratorView.xaml.cs b/src/NSwagStudio/Views/SwaggerGenerators/AspNetCoreToSwaggerGeneratorView.xaml.cs index 66e7ab9cda..95a4a6b027 100644 --- a/src/NSwagStudio/Views/SwaggerGenerators/AspNetCoreToSwaggerGeneratorView.xaml.cs +++ b/src/NSwagStudio/Views/SwaggerGenerators/AspNetCoreToSwaggerGeneratorView.xaml.cs @@ -1,7 +1,4 @@ -using System.Linq; -using System.Threading.Tasks; -using System.Windows.Controls; -using MyToolkit.Mvvm; +using MyToolkit.Mvvm; using NSwag.Commands; using NSwag.Commands.Generation.AspNetCore; using NSwagStudio.ViewModels.SwaggerGenerators; diff --git a/src/NSwagStudio/Views/SwaggerGenerators/JsonSchemaInputView.xaml.cs b/src/NSwagStudio/Views/SwaggerGenerators/JsonSchemaInputView.xaml.cs index fca17d1709..0b596e182c 100644 --- a/src/NSwagStudio/Views/SwaggerGenerators/JsonSchemaInputView.xaml.cs +++ b/src/NSwagStudio/Views/SwaggerGenerators/JsonSchemaInputView.xaml.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using System.Windows; +using System.Windows; using NSwag.Commands; using NSwag.Commands.CodeGeneration; diff --git a/src/NSwagStudio/Views/SwaggerGenerators/SwaggerInputView.xaml.cs b/src/NSwagStudio/Views/SwaggerGenerators/SwaggerInputView.xaml.cs index f75ed05f36..3b017f50ef 100644 --- a/src/NSwagStudio/Views/SwaggerGenerators/SwaggerInputView.xaml.cs +++ b/src/NSwagStudio/Views/SwaggerGenerators/SwaggerInputView.xaml.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using NSwag.Commands; +using NSwag.Commands; using NSwag.Commands.Generation; using NSwagStudio.ViewModels.SwaggerGenerators; diff --git a/src/NSwagStudio/nswag.cmd b/src/NSwagStudio/nswag.cmd index ed4321a24c..a102b33d2a 100644 --- a/src/NSwagStudio/nswag.cmd +++ b/src/NSwagStudio/nswag.cmd @@ -6,13 +6,13 @@ IF NOT "%args:/runtime:winx86=%" == "%args%" ( GOTO end ) -IF NOT "%args:/runtime:net60=%" == "%args%" ( - dotnet "%~dp0/Net60/dotnet-nswag.dll" %* +IF NOT "%args:/runtime:net80=%" == "%args%" ( + dotnet "%~dp0/Net80/dotnet-nswag.dll" %* GOTO end ) -IF NOT "%args:/runtime:net80=%" == "%args%" ( - dotnet "%~dp0/Net80/dotnet-nswag.dll" %* +IF NOT "%args:/runtime:net90=%" == "%args%" ( + dotnet "%~dp0/Net90/dotnet-nswag.dll" %* GOTO end )