From 9ce0218a6362fcadd32a6f7df856f3d46f076b10 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Fri, 22 Nov 2024 20:29:09 +0200 Subject: [PATCH] Simplify collection initialization (#5044) --- Directory.Build.props | 5 +- .../OpenApiBodyParameterAttribute.cs | 2 +- src/NSwag.AspNet.Owin/SwaggerExtensions.cs | 6 +-- src/NSwag.AspNetCore.Launcher/Program.cs | 2 +- .../CSharpGeneratorBaseSettings.cs | 7 ++- .../Models/CSharpFileTemplateModel.cs | 4 +- .../Models/CSharpOperationModel.cs | 23 +++++---- .../CodeGenerationTests.cs | 6 +-- .../Models/TypeScriptFileTemplateModel.cs | 2 +- .../Models/TypeScriptOperationModel.cs | 7 +-- .../TypeScriptClientGenerator.cs | 4 +- .../TypeScriptClientGeneratorSettings.cs | 7 ++- .../ClientGeneratorBase.cs | 49 +++++++++++-------- ...tsFromOperationIdOperationNameGenerator.cs | 4 +- .../OpenApiToCSharpClientCommand.cs | 2 +- .../Generation/AspNetCore/ProjectMetadata.cs | 6 +-- src/NSwag.Commands/HostApplication.cs | 12 ++--- src/NSwag.Commands/HostFactoryResolver.cs | 8 +-- src/NSwag.Commands/NSwagCommandProcessor.cs | 4 +- .../OpenApiGeneratorCollection.cs | 6 +-- src/NSwag.Commands/PathUtilities.cs | 2 +- .../Parameters/EmptyPathController.cs | 2 +- .../Startup.cs | 6 +-- .../ApiVersionProcessorWithAspNetCoreTests.cs | 10 ++-- .../Processors/OperationParameterProcessor.cs | 8 +-- .../WebApiOpenApiDocumentGenerator.cs | 8 +-- .../OperationResponseProcessorBase.cs | 2 +- 27 files changed, 102 insertions(+), 102 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index f2e3db0aa2..1dd5c95b90 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -78,9 +78,6 @@ [IDE0260] Use pattern matching [IDE0270] Null check can be simplified [IDE0290] Use primary constructor - [IDE0300] Collection initialization can be simplified - [IDE0301] Collection initialization can be simplified - [IDE0305] Collection initialization can be simplified [IDE0330] Use 'System.Threading.Lock' [CA1200] Avoid using cref tags with a prefix [CA1304] The behavior of 'string.ToUpper()' could vary based on the current user's locale settings @@ -108,7 +105,7 @@ [SYSLIB0012] 'Assembly.CodeBase' is obsolete --> - $(NoWarn);IDE0005;IDE0008;IDE0011;IDE0017;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0061;IDE0074;IDE0078;IDE0083;IDE0090;IDE0130;IDE0160;IDE0200;IDE0260;IDE0270;IDE0290;IDE0300;IDE0305;IDE0301;IDE0330 + $(NoWarn);IDE0005;IDE0008;IDE0011;IDE0017;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0061;IDE0074;IDE0078;IDE0083;IDE0090;IDE0130;IDE0160;IDE0200;IDE0260;IDE0270;IDE0290;IDE0330 $(NoWarn);CA1200;CA1304;CA1305;CA1310;CA1311;CA1507;CA1510;CA1514;CA1710;CA1716;CA1720;CA1725;CA1805;CA1834;CA1845;CA1847;CA1861;CA1862;CA1865;CA1866;CA1870;CA2249;CA2263;SYSLIB0012 diff --git a/src/NSwag.Annotations/OpenApiBodyParameterAttribute.cs b/src/NSwag.Annotations/OpenApiBodyParameterAttribute.cs index a2029136aa..1e442b00cf 100644 --- a/src/NSwag.Annotations/OpenApiBodyParameterAttribute.cs +++ b/src/NSwag.Annotations/OpenApiBodyParameterAttribute.cs @@ -15,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.AspNet.Owin/SwaggerExtensions.cs b/src/NSwag.AspNet.Owin/SwaggerExtensions.cs index 6bdf6a95ba..592b0ebb73 100644 --- a/src/NSwag.AspNet.Owin/SwaggerExtensions.cs +++ b/src/NSwag.AspNet.Owin/SwaggerExtensions.cs @@ -32,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. @@ -81,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. @@ -152,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.AspNetCore.Launcher/Program.cs b/src/NSwag.AspNetCore.Launcher/Program.cs index fde8a9ad5f..79996c20d7 100644 --- a/src/NSwag.AspNetCore.Launcher/Program.cs +++ b/src/NSwag.AspNetCore.Launcher/Program.cs @@ -129,7 +129,7 @@ private static int Main(string[] args) try { - method.Invoke(null, new[] { commandContent, outputFile, applicationName }); + method.Invoke(null, [commandContent, outputFile, applicationName]); } catch (Exception ex) { diff --git a/src/NSwag.CodeGeneration.CSharp/CSharpGeneratorBaseSettings.cs b/src/NSwag.CodeGeneration.CSharp/CSharpGeneratorBaseSettings.cs index 899dbb8faa..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"; diff --git a/src/NSwag.CodeGeneration.CSharp/Models/CSharpFileTemplateModel.cs b/src/NSwag.CodeGeneration.CSharp/Models/CSharpFileTemplateModel.cs index d7bb555afd..04e51e9db0 100644 --- a/src/NSwag.CodeGeneration.CSharp/Models/CSharpFileTemplateModel.cs +++ b/src/NSwag.CodeGeneration.CSharp/Models/CSharpFileTemplateModel.cs @@ -128,7 +128,7 @@ public IEnumerable ResponseClassNames .Distinct(); } - return new[] { _settings.ResponseClass.Replace("{controller}", string.Empty) }; + return [_settings.ResponseClass.Replace("{controller}", string.Empty)]; } } @@ -150,7 +150,7 @@ public IEnumerable ExceptionClassNames } else { - return new[] { settings.ExceptionClass.Replace("{controller}", string.Empty) }; + return [settings.ExceptionClass.Replace("{controller}", string.Empty)]; } } return []; diff --git a/src/NSwag.CodeGeneration.CSharp/Models/CSharpOperationModel.cs b/src/NSwag.CodeGeneration.CSharp/Models/CSharpOperationModel.cs index a49866c86c..9c8b28999e 100644 --- a/src/NSwag.CodeGeneration.CSharp/Models/CSharpOperationModel.cs +++ b/src/NSwag.CodeGeneration.CSharp/Models/CSharpOperationModel.cs @@ -16,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; @@ -55,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)]; } } @@ -181,10 +180,10 @@ public IEnumerable ExceptionDescriptions } else if (r.InheritsExceptionSchema) { - return new[] - { + return + [ new CSharpExceptionDescriptionModel(r.Type, r.ExceptionDescription, controllerName, settings) - }; + ]; } else { diff --git a/src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs b/src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs index 8dd18deccb..37c3f6d945 100644 --- a/src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs +++ b/src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs @@ -99,7 +99,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 +140,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); @@ -237,7 +237,7 @@ public void When_using_MultipleClientsFromFirstTagAndOperationName_then_ensure_t // Arrange var operation = new OpenApiOperation { - Tags = tags.ToList() + Tags = [.. tags] }; var generator = new MultipleClientsFromFirstTagAndOperationNameGenerator(); diff --git a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFileTemplateModel.cs b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFileTemplateModel.cs index 24285d90c5..96fe7bb0f1 100644 --- a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFileTemplateModel.cs +++ b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptFileTemplateModel.cs @@ -81,7 +81,7 @@ public IEnumerable ResponseClassNames .Distinct(); } - return new[] { _settings.ResponseClass.Replace("{controller}", string.Empty) }; + return [_settings.ResponseClass.Replace("{controller}", string.Empty)]; } } diff --git a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptOperationModel.cs b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptOperationModel.cs index 02fcac12e6..1354bdfc58 100644 --- a/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptOperationModel.cs +++ b/src/NSwag.CodeGeneration.TypeScript/Models/TypeScriptOperationModel.cs @@ -39,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 @@ -131,7 +128,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/TypeScriptClientGenerator.cs b/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGenerator.cs index 73ecc8be90..f7eea46c09 100644 --- a/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGenerator.cs +++ b/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGenerator.cs @@ -45,8 +45,8 @@ public TypeScriptClientGenerator(OpenApiDocument document, TypeScriptClientGener _extensionCode = new TypeScriptExtensionCode( Settings.TypeScriptGeneratorSettings.ExtensionCode, - (Settings.TypeScriptGeneratorSettings.ExtendedClasses ?? []).Concat(new[] { Settings.ConfigurationClass }).ToArray(), - new[] { Settings.ClientBaseClass }); + [.. (Settings.TypeScriptGeneratorSettings.ExtendedClasses ?? []), Settings.ConfigurationClass], + [Settings.ClientBaseClass]); } /// Gets or sets the generator settings. diff --git a/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGeneratorSettings.cs b/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGeneratorSettings.cs index 9cb81a7180..944cdbb08f 100644 --- a/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGeneratorSettings.cs +++ b/src/NSwag.CodeGeneration.TypeScript/TypeScriptClientGeneratorSettings.cs @@ -36,11 +36,10 @@ 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 = []; } diff --git a/src/NSwag.CodeGeneration/ClientGeneratorBase.cs b/src/NSwag.CodeGeneration/ClientGeneratorBase.cs index 3118a16416..ec2c2e7472 100644 --- a/src/NSwag.CodeGeneration/ClientGeneratorBase.cs +++ b/src/NSwag.CodeGeneration/ClientGeneratorBase.cs @@ -28,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; @@ -70,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) @@ -95,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. @@ -111,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); } } @@ -131,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. @@ -141,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) { @@ -156,7 +162,8 @@ 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(".")) { @@ -169,7 +176,8 @@ private List GetOperations(OpenApiDocument document) } 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; @@ -177,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/OperationNameGenerators/MultipleClientsFromOperationIdOperationNameGenerator.cs b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromOperationIdOperationNameGenerator.cs index 92a814892a..acb555941f 100644 --- a/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromOperationIdOperationNameGenerator.cs +++ b/src/NSwag.CodeGeneration/OperationNameGenerators/MultipleClientsFromOperationIdOperationNameGenerator.cs @@ -77,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); @@ -88,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.Commands/Commands/CodeGeneration/OpenApiToCSharpClientCommand.cs b/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpClientCommand.cs index 07af9188eb..77c5f24781 100644 --- a/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpClientCommand.cs +++ b/src/NSwag.Commands/Commands/CodeGeneration/OpenApiToCSharpClientCommand.cs @@ -295,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/Generation/AspNetCore/ProjectMetadata.cs b/src/NSwag.Commands/Commands/Generation/AspNetCore/ProjectMetadata.cs index 22c2262a30..6508e33fd6 100644 --- a/src/NSwag.Commands/Commands/Generation/AspNetCore/ProjectMetadata.cs +++ b/src/NSwag.Commands/Commands/Generation/AspNetCore/ProjectMetadata.cs @@ -83,10 +83,10 @@ public static async Task GetProjectMetadata( var args = CreateMsBuildArguments(file, framework, configuration, runtime, noBuild, outputPath); - var metadata = await TryReadingUsingGetProperties(args.ToList(), file, noBuild); + var metadata = await TryReadingUsingGetProperties(args, file, noBuild); if (metadata == null) { - metadata = await ReadUsingMsBuildTargets(args.ToList(), file, buildExtensionsDir, console); + metadata = await ReadUsingMsBuildTargets(args, file, buildExtensionsDir, console); } var platformTarget = metadata[nameof(PlatformTarget)]; @@ -164,7 +164,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 diff --git a/src/NSwag.Commands/HostApplication.cs b/src/NSwag.Commands/HostApplication.cs index 13d0c28884..faafdb7204 100644 --- a/src/NSwag.Commands/HostApplication.cs +++ b/src/NSwag.Commands/HostApplication.cs @@ -30,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; } } @@ -154,7 +154,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 diff --git a/src/NSwag.Commands/HostFactoryResolver.cs b/src/NSwag.Commands/HostFactoryResolver.cs index b8bad0e1ec..df0569621f 100644 --- a/src/NSwag.Commands/HostFactoryResolver.cs +++ b/src/NSwag.Commands/HostFactoryResolver.cs @@ -85,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); @@ -149,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) @@ -204,11 +204,11 @@ public object CreateHost() var parameters = _entryPoint.GetParameters(); if (parameters.Length == 0) { - _entryPoint.Invoke(null, Array.Empty()); + _entryPoint.Invoke(null, []); } else { - _entryPoint.Invoke(null, new object[] { _args }); + _entryPoint.Invoke(null, [_args]); } // Try to set an exception if the entry point returns gracefully, this will force diff --git a/src/NSwag.Commands/NSwagCommandProcessor.cs b/src/NSwag.Commands/NSwagCommandProcessor.cs index 066c4e9e7a..4840b3afa7 100644 --- a/src/NSwag.Commands/NSwagCommandProcessor.cs +++ b/src/NSwag.Commands/NSwagCommandProcessor.cs @@ -78,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/OpenApiGeneratorCollection.cs b/src/NSwag.Commands/OpenApiGeneratorCollection.cs index 4e20aa026b..9b98efbae4 100644 --- a/src/NSwag.Commands/OpenApiGeneratorCollection.cs +++ b/src/NSwag.Commands/OpenApiGeneratorCollection.cs @@ -24,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/PathUtilities.cs b/src/NSwag.Commands/PathUtilities.cs index 889d647a9c..85c73682f9 100644 --- a/src/NSwag.Commands/PathUtilities.cs +++ b/src/NSwag.Commands/PathUtilities.cs @@ -18,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. 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 1dece164e8..b81922efd8 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/EmptyPathController.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Controllers/Parameters/EmptyPathController.cs @@ -9,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/Startup.cs b/src/NSwag.Generation.AspNetCore.Tests.Web/Startup.cs index 971dd9c317..92f4804a51 100644 --- a/src/NSwag.Generation.AspNetCore.Tests.Web/Startup.cs +++ b/src/NSwag.Generation.AspNetCore.Tests.Web/Startup.cs @@ -36,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 9277ae7c31..8a038eabe0 100644 --- a/src/NSwag.Generation.AspNetCore.Tests/ApiVersionProcessorWithAspNetCoreTests.cs +++ b/src/NSwag.Generation.AspNetCore.Tests/ApiVersionProcessorWithAspNetCoreTests.cs @@ -14,7 +14,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 +30,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)); @@ -51,7 +51,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)); @@ -72,7 +72,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)); @@ -92,7 +92,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/Processors/OperationParameterProcessor.cs b/src/NSwag.Generation.AspNetCore/Processors/OperationParameterProcessor.cs index 3049c67098..6328205953 100644 --- a/src/NSwag.Generation.AspNetCore/Processors/OperationParameterProcessor.cs +++ b/src/NSwag.Generation.AspNetCore/Processors/OperationParameterProcessor.cs @@ -44,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 => @@ -67,7 +67,7 @@ public bool Process(OperationProcessorContext operationProcessorContext) var extendedApiParameter = new ExtendedApiParameterDescription(_settings.SchemaSettings) { ApiParameter = apiParameter, - Attributes = Enumerable.Empty(), + Attributes = [], ParameterType = apiParameter.Type }; @@ -118,7 +118,7 @@ public bool Process(OperationProcessorContext operationProcessorContext) continue; } - extendedApiParameter.Attributes = extendedApiParameter.Attributes.Concat(new[] { new NotNullAttribute() }); + extendedApiParameter.Attributes = extendedApiParameter.Attributes.Concat([new NotNullAttribute()]); } } @@ -511,7 +511,7 @@ private sealed class ExtendedApiParameterDescription public Type ParameterType { get; set; } - public IEnumerable Attributes { get; set; } = Enumerable.Empty(); + public IEnumerable Attributes { get; set; } = []; public ExtendedApiParameterDescription(IXmlDocsSettings xmlDocsSettings) { diff --git a/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGenerator.cs b/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGenerator.cs index ec94c92147..d795bdcfe1 100644 --- a/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGenerator.cs +++ b/src/NSwag.Generation.WebApi/WebApiOpenApiDocumentGenerator.cs @@ -56,7 +56,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. @@ -65,7 +65,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. @@ -423,7 +423,7 @@ private List GetHttpPaths(Type controllerType, 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]; @@ -432,7 +432,7 @@ private static IEnumerable ExpandOptionalHttpPathParameters(string path, // Only expand if optional parameter is available in action method if (method.GetParameters().Any(p => segment.StartsWith("{" + p.Name + ":") || segment.StartsWith("{" + p.Name + "?"))) { - 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; } diff --git a/src/NSwag.Generation/Processors/OperationResponseProcessorBase.cs b/src/NSwag.Generation/Processors/OperationResponseProcessorBase.cs index 5a0d342086..f76492c2af 100644 --- a/src/NSwag.Generation/Processors/OperationResponseProcessorBase.cs +++ b/src/NSwag.Generation/Processors/OperationResponseProcessorBase.cs @@ -277,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);