diff --git a/bin/configs/csharp-generichost-latest-nrt-useSourceGeneration.yaml b/bin/configs/csharp-generichost-latest-nrt-useSourceGeneration.yaml new file mode 100644 index 00000000000..392e76b045f --- /dev/null +++ b/bin/configs/csharp-generichost-latest-nrt-useSourceGeneration.yaml @@ -0,0 +1,12 @@ +# for csharp generichost +generatorName: csharp +outputDir: samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration +inputSpec: modules/openapi-generator/src/test/resources/3_0/csharp/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +library: generichost +templateDir: modules/openapi-generator/src/main/resources/csharp +additionalProperties: + packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' + useCompareNetObjects: true + disallowAdditionalPropertiesIfNotPresent: false + useSourceGeneration: true + packageName: UseSourceGeneration diff --git a/docs/generators/csharp.md b/docs/generators/csharp.md index 20ef1031f07..54ee3942c72 100644 --- a/docs/generators/csharp.md +++ b/docs/generators/csharp.md @@ -49,6 +49,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false| +|useSourceGeneration|Use source generation where available (only `generichost` library supports this option).| |false| |validatable|Generates self-validatable models.| |true| |zeroBasedEnums|Enumerations with string values will start from 0 when true, 1 when false. If not set, enumerations with string values will start from 0 if the first value is 'unknown', case insensitive.| |null| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java index 3bbae5244ce..60b9060890f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java @@ -59,6 +59,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co protected boolean returnICollection = false; protected boolean netCoreProjectFileFlag = false; protected boolean nullReferenceTypesFlag = false; + protected boolean useSourceGeneration = false; protected String modelPropertyNaming = CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.PascalCase.name(); @@ -416,12 +417,15 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co .put("required", new RequiredParameterLambda()) .put("optional", new OptionalParameterLambda().generator(this)) .put("joinWithComma", new JoinWithCommaLambda()) + .put("joinLinesWithComma", new JoinWithCommaLambda(false, "\n", ",\n")) .put("trimLineBreaks", new TrimLineBreaksLambda()) .put("trimTrailingWithNewLine", new TrimTrailingWhiteSpaceLambda(true)) + .put("trimTrailing", new TrimTrailingWhiteSpaceLambda(false)) .put("first", new FirstLambda(" ")) .put("firstDot", new FirstLambda("\\.")) .put("indent3", new IndentedLambda(12, " ", false)) - .put("indent4", new IndentedLambda(16, " ", false)); + .put("indent4", new IndentedLambda(16, " ", false)) + .put("uniqueLinesWithNewLine", new UniqueLambda("\n", true)); } @Override @@ -1350,6 +1354,14 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co return this.nullReferenceTypesFlag; } + public void setUseSourceGeneration(final Boolean useSourceGeneration) { + this.useSourceGeneration = useSourceGeneration; + } + + public boolean getUseSourceGeneration() { + return this.useSourceGeneration; + } + public void setInterfacePrefix(final String interfacePrefix) { this.interfacePrefix = interfacePrefix; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java index dcb3a9b3f05..1e2b5ed7dce 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java @@ -322,6 +322,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { CodegenConstants.EQUATABLE_DESC, this.equatable); + addSwitch("useSourceGeneration", + "Use source generation where available (only `generichost` library supports this option).", + this.getUseSourceGeneration()); + supportedLibraries.put(GENERICHOST, "HttpClient with Generic Host dependency injection (https://docs.microsoft.com/en-us/dotnet/core/extensions/generic-host) " + "(Experimental. Subject to breaking changes without notice.)"); supportedLibraries.put(HTTPCLIENT, "HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) " @@ -788,6 +792,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { syncBooleanProperty(additionalProperties, CodegenConstants.NON_PUBLIC_API, this::setNonPublicApi, isNonPublicApi()); syncBooleanProperty(additionalProperties, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, this::setUseOneOfDiscriminatorLookup, this.useOneOfDiscriminatorLookup); syncBooleanProperty(additionalProperties, "supportsFileParameters", this::setSupportsFileParameters, this.supportsFileParameters); + syncBooleanProperty(additionalProperties, "useSourceGeneration", this::setUseSourceGeneration, this.useSourceGeneration); final String testPackageName = testPackageName(); String packageFolder = sourceFolder + File.separator + packageName; @@ -855,6 +860,14 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { this.setTypeMapping(); } + @Override + public void setUseSourceGeneration(final Boolean useSourceGeneration) { + if (useSourceGeneration && !this.additionalProperties.containsKey(NET_60_OR_LATER)) { + throw new RuntimeException("Source generation is only compatible with .Net 6 or later."); + } + this.useSourceGeneration = useSourceGeneration; + } + public void setClientPackage(String clientPackage) { this.clientPackage = clientPackage; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/JoinWithCommaLambda.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/JoinWithCommaLambda.java index 16ade8ee8b3..b06fdecb90f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/JoinWithCommaLambda.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/JoinWithCommaLambda.java @@ -38,15 +38,29 @@ import java.io.Writer; */ public class JoinWithCommaLambda implements Mustache.Lambda { - public JoinWithCommaLambda() { + private final String delimit; + private final String coalesce; + private final boolean trimInput; + public JoinWithCommaLambda() { + this.delimit = " "; + this.coalesce = ", "; + this.trimInput = true; + } + + public JoinWithCommaLambda(boolean trimInput, String delimit, String coalesce) { + this.delimit = delimit; + this.coalesce = coalesce; + this.trimInput = trimInput; } @Override public void execute(Template.Fragment fragment, Writer writer) throws IOException { - String[] substr = fragment.execute().trim().split(" "); + String[] input = this.trimInput + ? fragment.execute().trim().split(delimit) + : fragment.execute().split(delimit); - writer.write(String.join(", ", substr)); + writer.write(String.join(coalesce, input)); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/UniqueLambda.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/UniqueLambda.java new file mode 100644 index 00000000000..469c7075a22 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/UniqueLambda.java @@ -0,0 +1,64 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.templating.mustache; + +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; + +import java.io.IOException; +import java.io.Writer; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Split text by the delimiter and then write only the unique entries + * + * Register: + *
+ * additionalProperties.put("unique", new UniqueLambda());
+ * 
+ * + * Use: + *
+ * {{#unique}}{{name}}{{/unique}}
+ * 
+ */ +public class UniqueLambda implements Mustache.Lambda { + private final String delimiter; + private final boolean withNewLine; + + public UniqueLambda(String delimiter, boolean withNewLine) + { + this.delimiter = delimiter; + this.withNewLine = withNewLine; + } + + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + + String[] parts = fragment.execute().split(this.delimiter); + + List uniqueLines = Arrays.stream(parts).distinct().collect(Collectors.toList()); + + writer.write(String.join(delimiter, uniqueLines)); + + if (withNewLine) { + writer.write("\n"); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiResponse`1.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiResponse`1.mustache index 3a182e9f694..292ea17cabd 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiResponse`1.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiResponse`1.mustache @@ -110,8 +110,38 @@ namespace {{packageName}}.{{clientPackage}} /// /// The JsonSerialzierOptions /// - private System.Text.Json.JsonSerializerOptions _jsonSerializerOptions; + private System.Text.Json.JsonSerializerOptions{{#useSourceGeneration}}{{nrt?}}{{/useSourceGeneration}} _jsonSerializerOptions; + {{#useSourceGeneration}} + /// + /// The JsonTypeInfo + /// + private readonly System.Text.Json.Serialization.Metadata.JsonTypeInfo{{nrt?}} _typeInfo; + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + /// + /// + /// + /// + public ApiResponse(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.Serialization.Metadata.JsonTypeInfo typeInfo) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + RawContent = rawContent; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _typeInfo = typeInfo; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + {{/useSourceGeneration}} /// /// Construct the response using an HttpResponseMessage /// diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/AsModel.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/AsModel.mustache index 74601310d63..4bffea0985d 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/AsModel.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/AsModel.mustache @@ -1,4 +1,14 @@ // This logic may be modified with the AsModel.mustache template + {{^useSourceGeneration}} return IsSuccessStatusCode ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) - : default(T); \ No newline at end of file + : default(T); + {{/useSourceGeneration}} + {{#useSourceGeneration}} + if (!IsSuccessStatusCode) + return default(T); + + return _typeInfo == null + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : System.Text.Json.JsonSerializer.Deserialize(RawContent, _typeInfo); + {{/useSourceGeneration}} diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/HostConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/HostConfiguration.mustache index 0d7d2a564f4..61c02557279 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/HostConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/HostConfiguration.mustache @@ -48,6 +48,21 @@ namespace {{packageName}}.{{clientPackage}} {{/models}} JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new{{^net60OrLater}} JsonSerializerOptionsProvider{{/net60OrLater}}(_jsonOptions); _services.AddSingleton(jsonSerializerOptionsProvider); + {{#useSourceGeneration}} + + {{#models}} + {{#model}} + _services.AddSingleton<{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}SerializationContext>(); + {{/model}} + {{/models}} + + {{#models}} + {{#model}} + _services.AddSingleton<{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}DeserializationContext>(); + {{/model}} + {{/models}} + + {{/useSourceGeneration}} _services.AddSingleton();{{#apiInfo}}{{#apis}} _services.AddSingleton<{{classname}}Events>(); _services.AddTransient<{{interfacePrefix}}{{classname}}, {{classname}}>();{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/SourceGenerationContext.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/SourceGenerationContext.mustache new file mode 100644 index 00000000000..9e4612cfd89 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/SourceGenerationContext.mustache @@ -0,0 +1,34 @@ +{{#useSourceGeneration}} + + /// + /// The {{classname}}SerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof({{classname}}))] + {{>visibility}} partial class {{classname}}SerializationContext : JsonSerializerContext + { + /// + /// The {{classname}}SerializationContext + /// + /// + public {{classname}}SerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// {{classname}}DeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof({{classname}}))] + {{>visibility}} partial class {{classname}}DeserializationContext : JsonSerializerContext + { + /// + /// {{classname}}DeserializationContext + /// + /// + public {{classname}}DeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +{{/useSourceGeneration}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/api.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/api.mustache index 305f76b5f7a..03f273af3af 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/api.mustache @@ -103,6 +103,19 @@ namespace {{packageName}}.{{apiPackage}} {{>visibility}} sealed partial class {{classname}} : {{interfacePrefix}}{{classname}} { private JsonSerializerOptions _jsonSerializerOptions; + {{#useSourceGeneration}} + {{#lambda.uniqueLinesWithNewLine}} + {{#operation}} + {{#returnProperty}} + {{#isModel}} + {{#returnType}} + private {{{.}}}DeserializationContext _{{#lambda.camelcase_param}}{{{.}}}DeserializationContext{{/lambda.camelcase_param}}; + {{/returnType}} + {{/isModel}} + {{/returnProperty}} + {{/operation}} + {{/lambda.uniqueLinesWithNewLine}} + {{/useSourceGeneration}} /// /// The logger @@ -148,7 +161,24 @@ namespace {{packageName}}.{{apiPackage}} /// Initializes a new instance of the class. /// /// - public {{classname}}(ILogger<{{classname}}> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, {{classname}}Events {{#lambda.camelcase_param}}{{classname}}Events{{/lambda.camelcase_param}}{{#hasApiKeyMethods}}, + public {{classname}}(ILogger<{{classname}}> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, {{classname}}Events {{#lambda.camelcase_param}}{{classname}}Events{{/lambda.camelcase_param}}{{#lambda.first}}{{#useSourceGeneration}}{{#operation}}{{#returnProperty}}{{#isModel}}, {{/isModel}}{{/returnProperty}}{{/operation}}{{/useSourceGeneration}}{{/lambda.first}}{{#lambda.trimTrailing}}{{#useSourceGeneration}} + {{#lambda.joinLinesWithComma}} + {{#lambda.uniqueLinesWithNewLine}} + {{#operation}} + {{#returnProperty}} + {{#isModel}} + {{#returnType}} + {{{.}}}DeserializationContext {{#lambda.camelcase_param}}{{{.}}}DeserializationContext{{/lambda.camelcase_param}} + {{/returnType}} + {{/isModel}} + {{/returnProperty}} + {{/operation}} + {{/lambda.uniqueLinesWithNewLine}} + {{/lambda.joinLinesWithComma}} + {{/useSourceGeneration}} + {{/lambda.trimTrailing}} + {{#hasApiKeyMethods}} +, TokenProvider apiKeyProvider{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}}, TokenProvider bearerTokenProvider{{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}}, TokenProvider basicTokenProvider{{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}}, @@ -156,6 +186,19 @@ namespace {{packageName}}.{{apiPackage}} TokenProvider oauthTokenProvider{{/hasOAuthMethods}}) { _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + {{#useSourceGeneration}} + {{#lambda.uniqueLinesWithNewLine}} + {{#operation}} + {{#returnProperty}} + {{#isModel}} + {{#returnType}} + _{{#lambda.camelcase_param}}{{{.}}}DeserializationContext{{/lambda.camelcase_param}} = {{#lambda.camelcase_param}}{{{.}}}DeserializationContext{{/lambda.camelcase_param}}; + {{/returnType}} + {{/isModel}} + {{/returnProperty}} + {{/operation}} + {{/lambda.uniqueLinesWithNewLine}} + {{/useSourceGeneration}} Logger = logger; HttpClient = httpClient; Events = {{#lambda.camelcase_param}}{{classname}}Events{{/lambda.camelcase_param}};{{#hasApiKeyMethods}} @@ -539,7 +582,7 @@ namespace {{packageName}}.{{apiPackage}} { string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync({{#net60OrLater}}cancellationToken{{/net60OrLater}}).ConfigureAwait(false); - ApiResponse<{{{returnType}}}{{^returnType}}object{{/returnType}}> apiResponseLocalVar = new ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}>(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "{{path}}", requestedAtLocalVar, _jsonSerializerOptions); + ApiResponse<{{{returnType}}}{{^returnType}}object{{/returnType}}> apiResponseLocalVar = new ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}object{{/returnType}}>(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "{{path}}", requestedAtLocalVar, {{^useSourceGeneration}}_jsonSerializerOptions{{/useSourceGeneration}}{{#useSourceGeneration}}{{^returnProperty}}_jsonSerializerOptions{{/returnProperty}}{{#returnProperty}}{{^isModel}}_jsonSerializerOptions{{/isModel}}{{#isModel}}_{{#lambda.camelcase_param}}{{{returnType}}}DeserializationContext{{/lambda.camelcase_param}}.{{{returnType}}}{{/isModel}}{{/returnProperty}}{{/useSourceGeneration}}); After{{operationId}}DefaultImplementation({{#lambda.joinWithComma}}apiResponseLocalVar {{#allParams}}{{paramName}} {{/allParams}}{{/lambda.joinWithComma}}); diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/model.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/model.mustache index d71ab08c93d..f11dd9ba2b0 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/model.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/model.mustache @@ -23,6 +23,12 @@ using System.ComponentModel.DataAnnotations; {{#useCompareNetObjects}} using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; {{/useCompareNetObjects}} +{{#useGenericHost}} +{{#useSourceGeneration}} +using System.Text.Json.Serialization.Metadata; +using {{packageName}}.{{clientPackage}}; +{{/useSourceGeneration}} +{{/useGenericHost}} {{#models}} {{#lambda.trimTrailingWithNewLine}} {{#model}} @@ -37,6 +43,7 @@ namespace {{packageName}}.{{modelPackage}} {{>JsonConverter}} {{/isEnum}} +{{>SourceGenerationContext}} {{/model}} {{/lambda.trimTrailingWithNewLine}} {{/models}} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/ManualTests.Latest.UseSourceGeneration.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/ManualTests.Latest.UseSourceGeneration.csproj new file mode 100644 index 00000000000..b7165522a82 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/ManualTests.Latest.UseSourceGeneration.csproj @@ -0,0 +1,23 @@ + + + + net7.0 + enable + enable + + false + true + + + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/UnitTest1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/UnitTest1.cs new file mode 100644 index 00000000000..daaec806fa3 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/UnitTest1.cs @@ -0,0 +1,184 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using System.Text.Json; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; +using UseSourceGeneration.Extensions; + +namespace ManualTests.Latest.UseSourceGeneration; + +[TestClass] +public class UnitTest1 +{ + [TestClass] + public sealed class SerializationTests + { + private readonly IHost _host; + + public SerializationTests() + { + IHostBuilder hostBuild = Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + { + string apiKeyTokenValue = context.Configuration[""] ?? "Token not found."; + ApiKeyToken apiKeyToken = new(apiKeyTokenValue, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken); + + string bearerTokenValue = context.Configuration[""] ?? "Token not found."; + BearerToken bearerToken = new(bearerTokenValue, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken); + + string basicTokenUsername = context.Configuration[""] ?? "Username not found."; + string basicTokenPassword = context.Configuration[""] ?? "Password not found."; + BasicToken basicToken = new(basicTokenUsername, basicTokenPassword, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken); + + HttpSigningConfiguration config = new("", "", null, new List(), System.Security.Cryptography.HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken = new(config, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken); + + string oauthTokenValue = context.Configuration[""] ?? "Token not found."; + OAuthToken oauthToken = new(oauthTokenValue, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken); + }); + + _host = hostBuild.Build(); + } + + [TestMethod] + public void Category() + { + CategorySerializationContext serializationContext = _host.Services.GetRequiredService(); + CategoryDeserializationContext deserializationContext = _host.Services.GetRequiredService(); + + Category category = new(1, "test"); + string categoryJson = JsonSerializer.Serialize(category, serializationContext.Category); + Category? category2 = JsonSerializer.Deserialize(categoryJson, deserializationContext.Category); + Assert.AreEqual(category.Id, category2?.Id); + Assert.AreEqual(category.Name, category2?.Name); + } + + [TestMethod] + public void Apple() + { + AppleSerializationContext serializationContext = _host.Services.GetRequiredService(); + AppleDeserializationContext deserializationContext = _host.Services.GetRequiredService(); + + Apple apple = new("#000000", "cultivar", "origin"); + string appleJson = JsonSerializer.Serialize(apple, serializationContext.Apple); + Apple? apple2 = JsonSerializer.Deserialize(appleJson, deserializationContext.Apple); + Assert.IsTrue(apple2 != null && apple.Cultivar.Equals(apple2.Cultivar) && apple.Origin.Equals(apple2.Origin)); + } + + [TestMethod] + public void Pig() + { + PigSerializationContext serializationContext = _host.Services.GetRequiredService(); + PigDeserializationContext deserializationContext = _host.Services.GetRequiredService(); + + BasquePig basquePig = new("BasquePig"); + Pig pig = new(basquePig, "BasquePig"); + string pigJson = JsonSerializer.Serialize(pig, serializationContext.Pig); + Pig? pig2 = JsonSerializer.Deserialize(pigJson, deserializationContext.Pig); + Assert.IsTrue( + pig.DanishPig == null && + pig.BasquePig != null && + pig2 != null && + pig2.BasquePig != null && + pig2.DanishPig == null && + pig2.BasquePig.ClassName.Equals(pig.BasquePig.ClassName)); + } + + [TestMethod] + public void DanishPig() + { + DanishPigSerializationContext serializationContext = _host.Services.GetRequiredService(); + DanishPigDeserializationContext deserializationContext = _host.Services.GetRequiredService(); + + DanishPig danishPig = new("danishPig"); + string danishPigJson = JsonSerializer.Serialize(danishPig, serializationContext.DanishPig); + DanishPig? danishPig2 = JsonSerializer.Deserialize(danishPigJson, deserializationContext.DanishPig); + Assert.IsTrue(danishPig2 != null && danishPig.ClassName.Equals(danishPig2.ClassName)); + } + + [TestMethod] + public void GmFruit() + { + GmFruitSerializationContext serializationContext = _host.Services.GetRequiredService(); + GmFruitDeserializationContext deserializationContext = _host.Services.GetRequiredService(); + + Apple apple = new("#000000", "cultivar", "origin"); + Banana banana = new(10); + GmFruit gmFruit = new(apple, banana, "yellow"); + string gmFruitJson = JsonSerializer.Serialize(gmFruit, serializationContext.GmFruit); + GmFruit? gmFruit2 = JsonSerializer.Deserialize(gmFruitJson, deserializationContext.GmFruit); + Assert.IsTrue( + gmFruit.Apple != null && + gmFruit.Banana != null && + gmFruit2 != null && + gmFruit2.Apple != null && + gmFruit2.Banana != null && + gmFruit2.Apple.Cultivar.Equals(gmFruit.Apple.Cultivar) && + gmFruit2.Apple.Origin.Equals(gmFruit.Apple.Origin) && + gmFruit2.Banana.LengthCm.Equals(gmFruit.Banana.LengthCm)); + + Apple? apple2 = JsonSerializer.Deserialize(gmFruitJson); + Assert.IsTrue(apple2 != null && apple.Cultivar == apple2.Cultivar && apple.Origin == apple2.Origin); + // TODO: assert the the properties from Banana and GmFruit are in additionalProperties + } + + [TestMethod] + public void EquilateralTriangle() + { + EquilateralTriangleSerializationContext serializationContext = _host.Services.GetRequiredService(); + EquilateralTriangleDeserializationContext deserializationContext = _host.Services.GetRequiredService(); + + EquilateralTriangle equilateralTriangle = new("triangle", "equilateral"); + string equilateralTriangleJson = JsonSerializer.Serialize(equilateralTriangle, serializationContext.EquilateralTriangle); + EquilateralTriangle? equilateralTriangle2 = JsonSerializer.Deserialize(equilateralTriangleJson, deserializationContext.EquilateralTriangle); + Assert.IsTrue(equilateralTriangle2 != null && equilateralTriangle.TriangleType.Equals(equilateralTriangle2.TriangleType) && equilateralTriangle.ShapeType.Equals(equilateralTriangle2.ShapeType)); + } + + [TestMethod] + public void Quadrilateral() + { + QuadrilateralSerializationContext serializationContext = _host.Services.GetRequiredService(); + QuadrilateralDeserializationContext deserializationContext = _host.Services.GetRequiredService(); + + ComplexQuadrilateral complexQuadrilateral = new("ComplexQuadrilateral", "shapeType"); + Quadrilateral quadrilateral = new(complexQuadrilateral, "ComplexQuadrilateral"); + string quadrilateralJson = JsonSerializer.Serialize(quadrilateral, serializationContext.Quadrilateral); + Quadrilateral? quadrilateral2 = JsonSerializer.Deserialize(quadrilateralJson, deserializationContext.Quadrilateral); + Assert.IsTrue( + quadrilateral.ComplexQuadrilateral != null && + quadrilateral2 != null && + quadrilateral2.SimpleQuadrilateral == null && + quadrilateral2.ComplexQuadrilateral != null && + quadrilateral2.ComplexQuadrilateral.QuadrilateralType.Equals(quadrilateral.ComplexQuadrilateral.QuadrilateralType) && + quadrilateral2.ComplexQuadrilateral.ShapeType.Equals(quadrilateral.ComplexQuadrilateral.ShapeType)); + } + + [TestMethod] + public void ChildCatTest() + { + ChildCatSerializationContext serializationContext = _host.Services.GetRequiredService(); + ChildCatDeserializationContext deserializationContext = _host.Services.GetRequiredService(); + + ChildCat childCat = new("some name", ChildCat.PetTypeEnum.ChildCat); + string childCatJson = JsonSerializer.Serialize(childCat, serializationContext.ChildCat); + ChildCat? childCat2 = JsonSerializer.Deserialize(childCatJson, deserializationContext.ChildCat); + Assert.IsTrue(childCat2 != null && childCat.PetType.Equals(childCat2.PetType) && childCat.Name.Equals(childCat2.Name)); + } + + [TestMethod] + public void Cat() + { + CatSerializationContext serializationContext = _host.Services.GetRequiredService(); + CatDeserializationContext deserializationContext = _host.Services.GetRequiredService(); + + Cat cat = new("cat", false, "black"); // TODO: where is the address property? + string catJson = JsonSerializer.Serialize(cat, serializationContext.Cat); + Cat? cat2 = JsonSerializer.Deserialize(catJson, deserializationContext.Cat); + Assert.IsTrue(cat2 != null && cat.Declawed.Equals(cat2.Declawed) && cat.ClassName.Equals(cat2.ClassName) && cat.Color.Equals(cat2.Color)); // TODO: add the address property + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/Usings.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/Usings.cs new file mode 100644 index 00000000000..ab67c7ea9df --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/Usings.cs @@ -0,0 +1 @@ +global using Microsoft.VisualStudio.TestTools.UnitTesting; \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/Org.OpenAPITools.sln b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/Org.OpenAPITools.sln index d10a1b4d2ee..dedb0f176ea 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/Org.OpenAPITools.sln +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/Org.OpenAPITools.sln @@ -3,10 +3,14 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.5.33502.453 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenAPIClient-generichost-manual-tests", "OpenAPIClient-generichost-manual-tests\OpenAPIClient-generichost-manual-tests.csproj", "{B120BBFD-C287-4235-A7CC-2C5B37601EB1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenAPIClient-generichost-manual-tests", "OpenAPIClient-generichost-manual-tests\OpenAPIClient-generichost-manual-tests.csproj", "{B120BBFD-C287-4235-A7CC-2C5B37601EB1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Org.OpenAPITools", "..\OpenAPIClient-generichost-net6.0-nrt\src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{C48E5ACD-1ACD-4084-843E-B29DFEE1779C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ManualTests.Latest.UseSourceGeneration", "ManualTests.Latest.UseSourceGeneration\ManualTests.Latest.UseSourceGeneration.csproj", "{0CDF58C6-300E-4282-99AF-69A92FD6EAA5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UseSourceGeneration", "..\OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration\src\UseSourceGeneration\UseSourceGeneration.csproj", "{39D8167C-2DF8-42E9-92F5-5DA59E7F281B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -21,6 +25,14 @@ Global {C48E5ACD-1ACD-4084-843E-B29DFEE1779C}.Debug|Any CPU.Build.0 = Debug|Any CPU {C48E5ACD-1ACD-4084-843E-B29DFEE1779C}.Release|Any CPU.ActiveCfg = Release|Any CPU {C48E5ACD-1ACD-4084-843E-B29DFEE1779C}.Release|Any CPU.Build.0 = Release|Any CPU + {0CDF58C6-300E-4282-99AF-69A92FD6EAA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0CDF58C6-300E-4282-99AF-69A92FD6EAA5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0CDF58C6-300E-4282-99AF-69A92FD6EAA5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0CDF58C6-300E-4282-99AF-69A92FD6EAA5}.Release|Any CPU.Build.0 = Release|Any CPU + {39D8167C-2DF8-42E9-92F5-5DA59E7F281B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {39D8167C-2DF8-42E9-92F5-5DA59E7F281B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {39D8167C-2DF8-42E9-92F5-5DA59E7F281B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {39D8167C-2DF8-42E9-92F5-5DA59E7F281B}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.gitignore b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.gitignore new file mode 100644 index 00000000000..1ee53850b84 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator-ignore b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/FILES new file mode 100644 index 00000000000..4e462324c9c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/FILES @@ -0,0 +1,228 @@ +.gitignore +README.md +UseSourceGeneration.sln +api/openapi.yaml +appveyor.yml +docs/apis/AnotherFakeApi.md +docs/apis/DefaultApi.md +docs/apis/FakeApi.md +docs/apis/FakeClassnameTags123Api.md +docs/apis/PetApi.md +docs/apis/StoreApi.md +docs/apis/UserApi.md +docs/models/Activity.md +docs/models/ActivityOutputElementRepresentation.md +docs/models/AdditionalPropertiesClass.md +docs/models/Animal.md +docs/models/ApiResponse.md +docs/models/Apple.md +docs/models/AppleReq.md +docs/models/ArrayOfArrayOfNumberOnly.md +docs/models/ArrayOfNumberOnly.md +docs/models/ArrayTest.md +docs/models/Banana.md +docs/models/BananaReq.md +docs/models/BasquePig.md +docs/models/Capitalization.md +docs/models/Cat.md +docs/models/Category.md +docs/models/ChildCat.md +docs/models/ClassModel.md +docs/models/ComplexQuadrilateral.md +docs/models/DanishPig.md +docs/models/DateOnlyClass.md +docs/models/DeprecatedObject.md +docs/models/Dog.md +docs/models/Drawing.md +docs/models/EnumArrays.md +docs/models/EnumClass.md +docs/models/EnumTest.md +docs/models/EquilateralTriangle.md +docs/models/File.md +docs/models/FileSchemaTestClass.md +docs/models/Foo.md +docs/models/FooGetDefaultResponse.md +docs/models/FormatTest.md +docs/models/Fruit.md +docs/models/FruitReq.md +docs/models/GmFruit.md +docs/models/GrandparentAnimal.md +docs/models/HasOnlyReadOnly.md +docs/models/HealthCheckResult.md +docs/models/IsoscelesTriangle.md +docs/models/List.md +docs/models/LiteralStringClass.md +docs/models/Mammal.md +docs/models/MapTest.md +docs/models/MixedPropertiesAndAdditionalPropertiesClass.md +docs/models/Model200Response.md +docs/models/ModelClient.md +docs/models/Name.md +docs/models/NotificationtestGetElementsV1ResponseMPayload.md +docs/models/NullableClass.md +docs/models/NullableGuidClass.md +docs/models/NullableShape.md +docs/models/NumberOnly.md +docs/models/ObjectWithDeprecatedFields.md +docs/models/OneOfString.md +docs/models/Order.md +docs/models/OuterComposite.md +docs/models/OuterEnum.md +docs/models/OuterEnumDefaultValue.md +docs/models/OuterEnumInteger.md +docs/models/OuterEnumIntegerDefaultValue.md +docs/models/OuterEnumTest.md +docs/models/ParentPet.md +docs/models/Pet.md +docs/models/Pig.md +docs/models/PolymorphicProperty.md +docs/models/Quadrilateral.md +docs/models/QuadrilateralInterface.md +docs/models/ReadOnlyFirst.md +docs/models/Return.md +docs/models/RolesReportsHash.md +docs/models/RolesReportsHashRole.md +docs/models/ScaleneTriangle.md +docs/models/Shape.md +docs/models/ShapeInterface.md +docs/models/ShapeOrNull.md +docs/models/SimpleQuadrilateral.md +docs/models/SpecialModelName.md +docs/models/Tag.md +docs/models/TestCollectionEndingWithWordList.md +docs/models/TestCollectionEndingWithWordListObject.md +docs/models/Triangle.md +docs/models/TriangleInterface.md +docs/models/User.md +docs/models/Whale.md +docs/models/Zebra.md +docs/models/ZeroBasedEnum.md +docs/models/ZeroBasedEnumClass.md +docs/scripts/git_push.ps1 +docs/scripts/git_push.sh +src/UseSourceGeneration.Test/Api/DependencyInjectionTests.cs +src/UseSourceGeneration.Test/README.md +src/UseSourceGeneration.Test/UseSourceGeneration.Test.csproj +src/UseSourceGeneration/Api/AnotherFakeApi.cs +src/UseSourceGeneration/Api/DefaultApi.cs +src/UseSourceGeneration/Api/FakeApi.cs +src/UseSourceGeneration/Api/FakeClassnameTags123Api.cs +src/UseSourceGeneration/Api/IApi.cs +src/UseSourceGeneration/Api/PetApi.cs +src/UseSourceGeneration/Api/StoreApi.cs +src/UseSourceGeneration/Api/UserApi.cs +src/UseSourceGeneration/Client/ApiException.cs +src/UseSourceGeneration/Client/ApiFactory.cs +src/UseSourceGeneration/Client/ApiKeyToken.cs +src/UseSourceGeneration/Client/ApiResponseEventArgs.cs +src/UseSourceGeneration/Client/ApiResponse`1.cs +src/UseSourceGeneration/Client/BasicToken.cs +src/UseSourceGeneration/Client/BearerToken.cs +src/UseSourceGeneration/Client/ClientUtils.cs +src/UseSourceGeneration/Client/CookieContainer.cs +src/UseSourceGeneration/Client/DateTimeJsonConverter.cs +src/UseSourceGeneration/Client/DateTimeNullableJsonConverter.cs +src/UseSourceGeneration/Client/ExceptionEventArgs.cs +src/UseSourceGeneration/Client/HostConfiguration.cs +src/UseSourceGeneration/Client/HttpSigningConfiguration.cs +src/UseSourceGeneration/Client/HttpSigningToken.cs +src/UseSourceGeneration/Client/JsonSerializerOptionsProvider.cs +src/UseSourceGeneration/Client/OAuthToken.cs +src/UseSourceGeneration/Client/Option.cs +src/UseSourceGeneration/Client/RateLimitProvider`1.cs +src/UseSourceGeneration/Client/TokenBase.cs +src/UseSourceGeneration/Client/TokenContainer`1.cs +src/UseSourceGeneration/Client/TokenProvider`1.cs +src/UseSourceGeneration/Extensions/IHostBuilderExtensions.cs +src/UseSourceGeneration/Extensions/IHttpClientBuilderExtensions.cs +src/UseSourceGeneration/Extensions/IServiceCollectionExtensions.cs +src/UseSourceGeneration/Model/Activity.cs +src/UseSourceGeneration/Model/ActivityOutputElementRepresentation.cs +src/UseSourceGeneration/Model/AdditionalPropertiesClass.cs +src/UseSourceGeneration/Model/Animal.cs +src/UseSourceGeneration/Model/ApiResponse.cs +src/UseSourceGeneration/Model/Apple.cs +src/UseSourceGeneration/Model/AppleReq.cs +src/UseSourceGeneration/Model/ArrayOfArrayOfNumberOnly.cs +src/UseSourceGeneration/Model/ArrayOfNumberOnly.cs +src/UseSourceGeneration/Model/ArrayTest.cs +src/UseSourceGeneration/Model/Banana.cs +src/UseSourceGeneration/Model/BananaReq.cs +src/UseSourceGeneration/Model/BasquePig.cs +src/UseSourceGeneration/Model/Capitalization.cs +src/UseSourceGeneration/Model/Cat.cs +src/UseSourceGeneration/Model/Category.cs +src/UseSourceGeneration/Model/ChildCat.cs +src/UseSourceGeneration/Model/ClassModel.cs +src/UseSourceGeneration/Model/ComplexQuadrilateral.cs +src/UseSourceGeneration/Model/DanishPig.cs +src/UseSourceGeneration/Model/DateOnlyClass.cs +src/UseSourceGeneration/Model/DeprecatedObject.cs +src/UseSourceGeneration/Model/Dog.cs +src/UseSourceGeneration/Model/Drawing.cs +src/UseSourceGeneration/Model/EnumArrays.cs +src/UseSourceGeneration/Model/EnumClass.cs +src/UseSourceGeneration/Model/EnumTest.cs +src/UseSourceGeneration/Model/EquilateralTriangle.cs +src/UseSourceGeneration/Model/File.cs +src/UseSourceGeneration/Model/FileSchemaTestClass.cs +src/UseSourceGeneration/Model/Foo.cs +src/UseSourceGeneration/Model/FooGetDefaultResponse.cs +src/UseSourceGeneration/Model/FormatTest.cs +src/UseSourceGeneration/Model/Fruit.cs +src/UseSourceGeneration/Model/FruitReq.cs +src/UseSourceGeneration/Model/GmFruit.cs +src/UseSourceGeneration/Model/GrandparentAnimal.cs +src/UseSourceGeneration/Model/HasOnlyReadOnly.cs +src/UseSourceGeneration/Model/HealthCheckResult.cs +src/UseSourceGeneration/Model/IsoscelesTriangle.cs +src/UseSourceGeneration/Model/List.cs +src/UseSourceGeneration/Model/LiteralStringClass.cs +src/UseSourceGeneration/Model/Mammal.cs +src/UseSourceGeneration/Model/MapTest.cs +src/UseSourceGeneration/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +src/UseSourceGeneration/Model/Model200Response.cs +src/UseSourceGeneration/Model/ModelClient.cs +src/UseSourceGeneration/Model/Name.cs +src/UseSourceGeneration/Model/NotificationtestGetElementsV1ResponseMPayload.cs +src/UseSourceGeneration/Model/NullableClass.cs +src/UseSourceGeneration/Model/NullableGuidClass.cs +src/UseSourceGeneration/Model/NullableShape.cs +src/UseSourceGeneration/Model/NumberOnly.cs +src/UseSourceGeneration/Model/ObjectWithDeprecatedFields.cs +src/UseSourceGeneration/Model/OneOfString.cs +src/UseSourceGeneration/Model/Order.cs +src/UseSourceGeneration/Model/OuterComposite.cs +src/UseSourceGeneration/Model/OuterEnum.cs +src/UseSourceGeneration/Model/OuterEnumDefaultValue.cs +src/UseSourceGeneration/Model/OuterEnumInteger.cs +src/UseSourceGeneration/Model/OuterEnumIntegerDefaultValue.cs +src/UseSourceGeneration/Model/OuterEnumTest.cs +src/UseSourceGeneration/Model/ParentPet.cs +src/UseSourceGeneration/Model/Pet.cs +src/UseSourceGeneration/Model/Pig.cs +src/UseSourceGeneration/Model/PolymorphicProperty.cs +src/UseSourceGeneration/Model/Quadrilateral.cs +src/UseSourceGeneration/Model/QuadrilateralInterface.cs +src/UseSourceGeneration/Model/ReadOnlyFirst.cs +src/UseSourceGeneration/Model/Return.cs +src/UseSourceGeneration/Model/RolesReportsHash.cs +src/UseSourceGeneration/Model/RolesReportsHashRole.cs +src/UseSourceGeneration/Model/ScaleneTriangle.cs +src/UseSourceGeneration/Model/Shape.cs +src/UseSourceGeneration/Model/ShapeInterface.cs +src/UseSourceGeneration/Model/ShapeOrNull.cs +src/UseSourceGeneration/Model/SimpleQuadrilateral.cs +src/UseSourceGeneration/Model/SpecialModelName.cs +src/UseSourceGeneration/Model/Tag.cs +src/UseSourceGeneration/Model/TestCollectionEndingWithWordList.cs +src/UseSourceGeneration/Model/TestCollectionEndingWithWordListObject.cs +src/UseSourceGeneration/Model/Triangle.cs +src/UseSourceGeneration/Model/TriangleInterface.cs +src/UseSourceGeneration/Model/User.cs +src/UseSourceGeneration/Model/Whale.cs +src/UseSourceGeneration/Model/Zebra.cs +src/UseSourceGeneration/Model/ZeroBasedEnum.cs +src/UseSourceGeneration/Model/ZeroBasedEnumClass.cs +src/UseSourceGeneration/README.md +src/UseSourceGeneration/UseSourceGeneration.csproj diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/VERSION new file mode 100644 index 00000000000..44bad91b171 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/README.md new file mode 100644 index 00000000000..f9c1c7f7462 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/README.md @@ -0,0 +1 @@ +# Created with Openapi Generator diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/UseSourceGeneration.sln b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/UseSourceGeneration.sln new file mode 100644 index 00000000000..6f2442d00e5 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/UseSourceGeneration.sln @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UseSourceGeneration", "src\UseSourceGeneration\UseSourceGeneration.csproj", "{321C8C3F-0156-40C1-AE42-D59761FB9B6C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UseSourceGeneration.Test", "src\UseSourceGeneration.Test\UseSourceGeneration.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.Build.0 = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/api/openapi.yaml new file mode 100644 index 00000000000..45616d427fb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/api/openapi.yaml @@ -0,0 +1,2543 @@ +openapi: 3.0.0 +info: + description: "This spec is mainly for testing Petstore server and contains fake\ + \ endpoints, models. Please do not use this for any other purpose. Special characters:\ + \ \" \\" + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +servers: +- description: petstore server + url: "http://{server}.swagger.io:{port}/v2" + variables: + server: + default: petstore + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" +- description: The local server + url: "https://localhost:8080/{version}" + variables: + version: + default: v2 + enum: + - v1 + - v2 +- description: The local server without variables + url: https://127.0.0.1/no_variable +tags: +- description: Everything about your Pets + name: pet +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /roles/report: + get: + responses: + "200": + content: + application/json: + schema: + items: + $ref: '#/components/schemas/RolesReport' + type: array + description: returns report + /hello: + get: + description: Hello + operationId: Hello + responses: + "200": + content: + application/json: + schema: + items: + format: uuid + type: string + type: array + description: UUIDs + summary: Hello + /foo: + get: + responses: + default: + content: + application/json: + schema: + $ref: '#/components/schemas/_foo_get_default_response' + description: response + /pet: + post: + description: "" + operationId: addPet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "405": + description: Invalid input + security: + - http_signature_test: [] + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet + put: + description: "" + operationId: updatePet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "400": + description: Invalid ID supplied + "404": + description: Pet not found + "405": + description: Validation exception + security: + - http_signature_test: [] + - petstore_auth: + - write:pets + - read:pets + summary: Update an existing pet + tags: + - pet + servers: + - url: http://petstore.swagger.io/v2 + - url: http://path-server-test.petstore.local/v2 + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - deprecated: true + description: Status values that need to be considered for filter + explode: false + in: query + name: status + required: true + schema: + items: + default: available + enum: + - available + - pending + - sold + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid status value + security: + - http_signature_test: [] + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by status + tags: + - pet + /pet/findByTags: + get: + deprecated: true + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: findPetsByTags + parameters: + - description: Tags to filter by + explode: false + in: query + name: tags + required: true + schema: + items: + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid tag value + security: + - http_signature_test: [] + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by tags + tags: + - pet + /pet/{petId}: + delete: + description: "" + operationId: deletePet + parameters: + - explode: false + in: header + name: api_key + required: false + schema: + type: string + style: simple + - description: Pet id to delete + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "400": + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Deletes a pet + tags: + - pet + get: + description: Returns a single pet + operationId: getPetById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + security: + - api_key: [] + summary: Find pet by ID + tags: + - pet + post: + description: "" + operationId: updatePetWithForm + parameters: + - description: ID of pet that needs to be updated + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/updatePetWithForm_request' + responses: + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + /pet/{petId}/uploadImage: + post: + description: "" + operationId: uploadFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFile_request' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image + tags: + - pet + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + "200": + content: + application/json: + schema: + additionalProperties: + format: int32 + type: integer + type: object + description: successful operation + security: + - api_key: [] + summary: Returns pet inventories by status + tags: + - store + /store/order: + post: + description: "" + operationId: placeOrder + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid Order + summary: Place an order for a pet + tags: + - store + /store/order/{order_id}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - description: ID of the order that needs to be deleted + explode: false + in: path + name: order_id + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Delete purchase order by ID + tags: + - store + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generate exceptions + operationId: getOrderById + parameters: + - description: ID of pet that needs to be fetched + explode: false + in: path + name: order_id + required: true + schema: + format: int64 + maximum: 5 + minimum: 1 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Find purchase order by ID + tags: + - store + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + responses: + default: + description: successful operation + summary: Create user + tags: + - user + /user/createWithArray: + post: + description: "" + operationId: createUsersWithArrayInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + summary: Creates list of users with given input array + tags: + - user + /user/createWithList: + post: + description: "" + operationId: createUsersWithListInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + summary: Creates list of users with given input array + tags: + - user + /user/login: + get: + description: "" + operationId: loginUser + parameters: + - description: The user name for login + explode: true + in: query + name: username + required: true + schema: + type: string + style: form + - description: The password for login in clear text + explode: true + in: query + name: password + required: true + schema: + type: string + style: form + responses: + "200": + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + explode: false + schema: + format: int32 + type: integer + style: simple + X-Expires-After: + description: date in UTC when token expires + explode: false + schema: + format: date-time + type: string + style: simple + "400": + description: Invalid username/password supplied + summary: Logs user into the system + tags: + - user + /user/logout: + get: + description: "" + operationId: logoutUser + responses: + default: + description: successful operation + summary: Logs out current logged in user session + tags: + - user + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - description: The name that needs to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Delete user + tags: + - user + get: + description: "" + operationId: getUserByName + parameters: + - description: The name that needs to be fetched. Use user1 for testing. + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + description: successful operation + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Get user by user name + tags: + - user + put: + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - description: name that need to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + responses: + "400": + description: Invalid user supplied + "404": + description: User not found + summary: Updated user + tags: + - user + /fake_classname_test: + patch: + description: To test class name in snake case + operationId: testClassname + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + security: + - api_key_query: [] + summary: To test class name in snake case + tags: + - fake_classname_tags 123#$%^ + /fake: + delete: + description: Fake endpoint to test group parameters (optional) + operationId: testGroupParameters + parameters: + - description: Required String in group parameters + explode: true + in: query + name: required_string_group + required: true + schema: + type: integer + style: form + - description: Required Boolean in group parameters + explode: false + in: header + name: required_boolean_group + required: true + schema: + type: boolean + style: simple + - description: Required Integer in group parameters + explode: true + in: query + name: required_int64_group + required: true + schema: + format: int64 + type: integer + style: form + - description: String in group parameters + explode: true + in: query + name: string_group + required: false + schema: + type: integer + style: form + - description: Boolean in group parameters + explode: false + in: header + name: boolean_group + required: false + schema: + type: boolean + style: simple + - description: Integer in group parameters + explode: true + in: query + name: int64_group + required: false + schema: + format: int64 + type: integer + style: form + responses: + "400": + description: Something wrong + security: + - bearer_test: [] + summary: Fake endpoint to test group parameters (optional) + tags: + - fake + x-group-parameters: true + get: + description: To test enum parameters + operationId: testEnumParameters + parameters: + - description: Header parameter enum test (string array) + explode: false + in: header + name: enum_header_string_array + required: false + schema: + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: simple + - description: Header parameter enum test (string) + explode: false + in: header + name: enum_header_string + required: false + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + style: simple + - description: Query parameter enum test (string array) + explode: true + in: query + name: enum_query_string_array + required: false + schema: + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: form + - description: Query parameter enum test (string) + explode: true + in: query + name: enum_query_string + required: false + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + style: form + - description: Query parameter enum test (double) + explode: true + in: query + name: enum_query_integer + required: false + schema: + enum: + - 1 + - -2 + format: int32 + type: integer + style: form + - description: Query parameter enum test (double) + explode: true + in: query + name: enum_query_double + required: false + schema: + enum: + - 1.1 + - -1.2 + format: double + type: number + style: form + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testEnumParameters_request' + responses: + "400": + description: Invalid request + "404": + description: Not found + summary: To test enum parameters + tags: + - fake + patch: + description: To test "client" model + operationId: testClientModel + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + summary: To test "client" model + tags: + - fake + post: + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: testEndpointParameters + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testEndpointParameters_request' + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + security: + - http_basic_test: [] + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + tags: + - fake + /fake/outer/number: + post: + description: Test serialization of outer number types + operationId: fakeOuterNumberSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterNumber' + description: Input number as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterNumber' + description: Output number + tags: + - fake + /fake/outer/string: + post: + description: Test serialization of outer string types + operationId: fakeOuterStringSerialize + parameters: + - description: Required UUID String + explode: true + in: query + name: required_string_uuid + required: true + schema: + format: uuid + type: string + style: form + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterString' + description: Input string as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterString' + description: Output string + tags: + - fake + /fake/outer/boolean: + post: + description: Test serialization of outer boolean types + operationId: fakeOuterBooleanSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Input boolean as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Output boolean + tags: + - fake + /fake/outer/composite: + post: + description: Test serialization of object with outer number type + operationId: fakeOuterCompositeSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterComposite' + description: Input composite as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterComposite' + description: Output composite + tags: + - fake + /fake/jsonFormData: + get: + description: "" + operationId: testJsonFormData + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testJsonFormData_request' + responses: + "200": + description: successful operation + summary: test json serialization of form data + tags: + - fake + /fake/inline-additionalProperties: + post: + description: "" + operationId: testInlineAdditionalProperties + requestBody: + content: + application/json: + schema: + additionalProperties: + type: string + type: object + description: request body + required: true + responses: + "200": + description: successful operation + summary: test inline additionalProperties + tags: + - fake + /fake/body-with-query-params: + put: + operationId: testBodyWithQueryParams + parameters: + - explode: true + in: query + name: query + required: true + schema: + type: string + style: form + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + required: true + responses: + "200": + description: Success + tags: + - fake + /another-fake/dummy: + patch: + description: To test special tags and operation ID starting with number + operationId: 123_test_@#$%_special_tags + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + summary: To test special tags + tags: + - $another-fake? + /fake/body-with-file-schema: + put: + description: "For this test, the body for this request much reference a schema\ + \ named `File`." + operationId: testBodyWithFileSchema + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FileSchemaTestClass' + required: true + responses: + "200": + description: Success + tags: + - fake + /fake/test-query-parameters: + put: + description: To test the collection format in query parameters + operationId: testQueryParameterCollectionFormat + parameters: + - explode: true + in: query + name: pipe + required: true + schema: + items: + type: string + type: array + style: form + - explode: false + in: query + name: ioutil + required: true + schema: + items: + type: string + type: array + style: form + - explode: false + in: query + name: http + required: true + schema: + items: + type: string + type: array + style: spaceDelimited + - explode: false + in: query + name: url + required: true + schema: + items: + type: string + type: array + style: form + - explode: true + in: query + name: context + required: true + schema: + items: + type: string + type: array + style: form + - explode: true + in: query + name: requiredNotNullable + required: true + schema: + nullable: false + type: string + style: form + - explode: true + in: query + name: requiredNullable + required: true + schema: + nullable: true + type: string + style: form + - explode: true + in: query + name: notRequiredNotNullable + required: false + schema: + nullable: false + type: string + style: form + - explode: true + in: query + name: notRequiredNullable + required: false + schema: + nullable: true + type: string + style: form + responses: + "200": + description: Success + tags: + - fake + /fake/{petId}/uploadImageWithRequiredFile: + post: + description: "" + operationId: uploadFileWithRequiredFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFileWithRequiredFile_request' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + application/vnd.openxmlformats-officedocument.spreadsheetml.sheet: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image (required) + tags: + - pet + /fake/health: + get: + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/HealthCheckResult' + description: The instance started successfully + summary: Health check endpoint + tags: + - fake + /fake/array-of-enums: + get: + operationId: getArrayOfEnums + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ArrayOfEnums' + description: Got named array of enums + summary: Array of Enums + tags: + - fake + /country: + post: + operationId: getCountry + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/getCountry_request' + responses: + "200": + description: OK + /test: + get: + operationId: Test + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/notificationtest-getElements-v1-Response-mPayload' + description: Successful response + summary: Retrieve an existing Notificationtest's Elements +components: + requestBodies: + UserArray: + content: + application/json: + examples: + simple-list: + description: Should not get into code examples + summary: Simple list example + value: + - username: foo + - username: bar + schema: + items: + $ref: '#/components/schemas/User' + type: array + description: List of user object + required: true + Client: + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: client model + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + schemas: + RolesReport: + description: Roles report + items: + $ref: '#/components/schemas/RolesReportsHash' + type: array + RolesReportsHash: + description: Role report Hash + properties: + role_uuid: + format: uuid + type: string + role: + $ref: '#/components/schemas/RolesReportsHash_role' + type: object + Foo: + example: + bar: bar + properties: + bar: + default: bar + type: string + type: object + Bar: + default: bar + type: string + Order: + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: 2020-02-02T20:20:20.000222Z + complete: false + status: placed + properties: + id: + format: int64 + type: integer + petId: + format: int64 + type: integer + quantity: + format: int32 + type: integer + shipDate: + example: 2020-02-02T20:20:20.000222Z + format: date-time + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + type: string + complete: + default: false + type: boolean + type: object + xml: + name: Order + Category: + example: + name: default-name + id: 6 + properties: + id: + format: int64 + type: integer + name: + default: default-name + type: string + required: + - name + type: object + xml: + name: Category + User: + example: + firstName: firstName + lastName: lastName + password: password + userStatus: 6 + objectWithNoDeclaredPropsNullable: "{}" + phone: phone + objectWithNoDeclaredProps: "{}" + id: 0 + anyTypePropNullable: "" + email: email + anyTypeProp: "" + username: username + properties: + id: + format: int64 + type: integer + x-is-unique: true + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + type: integer + objectWithNoDeclaredProps: + description: test code generation for objects Value must be a map of strings + to values. It cannot be the 'null' value. + type: object + objectWithNoDeclaredPropsNullable: + description: test code generation for nullable objects. Value must be a + map of strings to values or the 'null' value. + nullable: true + type: object + anyTypeProp: + description: "test code generation for any type Here the 'type' attribute\ + \ is not specified, which means the value can be anything, including the\ + \ null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389" + anyTypePropNullable: + description: "test code generation for any type Here the 'type' attribute\ + \ is not specified, which means the value can be anything, including the\ + \ null value, string, number, boolean, array or object. The 'nullable'\ + \ attribute does not change the allowed values." + nullable: true + type: object + xml: + name: User + Tag: + example: + name: name + id: 1 + properties: + id: + format: int64 + type: integer + name: + type: string + type: object + xml: + name: Tag + Pet: + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: default-name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + properties: + id: + format: int64 + type: integer + x-is-unique: true + category: + $ref: '#/components/schemas/Category' + name: + example: doggie + type: string + photoUrls: + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + type: object + xml: + name: Pet + ApiResponse: + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + type: object + Return: + description: Model for testing reserved words + properties: + return: + format: int32 + type: integer + xml: + name: Return + Name: + description: Model for testing model name same as property name + properties: + name: + format: int32 + type: integer + snake_case: + format: int32 + readOnly: true + type: integer + property: + type: string + "123Number": + readOnly: true + type: integer + required: + - name + xml: + name: Name + "200_response": + description: Model for testing model name starting with number + properties: + name: + format: int32 + type: integer + class: + type: string + xml: + name: Name + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Animal' + - properties: + breed: + type: string + type: object + Cat: + allOf: + - $ref: '#/components/schemas/Animal' + - $ref: '#/components/schemas/Address' + - properties: + declawed: + type: boolean + type: object + Address: + additionalProperties: + type: integer + type: object + Animal: + discriminator: + propertyName: className + properties: + className: + type: string + color: + default: red + type: string + required: + - className + type: object + AnimalFarm: + items: + $ref: '#/components/schemas/Animal' + type: array + format_test: + properties: + integer: + maximum: 100 + minimum: 10 + multipleOf: 2 + type: integer + int32: + format: int32 + maximum: 200 + minimum: 20 + type: integer + unsigned_integer: + format: int32 + maximum: 200 + minimum: 20 + type: integer + x-unsigned: true + int64: + format: int64 + type: integer + unsigned_long: + format: int64 + type: integer + x-unsigned: true + number: + maximum: 543.2 + minimum: 32.1 + multipleOf: 32.5 + type: number + float: + format: float + maximum: 987.6 + minimum: 54.3 + type: number + double: + format: double + maximum: 123.4 + minimum: 67.8 + type: number + decimal: + format: number + type: string + string: + pattern: "/[a-z]/i" + type: string + byte: + format: byte + type: string + binary: + format: binary + type: string + date: + example: 2020-02-02 + format: date + type: string + dateTime: + example: 2007-12-03T10:15:30+01:00 + format: date-time + type: string + uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + type: string + password: + format: password + maxLength: 64 + minLength: 10 + type: string + pattern_with_digits: + description: A string that is a 10 digit number. Can have leading zeros. + pattern: "^\\d{10}$" + type: string + pattern_with_digits_and_delimiter: + description: A string starting with 'image_' (case insensitive) and one + to three digits following i.e. Image_01. + pattern: "/^image_\\d{1,3}$/i" + type: string + pattern_with_backslash: + description: None + pattern: "^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\\\ + /([0-9]|[1-2][0-9]|3[0-2]))$" + type: string + required: + - byte + - date + - number + - password + type: object + EnumClass: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + Outer_Enum_Test: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + type: string + Enum_Test: + properties: + enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + type: string + enum_string_required: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + type: string + enum_integer: + enum: + - 1 + - -1 + format: int32 + type: integer + enum_integer_only: + enum: + - 2 + - -2 + type: integer + enum_number: + enum: + - 1.1 + - -1.2 + format: double + type: number + outerEnum: + $ref: '#/components/schemas/OuterEnum' + outerEnumInteger: + $ref: '#/components/schemas/OuterEnumInteger' + outerEnumDefaultValue: + $ref: '#/components/schemas/OuterEnumDefaultValue' + outerEnumIntegerDefaultValue: + $ref: '#/components/schemas/OuterEnumIntegerDefaultValue' + required: + - enum_string_required + type: object + AdditionalPropertiesClass: + properties: + map_property: + additionalProperties: + type: string + type: object + map_of_map_property: + additionalProperties: + additionalProperties: + type: string + type: object + type: object + anytype_1: {} + map_with_undeclared_properties_anytype_1: + type: object + map_with_undeclared_properties_anytype_2: + properties: {} + type: object + map_with_undeclared_properties_anytype_3: + additionalProperties: true + type: object + empty_map: + additionalProperties: false + description: "an object with no declared properties and no undeclared properties,\ + \ hence it's an empty map." + type: object + map_with_undeclared_properties_string: + additionalProperties: + type: string + type: object + type: object + MixedPropertiesAndAdditionalPropertiesClass: + properties: + uuid_with_pattern: + format: uuid + pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" + type: string + uuid: + format: uuid + type: string + dateTime: + format: date-time + type: string + map: + additionalProperties: + $ref: '#/components/schemas/Animal' + type: object + type: object + List: + properties: + "123-list": + type: string + type: object + Client: + example: + client: client + properties: + client: + type: string + type: object + ReadOnlyFirst: + properties: + bar: + readOnly: true + type: string + baz: + type: string + type: object + hasOnlyReadOnly: + properties: + bar: + readOnly: true + type: string + foo: + readOnly: true + type: string + type: object + Capitalization: + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: | + Name of the pet + type: string + type: object + MapTest: + properties: + map_map_of_string: + additionalProperties: + additionalProperties: + type: string + type: object + type: object + map_of_enum_string: + additionalProperties: + enum: + - UPPER + - lower + type: string + type: object + direct_map: + additionalProperties: + type: boolean + type: object + indirect_map: + additionalProperties: + type: boolean + type: object + type: object + ArrayTest: + properties: + array_of_string: + items: + type: string + type: array + array_array_of_integer: + items: + items: + format: int64 + type: integer + type: array + type: array + array_array_of_model: + items: + items: + $ref: '#/components/schemas/ReadOnlyFirst' + type: array + type: array + type: object + NumberOnly: + properties: + JustNumber: + type: number + type: object + x-cls-compliant: true + x-com-visible: true + ArrayOfNumberOnly: + properties: + ArrayNumber: + items: + type: number + type: array + type: object + ArrayOfArrayOfNumberOnly: + properties: + ArrayArrayNumber: + items: + items: + type: number + type: array + type: array + type: object + EnumArrays: + properties: + just_symbol: + enum: + - '>=' + - $ + type: string + array_enum: + items: + enum: + - fish + - crab + type: string + type: array + type: object + OuterEnum: + enum: + - placed + - approved + - delivered + nullable: true + type: string + OuterEnumInteger: + enum: + - 0 + - 1 + - 2 + type: integer + OuterEnumDefaultValue: + default: placed + enum: + - placed + - approved + - delivered + type: string + OuterEnumIntegerDefaultValue: + default: 0 + enum: + - 0 + - 1 + - 2 + type: integer + OuterComposite: + example: + my_string: my_string + my_number: 0.8008281904610115 + my_boolean: true + properties: + my_number: + type: number + my_string: + type: string + my_boolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + type: object + OuterNumber: + type: number + OuterString: + type: string + OuterBoolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + StringBooleanMap: + additionalProperties: + type: boolean + type: object + FileSchemaTestClass: + example: + file: + sourceURI: sourceURI + files: + - sourceURI: sourceURI + - sourceURI: sourceURI + properties: + file: + $ref: '#/components/schemas/File' + files: + items: + $ref: '#/components/schemas/File' + type: array + type: object + File: + description: Must be named `File` for test. + example: + sourceURI: sourceURI + properties: + sourceURI: + description: Test capitalization + type: string + type: object + _special_model.name_: + properties: + $special[property.name]: + format: int64 + type: integer + _special_model.name_: + type: string + xml: + name: "$special[model.name]" + HealthCheckResult: + description: Just a string to inform instance is up and running. Make it nullable + in hope to get it as pointer in generated model. + example: + NullableMessage: NullableMessage + properties: + NullableMessage: + nullable: true + type: string + type: object + NullableClass: + additionalProperties: + nullable: true + type: object + properties: + integer_prop: + nullable: true + type: integer + number_prop: + nullable: true + type: number + boolean_prop: + nullable: true + type: boolean + string_prop: + nullable: true + type: string + date_prop: + format: date + nullable: true + type: string + datetime_prop: + format: date-time + nullable: true + type: string + array_nullable_prop: + items: + type: object + nullable: true + type: array + array_and_items_nullable_prop: + items: + nullable: true + type: object + nullable: true + type: array + array_items_nullable: + items: + nullable: true + type: object + type: array + object_nullable_prop: + additionalProperties: + type: object + nullable: true + type: object + object_and_items_nullable_prop: + additionalProperties: + nullable: true + type: object + nullable: true + type: object + object_items_nullable: + additionalProperties: + nullable: true + type: object + type: object + type: object + fruit: + additionalProperties: false + oneOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + properties: + color: + type: string + apple: + nullable: true + properties: + cultivar: + pattern: "^[a-zA-Z\\s]*$" + type: string + origin: + pattern: "/^[A-Z\\s]*$/i" + type: string + color_code: + pattern: "^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$" + type: string + type: object + banana: + properties: + lengthCm: + type: number + type: object + mammal: + discriminator: + propertyName: className + oneOf: + - $ref: '#/components/schemas/whale' + - $ref: '#/components/schemas/zebra' + - $ref: '#/components/schemas/Pig' + whale: + properties: + hasBaleen: + type: boolean + hasTeeth: + type: boolean + className: + type: string + required: + - className + type: object + zebra: + additionalProperties: true + properties: + type: + enum: + - plains + - mountain + - grevys + type: string + className: + type: string + required: + - className + type: object + Pig: + discriminator: + propertyName: className + oneOf: + - $ref: '#/components/schemas/BasquePig' + - $ref: '#/components/schemas/DanishPig' + BasquePig: + properties: + className: + type: string + required: + - className + type: object + DanishPig: + properties: + className: + type: string + required: + - className + type: object + gmFruit: + additionalProperties: false + anyOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + properties: + color: + type: string + fruitReq: + additionalProperties: false + nullable: true + oneOf: + - $ref: '#/components/schemas/appleReq' + - $ref: '#/components/schemas/bananaReq' + appleReq: + additionalProperties: false + properties: + cultivar: + type: string + mealy: + type: boolean + required: + - cultivar + type: object + bananaReq: + additionalProperties: false + properties: + lengthCm: + type: number + sweet: + type: boolean + required: + - lengthCm + type: object + Drawing: + additionalProperties: + $ref: '#/components/schemas/fruit' + properties: + mainShape: + $ref: '#/components/schemas/Shape' + shapeOrNull: + $ref: '#/components/schemas/ShapeOrNull' + nullableShape: + $ref: '#/components/schemas/NullableShape' + shapes: + items: + $ref: '#/components/schemas/Shape' + type: array + type: object + Shape: + discriminator: + propertyName: shapeType + oneOf: + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + ShapeOrNull: + description: The value may be a shape or the 'null' value. This is introduced + in OAS schema >= 3.1. + discriminator: + propertyName: shapeType + nullable: true + oneOf: + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + NullableShape: + description: The value may be a shape or the 'null' value. The 'nullable' attribute + was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema + >= 3.1. + discriminator: + propertyName: shapeType + nullable: true + oneOf: + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + ShapeInterface: + properties: + shapeType: + type: string + required: + - shapeType + TriangleInterface: + properties: + triangleType: + type: string + required: + - triangleType + Triangle: + discriminator: + propertyName: triangleType + oneOf: + - $ref: '#/components/schemas/EquilateralTriangle' + - $ref: '#/components/schemas/IsoscelesTriangle' + - $ref: '#/components/schemas/ScaleneTriangle' + EquilateralTriangle: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/TriangleInterface' + IsoscelesTriangle: + additionalProperties: false + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/TriangleInterface' + ScaleneTriangle: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/TriangleInterface' + QuadrilateralInterface: + properties: + quadrilateralType: + type: string + required: + - quadrilateralType + Quadrilateral: + discriminator: + propertyName: quadrilateralType + oneOf: + - $ref: '#/components/schemas/SimpleQuadrilateral' + - $ref: '#/components/schemas/ComplexQuadrilateral' + SimpleQuadrilateral: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/QuadrilateralInterface' + ComplexQuadrilateral: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/QuadrilateralInterface' + GrandparentAnimal: + discriminator: + propertyName: pet_type + properties: + pet_type: + type: string + required: + - pet_type + type: object + ParentPet: + allOf: + - $ref: '#/components/schemas/GrandparentAnimal' + type: object + ChildCat: + allOf: + - $ref: '#/components/schemas/ParentPet' + - properties: + name: + type: string + pet_type: + default: ChildCat + enum: + - ChildCat + type: string + x-enum-as-string: true + type: object + ArrayOfEnums: + items: + $ref: '#/components/schemas/OuterEnum' + type: array + DateTimeTest: + default: 2010-01-01T10:10:10.000111+01:00 + example: 2010-01-01T10:10:10.000111+01:00 + format: date-time + type: string + DeprecatedObject: + deprecated: true + properties: + name: + type: string + type: object + ObjectWithDeprecatedFields: + properties: + uuid: + type: string + id: + deprecated: true + type: number + deprecatedRef: + $ref: '#/components/schemas/DeprecatedObject' + bars: + deprecated: true + items: + $ref: '#/components/schemas/Bar' + type: array + type: object + PolymorphicProperty: + oneOf: + - type: boolean + - type: string + - type: object + - items: + $ref: '#/components/schemas/StringArrayItem' + type: array + StringArrayItem: + format: string + type: string + Activity: + description: test map of maps + properties: + activity_outputs: + additionalProperties: + $ref: '#/components/schemas/ActivityOutputRepresentation' + type: object + type: object + ActivityOutputRepresentation: + items: + $ref: '#/components/schemas/ActivityOutputElementRepresentation' + type: array + ActivityOutputElementRepresentation: + properties: + prop1: + type: string + prop2: + type: object + type: object + NullableGuidClass: + properties: + uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + type: object + DateOnlyClass: + properties: + dateOnlyProperty: + example: 2017-07-21 + format: date + type: string + type: object + TestCollectionEndingWithWordListObject: + properties: + TestCollectionEndingWithWordList: + items: + $ref: '#/components/schemas/TestCollectionEndingWithWordList' + type: array + type: object + TestCollectionEndingWithWordList: + properties: + value: + type: string + type: object + LiteralStringClass: + properties: + escapedLiteralString: + default: C:\\Users\\username + type: string + unescapedLiteralString: + default: C:\Users\username + type: string + type: object + OneOfString: + oneOf: + - pattern: ^a + type: string + - pattern: ^b + type: string + ZeroBasedEnum: + enum: + - unknown + - notUnknown + type: string + ZeroBasedEnumClass: + properties: + ZeroBasedEnum: + enum: + - unknown + - notUnknown + type: string + type: object + Custom-Variableobject-Response: + additionalProperties: true + description: A Variable object without predefined property names + type: object + Field-pkiNotificationtestID: + type: integer + notificationtest-getElements-v1-Response-mPayload: + example: + a_objVariableobject: + - null + - null + pkiNotificationtestID: 0 + properties: + pkiNotificationtestID: + type: integer + a_objVariableobject: + items: + $ref: '#/components/schemas/Custom-Variableobject-Response' + type: array + required: + - a_objVariableobject + - pkiNotificationtestID + type: object + _foo_get_default_response: + example: + string: + bar: bar + properties: + string: + $ref: '#/components/schemas/Foo' + type: object + updatePetWithForm_request: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + uploadFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + testEnumParameters_request: + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + enum_form_string: + default: -efg + description: Form parameter enum test (string) + enum: + - _abc + - -efg + - (xyz) + type: string + type: object + testEndpointParameters_request: + properties: + integer: + description: None + maximum: 100 + minimum: 10 + type: integer + int32: + description: None + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + description: None + format: int64 + type: integer + number: + description: None + maximum: 543.2 + minimum: 32.1 + type: number + float: + description: None + format: float + maximum: 987.6 + type: number + double: + description: None + format: double + maximum: 123.4 + minimum: 67.8 + type: number + string: + description: None + pattern: "/[a-z]/i" + type: string + pattern_without_delimiter: + description: None + pattern: "^[A-Z].*" + type: string + byte: + description: None + format: byte + type: string + binary: + description: None + format: binary + type: string + date: + description: None + format: date + type: string + dateTime: + default: 2010-02-01T10:20:10.11111+01:00 + description: None + example: 2020-02-02T20:20:20.22222Z + format: date-time + type: string + password: + description: None + format: password + maxLength: 64 + minLength: 10 + type: string + callback: + description: None + type: string + required: + - byte + - double + - number + - pattern_without_delimiter + type: object + testJsonFormData_request: + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + type: object + uploadFileWithRequiredFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + format: binary + type: string + required: + - requiredFile + type: object + getCountry_request: + allOf: + - properties: + country: + type: string + required: + - country + type: object + RolesReportsHash_role: + properties: + name: + type: string + type: object + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 + api_key: + in: header + name: api_key + type: apiKey + api_key_query: + in: query + name: api_key_query + type: apiKey + http_basic_test: + scheme: basic + type: http + bearer_test: + bearerFormat: JWT + scheme: bearer + type: http + http_signature_test: + scheme: signature + type: http + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/appveyor.yml b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/appveyor.yml new file mode 100644 index 00000000000..82e02a91a31 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/appveyor.yml @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\UseSourceGeneration\UseSourceGeneration.csproj -o ../../output -c Release --no-build diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/AnotherFakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/AnotherFakeApi.md new file mode 100644 index 00000000000..a86037320d1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/AnotherFakeApi.md @@ -0,0 +1,99 @@ +# UseSourceGeneration.Api.AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**Call123TestSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags | + + +# **Call123TestSpecialTags** +> ModelClient Call123TestSpecialTags (ModelClient modelClient) + +To test special tags + +To test special tags and operation ID starting with number + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class Call123TestSpecialTagsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new AnotherFakeApi(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test special tags + ModelClient result = apiInstance.Call123TestSpecialTags(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling AnotherFakeApi.Call123TestSpecialTags: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the Call123TestSpecialTagsWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // To test special tags + ApiResponse response = apiInstance.Call123TestSpecialTagsWithHttpInfo(modelClient); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling AnotherFakeApi.Call123TestSpecialTagsWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **modelClient** | [**ModelClient**](ModelClient.md) | client model | | + +### Return type + +[**ModelClient**](ModelClient.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/DefaultApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/DefaultApi.md new file mode 100644 index 00000000000..060a9a33d26 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/DefaultApi.md @@ -0,0 +1,429 @@ +# UseSourceGeneration.Api.DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**FooGet**](DefaultApi.md#fooget) | **GET** /foo | | +| [**GetCountry**](DefaultApi.md#getcountry) | **POST** /country | | +| [**Hello**](DefaultApi.md#hello) | **GET** /hello | Hello | +| [**RolesReportGet**](DefaultApi.md#rolesreportget) | **GET** /roles/report | | +| [**Test**](DefaultApi.md#test) | **GET** /test | Retrieve an existing Notificationtest's Elements | + + +# **FooGet** +> FooGetDefaultResponse FooGet () + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class FooGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new DefaultApi(config); + + try + { + FooGetDefaultResponse result = apiInstance.FooGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.FooGet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FooGetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.FooGetWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.FooGetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**FooGetDefaultResponse**](FooGetDefaultResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | response | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **GetCountry** +> void GetCountry (string country) + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class GetCountryExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new DefaultApi(config); + var country = "country_example"; // string | + + try + { + apiInstance.GetCountry(country); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.GetCountry: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetCountryWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + apiInstance.GetCountryWithHttpInfo(country); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.GetCountryWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **country** | **string** | | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **Hello** +> List<Guid> Hello () + +Hello + +Hello + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class HelloExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new DefaultApi(config); + + try + { + // Hello + List result = apiInstance.Hello(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.Hello: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the HelloWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Hello + ApiResponse> response = apiInstance.HelloWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.HelloWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +**List** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | UUIDs | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **RolesReportGet** +> List<List<RolesReportsHash>> RolesReportGet () + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class RolesReportGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new DefaultApi(config); + + try + { + List> result = apiInstance.RolesReportGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.RolesReportGet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the RolesReportGetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse>> response = apiInstance.RolesReportGetWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.RolesReportGetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +**List>** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | returns report | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **Test** +> NotificationtestGetElementsV1ResponseMPayload Test () + +Retrieve an existing Notificationtest's Elements + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new DefaultApi(config); + + try + { + // Retrieve an existing Notificationtest's Elements + NotificationtestGetElementsV1ResponseMPayload result = apiInstance.Test(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.Test: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Retrieve an existing Notificationtest's Elements + ApiResponse response = apiInstance.TestWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.TestWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**NotificationtestGetElementsV1ResponseMPayload**](NotificationtestGetElementsV1ResponseMPayload.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful response | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/FakeApi.md new file mode 100644 index 00000000000..848b3c5a375 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/FakeApi.md @@ -0,0 +1,1402 @@ +# UseSourceGeneration.Api.FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**FakeHealthGet**](FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint | +| [**FakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | | +| [**FakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | | +| [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | +| [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | +| [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | +| [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | +| [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | +| [**TestEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 | +| [**TestEnumParameters**](FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters | +| [**TestGroupParameters**](FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) | +| [**TestInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties | +| [**TestJsonFormData**](FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data | +| [**TestQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-parameters | | + + +# **FakeHealthGet** +> HealthCheckResult FakeHealthGet () + +Health check endpoint + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class FakeHealthGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + + try + { + // Health check endpoint + HealthCheckResult result = apiInstance.FakeHealthGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeHealthGet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FakeHealthGetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Health check endpoint + ApiResponse response = apiInstance.FakeHealthGetWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.FakeHealthGetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | The instance started successfully | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **FakeOuterBooleanSerialize** +> bool FakeOuterBooleanSerialize (bool body = null) + + + +Test serialization of outer boolean types + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class FakeOuterBooleanSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var body = true; // bool | Input boolean as post body (optional) + + try + { + bool result = apiInstance.FakeOuterBooleanSerialize(body); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterBooleanSerialize: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FakeOuterBooleanSerializeWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.FakeOuterBooleanSerializeWithHttpInfo(body); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.FakeOuterBooleanSerializeWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **body** | **bool** | Input boolean as post body | [optional] | + +### Return type + +**bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output boolean | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **FakeOuterCompositeSerialize** +> OuterComposite FakeOuterCompositeSerialize (OuterComposite outerComposite = null) + + + +Test serialization of object with outer number type + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class FakeOuterCompositeSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body (optional) + + try + { + OuterComposite result = apiInstance.FakeOuterCompositeSerialize(outerComposite); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterCompositeSerialize: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FakeOuterCompositeSerializeWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.FakeOuterCompositeSerializeWithHttpInfo(outerComposite); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.FakeOuterCompositeSerializeWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **outerComposite** | [**OuterComposite**](OuterComposite.md) | Input composite as post body | [optional] | + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output composite | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **FakeOuterNumberSerialize** +> decimal FakeOuterNumberSerialize (decimal body = null) + + + +Test serialization of outer number types + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class FakeOuterNumberSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var body = 8.14D; // decimal | Input number as post body (optional) + + try + { + decimal result = apiInstance.FakeOuterNumberSerialize(body); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterNumberSerialize: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FakeOuterNumberSerializeWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.FakeOuterNumberSerializeWithHttpInfo(body); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.FakeOuterNumberSerializeWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **body** | **decimal** | Input number as post body | [optional] | + +### Return type + +**decimal** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output number | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **FakeOuterStringSerialize** +> string FakeOuterStringSerialize (Guid requiredStringUuid, string body = null) + + + +Test serialization of outer string types + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class FakeOuterStringSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requiredStringUuid = "requiredStringUuid_example"; // Guid | Required UUID String + var body = "body_example"; // string | Input string as post body (optional) + + try + { + string result = apiInstance.FakeOuterStringSerialize(requiredStringUuid, body); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterStringSerialize: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FakeOuterStringSerializeWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.FakeOuterStringSerializeWithHttpInfo(requiredStringUuid, body); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.FakeOuterStringSerializeWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requiredStringUuid** | **Guid** | Required UUID String | | +| **body** | **string** | Input string as post body | [optional] | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output string | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **GetArrayOfEnums** +> List<OuterEnum> GetArrayOfEnums () + +Array of Enums + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class GetArrayOfEnumsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + + try + { + // Array of Enums + List result = apiInstance.GetArrayOfEnums(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.GetArrayOfEnums: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetArrayOfEnumsWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Array of Enums + ApiResponse> response = apiInstance.GetArrayOfEnumsWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.GetArrayOfEnumsWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**List<OuterEnum>**](OuterEnum.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Got named array of enums | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **TestBodyWithFileSchema** +> void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) + + + +For this test, the body for this request much reference a schema named `File`. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestBodyWithFileSchemaExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | + + try + { + apiInstance.TestBodyWithFileSchema(fileSchemaTestClass); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestBodyWithFileSchema: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestBodyWithFileSchemaWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + apiInstance.TestBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestBodyWithFileSchemaWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md) | | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **TestBodyWithQueryParams** +> void TestBodyWithQueryParams (User user, string query) + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestBodyWithQueryParamsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var user = new User(); // User | + var query = "query_example"; // string | + + try + { + apiInstance.TestBodyWithQueryParams(user, query); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestBodyWithQueryParams: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestBodyWithQueryParamsWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + apiInstance.TestBodyWithQueryParamsWithHttpInfo(user, query); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestBodyWithQueryParamsWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **user** | [**User**](User.md) | | | +| **query** | **string** | | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **TestClientModel** +> ModelClient TestClientModel (ModelClient modelClient) + +To test \"client\" model + +To test \"client\" model + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestClientModelExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test \"client\" model + ModelClient result = apiInstance.TestClientModel(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestClientModel: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestClientModelWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // To test \"client\" model + ApiResponse response = apiInstance.TestClientModelWithHttpInfo(modelClient); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestClientModelWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **modelClient** | [**ModelClient**](ModelClient.md) | client model | | + +### Return type + +[**ModelClient**](ModelClient.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **TestEndpointParameters** +> void TestEndpointParameters (byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, DateTime date = null, System.IO.Stream binary = null, float varFloat = null, int integer = null, int int32 = null, long int64 = null, string varString = null, string password = null, string callback = null, DateTime dateTime = null) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestEndpointParametersExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure HTTP basic authorization: http_basic_test + config.Username = "YOUR_USERNAME"; + config.Password = "YOUR_PASSWORD"; + + var apiInstance = new FakeApi(config); + var varByte = System.Text.Encoding.ASCII.GetBytes("BYTE_ARRAY_DATA_HERE"); // byte[] | None + var number = 8.14D; // decimal | None + var varDouble = 1.2D; // double | None + var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // string | None + var date = DateTime.Parse("2013-10-20"); // DateTime | None (optional) + var binary = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | None (optional) + var varFloat = 3.4F; // float | None (optional) + var integer = 56; // int | None (optional) + var int32 = 56; // int | None (optional) + var int64 = 789L; // long | None (optional) + var varString = "varString_example"; // string | None (optional) + var password = "password_example"; // string | None (optional) + var callback = "callback_example"; // string | None (optional) + var dateTime = DateTime.Parse(""2010-02-01T10:20:10.111110+01:00""); // DateTime | None (optional) (default to "2010-02-01T10:20:10.111110+01:00") + + try + { + // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + apiInstance.TestEndpointParameters(varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestEndpointParameters: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestEndpointParametersWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + apiInstance.TestEndpointParametersWithHttpInfo(varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestEndpointParametersWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **varByte** | **byte[]** | None | | +| **number** | **decimal** | None | | +| **varDouble** | **double** | None | | +| **patternWithoutDelimiter** | **string** | None | | +| **date** | **DateTime** | None | [optional] | +| **binary** | **System.IO.Stream****System.IO.Stream** | None | [optional] | +| **varFloat** | **float** | None | [optional] | +| **integer** | **int** | None | [optional] | +| **int32** | **int** | None | [optional] | +| **int64** | **long** | None | [optional] | +| **varString** | **string** | None | [optional] | +| **password** | **string** | None | [optional] | +| **callback** | **string** | None | [optional] | +| **dateTime** | **DateTime** | None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] | + +### Return type + +void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **TestEnumParameters** +> void TestEnumParameters (List enumHeaderStringArray = null, List enumQueryStringArray = null, double enumQueryDouble = null, int enumQueryInteger = null, List enumFormStringArray = null, string enumHeaderString = null, string enumQueryString = null, string enumFormString = null) + +To test enum parameters + +To test enum parameters + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestEnumParametersExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var enumHeaderStringArray = new List(); // List | Header parameter enum test (string array) (optional) + var enumQueryStringArray = new List(); // List | Query parameter enum test (string array) (optional) + var enumQueryDouble = 1.1D; // double | Query parameter enum test (double) (optional) + var enumQueryInteger = 1; // int | Query parameter enum test (double) (optional) + var enumFormStringArray = new List(); // List | Form parameter enum test (string array) (optional) (default to $) + var enumHeaderString = "_abc"; // string | Header parameter enum test (string) (optional) (default to -efg) + var enumQueryString = "_abc"; // string | Query parameter enum test (string) (optional) (default to -efg) + var enumFormString = "_abc"; // string | Form parameter enum test (string) (optional) (default to -efg) + + try + { + // To test enum parameters + apiInstance.TestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestEnumParameters: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestEnumParametersWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // To test enum parameters + apiInstance.TestEnumParametersWithHttpInfo(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestEnumParametersWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **enumHeaderStringArray** | [**List<string>**](string.md) | Header parameter enum test (string array) | [optional] | +| **enumQueryStringArray** | [**List<string>**](string.md) | Query parameter enum test (string array) | [optional] | +| **enumQueryDouble** | **double** | Query parameter enum test (double) | [optional] | +| **enumQueryInteger** | **int** | Query parameter enum test (double) | [optional] | +| **enumFormStringArray** | [**List<string>**](string.md) | Form parameter enum test (string array) | [optional] [default to $] | +| **enumHeaderString** | **string** | Header parameter enum test (string) | [optional] [default to -efg] | +| **enumQueryString** | **string** | Query parameter enum test (string) | [optional] [default to -efg] | +| **enumFormString** | **string** | Form parameter enum test (string) | [optional] [default to -efg] | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid request | - | +| **404** | Not found | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **TestGroupParameters** +> void TestGroupParameters (bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, bool booleanGroup = null, int stringGroup = null, long int64Group = null) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestGroupParametersExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure Bearer token for authorization: bearer_test + config.AccessToken = "YOUR_BEARER_TOKEN"; + + var apiInstance = new FakeApi(config); + var requiredBooleanGroup = true; // bool | Required Boolean in group parameters + var requiredStringGroup = 56; // int | Required String in group parameters + var requiredInt64Group = 789L; // long | Required Integer in group parameters + var booleanGroup = true; // bool | Boolean in group parameters (optional) + var stringGroup = 56; // int | String in group parameters (optional) + var int64Group = 789L; // long | Integer in group parameters (optional) + + try + { + // Fake endpoint to test group parameters (optional) + apiInstance.TestGroupParameters(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestGroupParameters: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestGroupParametersWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Fake endpoint to test group parameters (optional) + apiInstance.TestGroupParametersWithHttpInfo(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestGroupParametersWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requiredBooleanGroup** | **bool** | Required Boolean in group parameters | | +| **requiredStringGroup** | **int** | Required String in group parameters | | +| **requiredInt64Group** | **long** | Required Integer in group parameters | | +| **booleanGroup** | **bool** | Boolean in group parameters | [optional] | +| **stringGroup** | **int** | String in group parameters | [optional] | +| **int64Group** | **long** | Integer in group parameters | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +[bearer_test](../README.md#bearer_test) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Something wrong | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **TestInlineAdditionalProperties** +> void TestInlineAdditionalProperties (Dictionary requestBody) + +test inline additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestInlineAdditionalPropertiesExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test inline additionalProperties + apiInstance.TestInlineAdditionalProperties(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestInlineAdditionalProperties: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestInlineAdditionalPropertiesWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test inline additionalProperties + apiInstance.TestInlineAdditionalPropertiesWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestInlineAdditionalPropertiesWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, string>**](string.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **TestJsonFormData** +> void TestJsonFormData (string param, string param2) + +test json serialization of form data + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestJsonFormDataExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var param = "param_example"; // string | field1 + var param2 = "param2_example"; // string | field2 + + try + { + // test json serialization of form data + apiInstance.TestJsonFormData(param, param2); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestJsonFormData: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestJsonFormDataWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test json serialization of form data + apiInstance.TestJsonFormDataWithHttpInfo(param, param2); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestJsonFormDataWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **param** | **string** | field1 | | +| **param2** | **string** | field2 | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **TestQueryParameterCollectionFormat** +> void TestQueryParameterCollectionFormat (List pipe, List ioutil, List http, List url, List context, string requiredNotNullable, string requiredNullable, string notRequiredNotNullable = null, string notRequiredNullable = null) + + + +To test the collection format in query parameters + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestQueryParameterCollectionFormatExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var pipe = new List(); // List | + var ioutil = new List(); // List | + var http = new List(); // List | + var url = new List(); // List | + var context = new List(); // List | + var requiredNotNullable = "requiredNotNullable_example"; // string | + var requiredNullable = "requiredNullable_example"; // string | + var notRequiredNotNullable = "notRequiredNotNullable_example"; // string | (optional) + var notRequiredNullable = "notRequiredNullable_example"; // string | (optional) + + try + { + apiInstance.TestQueryParameterCollectionFormat(pipe, ioutil, http, url, context, requiredNotNullable, requiredNullable, notRequiredNotNullable, notRequiredNullable); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestQueryParameterCollectionFormat: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestQueryParameterCollectionFormatWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + apiInstance.TestQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context, requiredNotNullable, requiredNullable, notRequiredNotNullable, notRequiredNullable); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestQueryParameterCollectionFormatWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **pipe** | [**List<string>**](string.md) | | | +| **ioutil** | [**List<string>**](string.md) | | | +| **http** | [**List<string>**](string.md) | | | +| **url** | [**List<string>**](string.md) | | | +| **context** | [**List<string>**](string.md) | | | +| **requiredNotNullable** | **string** | | | +| **requiredNullable** | **string** | | | +| **notRequiredNotNullable** | **string** | | [optional] | +| **notRequiredNullable** | **string** | | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/FakeClassnameTags123Api.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/FakeClassnameTags123Api.md new file mode 100644 index 00000000000..66f6bcb35ff --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/FakeClassnameTags123Api.md @@ -0,0 +1,104 @@ +# UseSourceGeneration.Api.FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**TestClassname**](FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case | + + +# **TestClassname** +> ModelClient TestClassname (ModelClient modelClient) + +To test class name in snake case + +To test class name in snake case + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestClassnameExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); + + var apiInstance = new FakeClassnameTags123Api(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test class name in snake case + ModelClient result = apiInstance.TestClassname(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeClassnameTags123Api.TestClassname: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestClassnameWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // To test class name in snake case + ApiResponse response = apiInstance.TestClassnameWithHttpInfo(modelClient); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeClassnameTags123Api.TestClassnameWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **modelClient** | [**ModelClient**](ModelClient.md) | client model | | + +### Return type + +[**ModelClient**](ModelClient.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/PetApi.md new file mode 100644 index 00000000000..760ad613c36 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/PetApi.md @@ -0,0 +1,856 @@ +# UseSourceGeneration.Api.PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**AddPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store | +| [**DeletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet | +| [**FindPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status | +| [**FindPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags | +| [**GetPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID | +| [**UpdatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet | +| [**UpdatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data | +| [**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image | +| [**UploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) | + + +# **AddPet** +> void AddPet (Pet pet) + +Add a new pet to the store + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class AddPetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var pet = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Add a new pet to the store + apiInstance.AddPet(pet); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the AddPetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Add a new pet to the store + apiInstance.AddPetWithHttpInfo(pet); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.AddPetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth), [http_signature_test](../README.md#http_signature_test) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **DeletePet** +> void DeletePet (long petId, string apiKey = null) + +Deletes a pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class DeletePetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789L; // long | Pet id to delete + var apiKey = "apiKey_example"; // string | (optional) + + try + { + // Deletes a pet + apiInstance.DeletePet(petId, apiKey); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.DeletePet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the DeletePetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Deletes a pet + apiInstance.DeletePetWithHttpInfo(petId, apiKey); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.DeletePetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **petId** | **long** | Pet id to delete | | +| **apiKey** | **string** | | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid pet value | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **FindPetsByStatus** +> List<Pet> FindPetsByStatus (List status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class FindPetsByStatusExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var status = new List(); // List | Status values that need to be considered for filter + + try + { + // Finds Pets by status + List result = apiInstance.FindPetsByStatus(status); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.FindPetsByStatus: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FindPetsByStatusWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Finds Pets by status + ApiResponse> response = apiInstance.FindPetsByStatusWithHttpInfo(status); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.FindPetsByStatusWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **status** | [**List<string>**](string.md) | Status values that need to be considered for filter | | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth), [http_signature_test](../README.md#http_signature_test) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **FindPetsByTags** +> List<Pet> FindPetsByTags (List tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class FindPetsByTagsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var tags = new List(); // List | Tags to filter by + + try + { + // Finds Pets by tags + List result = apiInstance.FindPetsByTags(tags); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.FindPetsByTags: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FindPetsByTagsWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Finds Pets by tags + ApiResponse> response = apiInstance.FindPetsByTagsWithHttpInfo(tags); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.FindPetsByTagsWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **tags** | [**List<string>**](string.md) | Tags to filter by | | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth), [http_signature_test](../README.md#http_signature_test) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **GetPetById** +> Pet GetPetById (long petId) + +Find pet by ID + +Returns a single pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class GetPetByIdExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new PetApi(config); + var petId = 789L; // long | ID of pet to return + + try + { + // Find pet by ID + Pet result = apiInstance.GetPetById(petId); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.GetPetById: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetPetByIdWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Find pet by ID + ApiResponse response = apiInstance.GetPetByIdWithHttpInfo(petId); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.GetPetByIdWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **petId** | **long** | ID of pet to return | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **UpdatePet** +> void UpdatePet (Pet pet) + +Update an existing pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class UpdatePetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var pet = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Update an existing pet + apiInstance.UpdatePet(pet); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UpdatePet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the UpdatePetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Update an existing pet + apiInstance.UpdatePetWithHttpInfo(pet); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.UpdatePetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth), [http_signature_test](../README.md#http_signature_test) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **UpdatePetWithForm** +> void UpdatePetWithForm (long petId, string name = null, string status = null) + +Updates a pet in the store with form data + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class UpdatePetWithFormExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789L; // long | ID of pet that needs to be updated + var name = "name_example"; // string | Updated name of the pet (optional) + var status = "status_example"; // string | Updated status of the pet (optional) + + try + { + // Updates a pet in the store with form data + apiInstance.UpdatePetWithForm(petId, name, status); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UpdatePetWithForm: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the UpdatePetWithFormWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Updates a pet in the store with form data + apiInstance.UpdatePetWithFormWithHttpInfo(petId, name, status); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.UpdatePetWithFormWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **petId** | **long** | ID of pet that needs to be updated | | +| **name** | **string** | Updated name of the pet | [optional] | +| **status** | **string** | Updated status of the pet | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **UploadFile** +> ApiResponse UploadFile (long petId, System.IO.Stream file = null, string additionalMetadata = null) + +uploads an image + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class UploadFileExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789L; // long | ID of pet to update + var file = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | file to upload (optional) + var additionalMetadata = "additionalMetadata_example"; // string | Additional data to pass to server (optional) + + try + { + // uploads an image + ApiResponse result = apiInstance.UploadFile(petId, file, additionalMetadata); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UploadFile: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the UploadFileWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // uploads an image + ApiResponse response = apiInstance.UploadFileWithHttpInfo(petId, file, additionalMetadata); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.UploadFileWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **petId** | **long** | ID of pet to update | | +| **file** | **System.IO.Stream****System.IO.Stream** | file to upload | [optional] | +| **additionalMetadata** | **string** | Additional data to pass to server | [optional] | + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **UploadFileWithRequiredFile** +> ApiResponse UploadFileWithRequiredFile (System.IO.Stream requiredFile, long petId, string additionalMetadata = null) + +uploads an image (required) + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class UploadFileWithRequiredFileExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var requiredFile = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | file to upload + var petId = 789L; // long | ID of pet to update + var additionalMetadata = "additionalMetadata_example"; // string | Additional data to pass to server (optional) + + try + { + // uploads an image (required) + ApiResponse result = apiInstance.UploadFileWithRequiredFile(requiredFile, petId, additionalMetadata); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UploadFileWithRequiredFile: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the UploadFileWithRequiredFileWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // uploads an image (required) + ApiResponse response = apiInstance.UploadFileWithRequiredFileWithHttpInfo(requiredFile, petId, additionalMetadata); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.UploadFileWithRequiredFileWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requiredFile** | **System.IO.Stream****System.IO.Stream** | file to upload | | +| **petId** | **long** | ID of pet to update | | +| **additionalMetadata** | **string** | Additional data to pass to server | [optional] | + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/StoreApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/StoreApi.md new file mode 100644 index 00000000000..a86439757ab --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/StoreApi.md @@ -0,0 +1,373 @@ +# UseSourceGeneration.Api.StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**DeleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID | +| [**GetInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status | +| [**GetOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID | +| [**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet | + + +# **DeleteOrder** +> void DeleteOrder (string orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class DeleteOrderExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new StoreApi(config); + var orderId = "orderId_example"; // string | ID of the order that needs to be deleted + + try + { + // Delete purchase order by ID + apiInstance.DeleteOrder(orderId); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.DeleteOrder: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the DeleteOrderWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Delete purchase order by ID + apiInstance.DeleteOrderWithHttpInfo(orderId); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling StoreApi.DeleteOrderWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **orderId** | **string** | ID of the order that needs to be deleted | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **GetInventory** +> Dictionary<string, int> GetInventory () + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class GetInventoryExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new StoreApi(config); + + try + { + // Returns pet inventories by status + Dictionary result = apiInstance.GetInventory(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.GetInventory: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetInventoryWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Returns pet inventories by status + ApiResponse> response = apiInstance.GetInventoryWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling StoreApi.GetInventoryWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +**Dictionary** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **GetOrderById** +> Order GetOrderById (long orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class GetOrderByIdExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new StoreApi(config); + var orderId = 789L; // long | ID of pet that needs to be fetched + + try + { + // Find purchase order by ID + Order result = apiInstance.GetOrderById(orderId); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.GetOrderById: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetOrderByIdWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Find purchase order by ID + ApiResponse response = apiInstance.GetOrderByIdWithHttpInfo(orderId); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling StoreApi.GetOrderByIdWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **orderId** | **long** | ID of pet that needs to be fetched | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **PlaceOrder** +> Order PlaceOrder (Order order) + +Place an order for a pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class PlaceOrderExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new StoreApi(config); + var order = new Order(); // Order | order placed for purchasing the pet + + try + { + // Place an order for a pet + Order result = apiInstance.PlaceOrder(order); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.PlaceOrder: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the PlaceOrderWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Place an order for a pet + ApiResponse response = apiInstance.PlaceOrderWithHttpInfo(order); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling StoreApi.PlaceOrderWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **order** | [**Order**](Order.md) | order placed for purchasing the pet | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/UserApi.md new file mode 100644 index 00000000000..b9a2ee71fe6 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/UserApi.md @@ -0,0 +1,713 @@ +# UseSourceGeneration.Api.UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateUser**](UserApi.md#createuser) | **POST** /user | Create user | +| [**CreateUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array | +| [**CreateUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array | +| [**DeleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user | +| [**GetUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name | +| [**LoginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system | +| [**LogoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session | +| [**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user | + + +# **CreateUser** +> void CreateUser (User user) + +Create user + +This can only be done by the logged in user. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class CreateUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var user = new User(); // User | Created user object + + try + { + // Create user + apiInstance.CreateUser(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUser: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the CreateUserWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Create user + apiInstance.CreateUserWithHttpInfo(user); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.CreateUserWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **user** | [**User**](User.md) | Created user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **CreateUsersWithArrayInput** +> void CreateUsersWithArrayInput (List user) + +Creates list of users with given input array + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class CreateUsersWithArrayInputExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var user = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithArrayInput(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInput: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the CreateUsersWithArrayInputWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Creates list of users with given input array + apiInstance.CreateUsersWithArrayInputWithHttpInfo(user); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInputWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **user** | [**List<User>**](User.md) | List of user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **CreateUsersWithListInput** +> void CreateUsersWithListInput (List user) + +Creates list of users with given input array + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class CreateUsersWithListInputExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var user = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithListInput(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithListInput: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the CreateUsersWithListInputWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Creates list of users with given input array + apiInstance.CreateUsersWithListInputWithHttpInfo(user); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.CreateUsersWithListInputWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **user** | [**List<User>**](User.md) | List of user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **DeleteUser** +> void DeleteUser (string username) + +Delete user + +This can only be done by the logged in user. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class DeleteUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = "username_example"; // string | The name that needs to be deleted + + try + { + // Delete user + apiInstance.DeleteUser(username); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.DeleteUser: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the DeleteUserWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Delete user + apiInstance.DeleteUserWithHttpInfo(username); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.DeleteUserWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **username** | **string** | The name that needs to be deleted | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **GetUserByName** +> User GetUserByName (string username) + +Get user by user name + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class GetUserByNameExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = "username_example"; // string | The name that needs to be fetched. Use user1 for testing. + + try + { + // Get user by user name + User result = apiInstance.GetUserByName(username); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.GetUserByName: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetUserByNameWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Get user by user name + ApiResponse response = apiInstance.GetUserByNameWithHttpInfo(username); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.GetUserByNameWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **username** | **string** | The name that needs to be fetched. Use user1 for testing. | | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **LoginUser** +> string LoginUser (string username, string password) + +Logs user into the system + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class LoginUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = "username_example"; // string | The user name for login + var password = "password_example"; // string | The password for login in clear text + + try + { + // Logs user into the system + string result = apiInstance.LoginUser(username, password); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.LoginUser: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the LoginUserWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Logs user into the system + ApiResponse response = apiInstance.LoginUserWithHttpInfo(username, password); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.LoginUserWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **username** | **string** | The user name for login | | +| **password** | **string** | The password for login in clear text | | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
* X-Expires-After - date in UTC when token expires
| +| **400** | Invalid username/password supplied | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **LogoutUser** +> void LogoutUser () + +Logs out current logged in user session + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class LogoutUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + + try + { + // Logs out current logged in user session + apiInstance.LogoutUser(); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.LogoutUser: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the LogoutUserWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Logs out current logged in user session + apiInstance.LogoutUserWithHttpInfo(); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.LogoutUserWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + + +# **UpdateUser** +> void UpdateUser (User user, string username) + +Updated user + +This can only be done by the logged in user. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class UpdateUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var user = new User(); // User | Updated user object + var username = "username_example"; // string | name that need to be deleted + + try + { + // Updated user + apiInstance.UpdateUser(user, username); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.UpdateUser: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the UpdateUserWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Updated user + apiInstance.UpdateUserWithHttpInfo(user, username); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.UpdateUserWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **user** | [**User**](User.md) | Updated user object | | +| **username** | **string** | name that need to be deleted | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Activity.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Activity.md new file mode 100644 index 00000000000..02200c197f0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Activity.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.Activity +test map of maps + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ActivityOutputs** | **Dictionary<string, List<ActivityOutputElementRepresentation>>** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ActivityOutputElementRepresentation.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ActivityOutputElementRepresentation.md new file mode 100644 index 00000000000..6020aee5a8f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ActivityOutputElementRepresentation.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.ActivityOutputElementRepresentation + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Prop1** | **string** | | [optional] +**Prop2** | **Object** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/AdditionalPropertiesClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0cd0716de5f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/AdditionalPropertiesClass.md @@ -0,0 +1,17 @@ +# UseSourceGeneration.Model.AdditionalPropertiesClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] +**MapOfMapProperty** | **Dictionary<string, Dictionary<string, string>>** | | [optional] +**MapProperty** | **Dictionary<string, string>** | | [optional] +**MapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional] +**MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] +**MapWithUndeclaredPropertiesAnytype3** | **Dictionary<string, Object>** | | [optional] +**MapWithUndeclaredPropertiesString** | **Dictionary<string, string>** | | [optional] +**Anytype1** | **Object** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Animal.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Animal.md new file mode 100644 index 00000000000..85b216c6844 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Animal.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.Animal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ApiResponse.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ApiResponse.md new file mode 100644 index 00000000000..4a89232fe00 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ApiResponse.md @@ -0,0 +1,12 @@ +# UseSourceGeneration.Model.ApiResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Code** | **int** | | [optional] +**Message** | **string** | | [optional] +**Type** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Apple.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Apple.md new file mode 100644 index 00000000000..65a079b9972 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Apple.md @@ -0,0 +1,12 @@ +# UseSourceGeneration.Model.Apple + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ColorCode** | **string** | | [optional] +**Cultivar** | **string** | | [optional] +**Origin** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/AppleReq.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/AppleReq.md new file mode 100644 index 00000000000..9908286785b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/AppleReq.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.AppleReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Cultivar** | **string** | | +**Mealy** | **bool** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..b17ec104d7c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.ArrayOfArrayOfNumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayArrayNumber** | **List<List<decimal>>** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ArrayOfNumberOnly.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..ab7bf35d6b2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.ArrayOfNumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayNumber** | **List<decimal>** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ArrayTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ArrayTest.md new file mode 100644 index 00000000000..599c44576a9 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ArrayTest.md @@ -0,0 +1,12 @@ +# UseSourceGeneration.Model.ArrayTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayArrayOfInteger** | **List<List<long>>** | | [optional] +**ArrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] +**ArrayOfString** | **List<string>** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Banana.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Banana.md new file mode 100644 index 00000000000..3793247c1bf --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Banana.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.Banana + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**LengthCm** | **decimal** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/BananaReq.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/BananaReq.md new file mode 100644 index 00000000000..9284ab55762 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/BananaReq.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.BananaReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**LengthCm** | **decimal** | | +**Sweet** | **bool** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/BasquePig.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/BasquePig.md new file mode 100644 index 00000000000..48c2dc90cbb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/BasquePig.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.BasquePig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Capitalization.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Capitalization.md new file mode 100644 index 00000000000..31ea60189c5 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Capitalization.md @@ -0,0 +1,15 @@ +# UseSourceGeneration.Model.Capitalization + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ATT_NAME** | **string** | Name of the pet | [optional] +**CapitalCamel** | **string** | | [optional] +**CapitalSnake** | **string** | | [optional] +**SCAETHFlowPoints** | **string** | | [optional] +**SmallCamel** | **string** | | [optional] +**SmallSnake** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Cat.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Cat.md new file mode 100644 index 00000000000..22eb79a9ca0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Cat.md @@ -0,0 +1,12 @@ +# UseSourceGeneration.Model.Cat + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] +**Declawed** | **bool** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Category.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Category.md new file mode 100644 index 00000000000..cebefe7ff37 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Category.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.Category + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Name** | **string** | | [default to "default-name"] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ChildCat.md new file mode 100644 index 00000000000..670272cc202 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ChildCat.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.ChildCat + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [optional] +**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ClassModel.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ClassModel.md new file mode 100644 index 00000000000..8f3f093f582 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ClassModel.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.ClassModel +Model for testing model with \"_class\" property + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**VarClass** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ComplexQuadrilateral.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ComplexQuadrilateral.md new file mode 100644 index 00000000000..f58f4217924 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ComplexQuadrilateral.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.ComplexQuadrilateral + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**QuadrilateralType** | **string** | | +**ShapeType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DanishPig.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DanishPig.md new file mode 100644 index 00000000000..4daedaeb2e1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DanishPig.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.DanishPig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DateOnlyClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DateOnlyClass.md new file mode 100644 index 00000000000..6a98ffe33b9 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DateOnlyClass.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.DateOnlyClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**DateOnlyProperty** | **DateTime** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DeprecatedObject.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DeprecatedObject.md new file mode 100644 index 00000000000..7bb31c469d7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DeprecatedObject.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.DeprecatedObject + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Dog.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Dog.md new file mode 100644 index 00000000000..b41e769c469 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Dog.md @@ -0,0 +1,12 @@ +# UseSourceGeneration.Model.Dog + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] +**Breed** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Drawing.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Drawing.md new file mode 100644 index 00000000000..a9a319fd6bb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Drawing.md @@ -0,0 +1,13 @@ +# UseSourceGeneration.Model.Drawing + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MainShape** | [**Shape**](Shape.md) | | [optional] +**Shapes** | [**List<Shape>**](Shape.md) | | [optional] +**NullableShape** | [**NullableShape**](NullableShape.md) | | [optional] +**ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumArrays.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumArrays.md new file mode 100644 index 00000000000..eec4953ca86 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumArrays.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.EnumArrays + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] +**JustSymbol** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumClass.md new file mode 100644 index 00000000000..339c2a3524d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumClass.md @@ -0,0 +1,9 @@ +# UseSourceGeneration.Model.EnumClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumTest.md new file mode 100644 index 00000000000..49836874e08 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumTest.md @@ -0,0 +1,18 @@ +# UseSourceGeneration.Model.EnumTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EnumInteger** | **int** | | [optional] +**EnumIntegerOnly** | **int** | | [optional] +**EnumNumber** | **double** | | [optional] +**EnumString** | **string** | | [optional] +**EnumStringRequired** | **string** | | +**OuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**OuterEnumInteger** | **OuterEnumInteger** | | [optional] +**OuterEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] +**OuterEnum** | **OuterEnum** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EquilateralTriangle.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EquilateralTriangle.md new file mode 100644 index 00000000000..13021288912 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EquilateralTriangle.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.EquilateralTriangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/File.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/File.md new file mode 100644 index 00000000000..8a86812c936 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/File.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.File +Must be named `File` for test. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SourceURI** | **string** | Test capitalization | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FileSchemaTestClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FileSchemaTestClass.md new file mode 100644 index 00000000000..353a581754c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FileSchemaTestClass.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.FileSchemaTestClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**File** | [**File**](File.md) | | [optional] +**Files** | [**List<File>**](File.md) | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Foo.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Foo.md new file mode 100644 index 00000000000..31583a098f6 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Foo.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.Foo + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [default to "bar"] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FooGetDefaultResponse.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FooGetDefaultResponse.md new file mode 100644 index 00000000000..9beed4cd842 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FooGetDefaultResponse.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.FooGetDefaultResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**VarString** | [**Foo**](Foo.md) | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FormatTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FormatTest.md new file mode 100644 index 00000000000..33be89a5331 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FormatTest.md @@ -0,0 +1,28 @@ +# UseSourceGeneration.Model.FormatTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Binary** | **System.IO.Stream** | | [optional] +**VarByte** | **byte[]** | | +**Date** | **DateTime** | | +**DateTime** | **DateTime** | | [optional] +**VarDecimal** | **decimal** | | [optional] +**VarDouble** | **double** | | [optional] +**VarFloat** | **float** | | [optional] +**Int32** | **int** | | [optional] +**Int64** | **long** | | [optional] +**Integer** | **int** | | [optional] +**Number** | **decimal** | | +**Password** | **string** | | +**PatternWithBackslash** | **string** | None | [optional] +**PatternWithDigits** | **string** | A string that is a 10 digit number. Can have leading zeros. | [optional] +**PatternWithDigitsAndDelimiter** | **string** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] +**VarString** | **string** | | [optional] +**UnsignedInteger** | **uint** | | [optional] +**UnsignedLong** | **ulong** | | [optional] +**Uuid** | **Guid** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Fruit.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Fruit.md new file mode 100644 index 00000000000..a87aa8d7164 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Fruit.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.Fruit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Color** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FruitReq.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FruitReq.md new file mode 100644 index 00000000000..41a68aef65b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FruitReq.md @@ -0,0 +1,9 @@ +# UseSourceGeneration.Model.FruitReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/GmFruit.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/GmFruit.md new file mode 100644 index 00000000000..b265cc9df35 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/GmFruit.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.GmFruit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Color** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/GrandparentAnimal.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/GrandparentAnimal.md new file mode 100644 index 00000000000..26dd7ca81ef --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/GrandparentAnimal.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.GrandparentAnimal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**PetType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/HasOnlyReadOnly.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/HasOnlyReadOnly.md new file mode 100644 index 00000000000..7177783ea0f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.HasOnlyReadOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [readonly] +**Foo** | **string** | | [optional] [readonly] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/HealthCheckResult.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/HealthCheckResult.md new file mode 100644 index 00000000000..c7babb863c1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/HealthCheckResult.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.HealthCheckResult +Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**NullableMessage** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/IsoscelesTriangle.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/IsoscelesTriangle.md new file mode 100644 index 00000000000..f835edb4c44 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/IsoscelesTriangle.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.IsoscelesTriangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/List.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/List.md new file mode 100644 index 00000000000..e38fdf2aa25 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/List.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.List + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Var123List** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/LiteralStringClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/LiteralStringClass.md new file mode 100644 index 00000000000..44fb22cb434 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/LiteralStringClass.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.LiteralStringClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EscapedLiteralString** | **string** | | [optional] [default to "C:\\Users\\username"] +**UnescapedLiteralString** | **string** | | [optional] [default to "C:\Users\username"] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Mammal.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Mammal.md new file mode 100644 index 00000000000..fe8b9d8ecf4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Mammal.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.Mammal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/MapTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/MapTest.md new file mode 100644 index 00000000000..9de4c0a242e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/MapTest.md @@ -0,0 +1,13 @@ +# UseSourceGeneration.Model.MapTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**DirectMap** | **Dictionary<string, bool>** | | [optional] +**IndirectMap** | **Dictionary<string, bool>** | | [optional] +**MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..aab1d5a4187 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,13 @@ +# UseSourceGeneration.Model.MixedPropertiesAndAdditionalPropertiesClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**DateTime** | **DateTime** | | [optional] +**Map** | [**Dictionary<string, Animal>**](Animal.md) | | [optional] +**Uuid** | **Guid** | | [optional] +**UuidWithPattern** | **Guid** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Model200Response.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Model200Response.md new file mode 100644 index 00000000000..28ea5e591da --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Model200Response.md @@ -0,0 +1,12 @@ +# UseSourceGeneration.Model.Model200Response +Model for testing model name starting with number + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**VarClass** | **string** | | [optional] +**Name** | **int** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ModelClient.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ModelClient.md new file mode 100644 index 00000000000..2bb04a1d9aa --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ModelClient.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.ModelClient + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**VarClient** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Name.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Name.md new file mode 100644 index 00000000000..93f6ca3c536 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Name.md @@ -0,0 +1,14 @@ +# UseSourceGeneration.Model.Name +Model for testing model name same as property name + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**VarName** | **int** | | +**Property** | **string** | | [optional] +**SnakeCase** | **int** | | [optional] [readonly] +**Var123Number** | **int** | | [optional] [readonly] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NotificationtestGetElementsV1ResponseMPayload.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NotificationtestGetElementsV1ResponseMPayload.md new file mode 100644 index 00000000000..9ee46b48027 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NotificationtestGetElementsV1ResponseMPayload.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.NotificationtestGetElementsV1ResponseMPayload + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**AObjVariableobject** | **List<Dictionary<string, Object>>** | | +**PkiNotificationtestID** | **int** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableClass.md new file mode 100644 index 00000000000..3bc480afe03 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableClass.md @@ -0,0 +1,21 @@ +# UseSourceGeneration.Model.NullableClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayItemsNullable** | **List<Object>** | | [optional] +**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] +**ArrayAndItemsNullableProp** | **List<Object>** | | [optional] +**ArrayNullableProp** | **List<Object>** | | [optional] +**BooleanProp** | **bool** | | [optional] +**DateProp** | **DateTime** | | [optional] +**DatetimeProp** | **DateTime** | | [optional] +**IntegerProp** | **int** | | [optional] +**NumberProp** | **decimal** | | [optional] +**ObjectAndItemsNullableProp** | **Dictionary<string, Object>** | | [optional] +**ObjectNullableProp** | **Dictionary<string, Object>** | | [optional] +**StringProp** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableGuidClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableGuidClass.md new file mode 100644 index 00000000000..889632214d7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableGuidClass.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.NullableGuidClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Uuid** | **Guid** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableShape.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableShape.md new file mode 100644 index 00000000000..b8418df82ec --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableShape.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.NullableShape +The value may be a shape or the 'null' value. The 'nullable' attribute was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema >= 3.1. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NumberOnly.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NumberOnly.md new file mode 100644 index 00000000000..7442b102d58 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NumberOnly.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.NumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustNumber** | **decimal** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ObjectWithDeprecatedFields.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ObjectWithDeprecatedFields.md new file mode 100644 index 00000000000..206dc48f5be --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ObjectWithDeprecatedFields.md @@ -0,0 +1,13 @@ +# UseSourceGeneration.Model.ObjectWithDeprecatedFields + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bars** | **List<string>** | | [optional] +**DeprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] +**Id** | **decimal** | | [optional] +**Uuid** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OneOfString.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OneOfString.md new file mode 100644 index 00000000000..dc200b1efa3 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OneOfString.md @@ -0,0 +1,9 @@ +# UseSourceGeneration.Model.OneOfString + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Order.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Order.md new file mode 100644 index 00000000000..3ec4ab0e9ad --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Order.md @@ -0,0 +1,15 @@ +# UseSourceGeneration.Model.Order + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**PetId** | **long** | | [optional] +**Quantity** | **int** | | [optional] +**ShipDate** | **DateTime** | | [optional] +**Status** | **string** | Order Status | [optional] +**Complete** | **bool** | | [optional] [default to false] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterComposite.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterComposite.md new file mode 100644 index 00000000000..434ecc88146 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterComposite.md @@ -0,0 +1,12 @@ +# UseSourceGeneration.Model.OuterComposite + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MyBoolean** | **bool** | | [optional] +**MyNumber** | **decimal** | | [optional] +**MyString** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnum.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnum.md new file mode 100644 index 00000000000..5a514c455da --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnum.md @@ -0,0 +1,9 @@ +# UseSourceGeneration.Model.OuterEnum + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumDefaultValue.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumDefaultValue.md new file mode 100644 index 00000000000..36b205ebf8b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumDefaultValue.md @@ -0,0 +1,9 @@ +# UseSourceGeneration.Model.OuterEnumDefaultValue + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumInteger.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumInteger.md new file mode 100644 index 00000000000..3b60a8d59f1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumInteger.md @@ -0,0 +1,9 @@ +# UseSourceGeneration.Model.OuterEnumInteger + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumIntegerDefaultValue.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumIntegerDefaultValue.md new file mode 100644 index 00000000000..9238fbf95b5 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumIntegerDefaultValue.md @@ -0,0 +1,9 @@ +# UseSourceGeneration.Model.OuterEnumIntegerDefaultValue + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumTest.md new file mode 100644 index 00000000000..2491148e71f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/OuterEnumTest.md @@ -0,0 +1,9 @@ +# UseSourceGeneration.Model.OuterEnumTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ParentPet.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ParentPet.md new file mode 100644 index 00000000000..f489f4813e0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ParentPet.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.ParentPet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**PetType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Pet.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Pet.md new file mode 100644 index 00000000000..0c5ac31d799 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Pet.md @@ -0,0 +1,15 @@ +# UseSourceGeneration.Model.Pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Category** | [**Category**](Category.md) | | [optional] +**Id** | **long** | | [optional] +**Name** | **string** | | +**PhotoUrls** | **List<string>** | | +**Status** | **string** | pet status in the store | [optional] +**Tags** | [**List<Tag>**](Tag.md) | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Pig.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Pig.md new file mode 100644 index 00000000000..5298dc5d40c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Pig.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.Pig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/PolymorphicProperty.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/PolymorphicProperty.md new file mode 100644 index 00000000000..77ed953f091 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/PolymorphicProperty.md @@ -0,0 +1,9 @@ +# UseSourceGeneration.Model.PolymorphicProperty + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Quadrilateral.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Quadrilateral.md new file mode 100644 index 00000000000..10c198b0639 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Quadrilateral.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.Quadrilateral + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**QuadrilateralType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/QuadrilateralInterface.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/QuadrilateralInterface.md new file mode 100644 index 00000000000..8c6a5c28b55 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/QuadrilateralInterface.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.QuadrilateralInterface + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**QuadrilateralType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ReadOnlyFirst.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ReadOnlyFirst.md new file mode 100644 index 00000000000..6d9a41c5621 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.ReadOnlyFirst + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [readonly] +**Baz** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Return.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Return.md new file mode 100644 index 00000000000..b96de8ee371 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Return.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.Return +Model for testing reserved words + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**VarReturn** | **int** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/RolesReportsHash.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/RolesReportsHash.md new file mode 100644 index 00000000000..b2f913bf0bb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/RolesReportsHash.md @@ -0,0 +1,12 @@ +# UseSourceGeneration.Model.RolesReportsHash +Role report Hash + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Role** | [**RolesReportsHashRole**](RolesReportsHashRole.md) | | [optional] +**RoleUuid** | **Guid** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/RolesReportsHashRole.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/RolesReportsHashRole.md new file mode 100644 index 00000000000..f5df8d46020 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/RolesReportsHashRole.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.RolesReportsHashRole + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ScaleneTriangle.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ScaleneTriangle.md new file mode 100644 index 00000000000..d3880b980fb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ScaleneTriangle.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.ScaleneTriangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Shape.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Shape.md new file mode 100644 index 00000000000..0cf36743869 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Shape.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.Shape + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ShapeInterface.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ShapeInterface.md new file mode 100644 index 00000000000..712d308bbf9 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ShapeInterface.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.ShapeInterface + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ShapeOrNull.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ShapeOrNull.md new file mode 100644 index 00000000000..6ace4a9d0eb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ShapeOrNull.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.ShapeOrNull +The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/SimpleQuadrilateral.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/SimpleQuadrilateral.md new file mode 100644 index 00000000000..5ea94fcdf60 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/SimpleQuadrilateral.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.SimpleQuadrilateral + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**QuadrilateralType** | **string** | | +**ShapeType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/SpecialModelName.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/SpecialModelName.md new file mode 100644 index 00000000000..72a95327d70 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/SpecialModelName.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.SpecialModelName + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**VarSpecialModelName** | **string** | | [optional] +**SpecialPropertyName** | **long** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Tag.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Tag.md new file mode 100644 index 00000000000..d6608121a13 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Tag.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.Tag + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Name** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/TestCollectionEndingWithWordList.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/TestCollectionEndingWithWordList.md new file mode 100644 index 00000000000..42a98f51ee3 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/TestCollectionEndingWithWordList.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.TestCollectionEndingWithWordList + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Value** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/TestCollectionEndingWithWordListObject.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/TestCollectionEndingWithWordListObject.md new file mode 100644 index 00000000000..0db8b5be146 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/TestCollectionEndingWithWordListObject.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.TestCollectionEndingWithWordListObject + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**TestCollectionEndingWithWordList** | [**List<TestCollectionEndingWithWordList>**](TestCollectionEndingWithWordList.md) | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Triangle.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Triangle.md new file mode 100644 index 00000000000..073cb49ab08 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Triangle.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.Triangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**TriangleType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/TriangleInterface.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/TriangleInterface.md new file mode 100644 index 00000000000..cc2f40f8960 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/TriangleInterface.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.TriangleInterface + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**TriangleType** | **string** | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/User.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/User.md new file mode 100644 index 00000000000..9c3095927a6 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/User.md @@ -0,0 +1,21 @@ +# UseSourceGeneration.Model.User + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Email** | **string** | | [optional] +**FirstName** | **string** | | [optional] +**Id** | **long** | | [optional] +**LastName** | **string** | | [optional] +**ObjectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] +**Password** | **string** | | [optional] +**Phone** | **string** | | [optional] +**UserStatus** | **int** | User Status | [optional] +**Username** | **string** | | [optional] +**AnyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] +**AnyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] +**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Whale.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Whale.md new file mode 100644 index 00000000000..5f4c4f2d263 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Whale.md @@ -0,0 +1,12 @@ +# UseSourceGeneration.Model.Whale + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**HasBaleen** | **bool** | | [optional] +**HasTeeth** | **bool** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Zebra.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Zebra.md new file mode 100644 index 00000000000..4b7be0ee5ad --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Zebra.md @@ -0,0 +1,11 @@ +# UseSourceGeneration.Model.Zebra + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Type** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ZeroBasedEnum.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ZeroBasedEnum.md new file mode 100644 index 00000000000..96b044aa90e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ZeroBasedEnum.md @@ -0,0 +1,9 @@ +# UseSourceGeneration.Model.ZeroBasedEnum + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ZeroBasedEnumClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ZeroBasedEnumClass.md new file mode 100644 index 00000000000..28a38298e73 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ZeroBasedEnumClass.md @@ -0,0 +1,10 @@ +# UseSourceGeneration.Model.ZeroBasedEnumClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ZeroBasedEnum** | **string** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/scripts/git_push.ps1 b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/scripts/git_push.ps1 new file mode 100644 index 00000000000..73ed35c2bb1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/scripts/git_push.ps1 @@ -0,0 +1,75 @@ +param( + [Parameter()][Alias("g")][String]$GitHost = "github.com", + [Parameter()][Alias("u")][String]$GitUserId = "GIT_USER_ID", + [Parameter()][Alias("r")][String]$GitRepoId = "GIT_REPO_ID", + [Parameter()][Alias("m")][string]$Message = "Minor update", + [Parameter()][Alias("h")][switch]$Help +) + +function Publish-ToGitHost{ + if ([string]::IsNullOrWhiteSpace($Message) -or $Message -eq "Minor update"){ + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + $Message = Read-Host -Prompt "Please provide a commit message or press enter" + $Message = if([string]::IsNullOrWhiteSpace($Message)) { "no message provided" } else { $Message } + } + + git init + git add . + git commit -am "${Message}" + $branchName=$(git rev-parse --abbrev-ref HEAD) + $gitRemote=$(git remote) + + if([string]::IsNullOrWhiteSpace($gitRemote)){ + git remote add origin https://${GitHost}/${GitUserId}/${GitRepoId}.git + } + + Write-Output "Pulling from https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git pull origin $branchName --ff-only + + if ($LastExitCode -ne 0){ + if (${GitHost} -eq "github.com"){ + Write-Output "The ${GitRepoId} repository may not exist yet. Creating it now with the GitHub CLI." + gh auth login --hostname github.com --web + gh repo create $GitRepoId --private + # sleep 2 seconds to ensure git finishes creation of the repo + Start-Sleep -Seconds 2 + } + else{ + throw "There was an issue pulling the origin branch. The remote repository may not exist yet." + } + } + + Write-Output "Pushing to https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git push origin $branchName +} + +$ErrorActionPreference = "Stop" +Set-StrictMode -Version 3.0 + +if ($Help){ + Write-Output " + This script will initialize a git repository, then add and commit all files. + The local repository will then be pushed to your preferred git provider. + If the remote repository does not exist yet and you are using GitHub, + the repository will be created for you provided you have the GitHub CLI installed. + + Parameters: + -g | -GitHost -> ex: github.com + -m | -Message -> the git commit message + -r | -GitRepoId -> the name of the repository + -u | -GitUserId -> your user id + " + + return +} + +$rootPath=Resolve-Path -Path $PSScriptRoot/../.. + +Push-Location $rootPath + +try { + Publish-ToGitHost $GitHost $GitUserId $GitRepoId $Message +} +finally{ + Pop-Location +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/scripts/git_push.sh b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/scripts/git_push.sh new file mode 100644 index 00000000000..88210492218 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/scripts/git_push.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=${1:-GIT_USER_ID} +git_repo_id=${2:-GIT_REPO_ID} +release_note=${3:-Minor update} +git_host=${4:-github.com} + +starting_directory=$(pwd) +script_root="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" +cd $script_root +cd ../.. + +if [ "$release_note" = "" ] || [ "$release_note" = "Minor update" ]; then + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + echo "Please provide a commit message or press enter" + read user_input + release_note=$user_input + if [ "$release_note" = "" ]; then + release_note="no message provided" + fi +fi + +git init +git add . +git commit -am "$release_note" +branch_name=$(git rev-parse --abbrev-ref HEAD) +git_remote=$(git remote) + +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +echo "[INFO] Pulling from https://${git_host}/${git_user_id}/${git_repo_id}.git" +git pull origin $branch_name --ff-only + +echo "[INFO] Pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin $branch_name + +cd $starting_directory diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/AnotherFakeApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/AnotherFakeApiTests.cs new file mode 100644 index 00000000000..8ef83b919dc --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/AnotherFakeApiTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace UseSourceGeneration.Test.Api +{ + /// + /// Class for testing AnotherFakeApi + /// + public sealed class AnotherFakeApiTests : ApiTestsBase + { + private readonly IAnotherFakeApi _instance; + + public AnotherFakeApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + /// + /// Test Call123TestSpecialTags + /// + [Fact (Skip = "not implemented")] + public async Task Call123TestSpecialTagsAsyncTest() + { + ModelClient modelClient = default!; + var response = await _instance.Call123TestSpecialTagsAsync(modelClient); + var model = response.AsModel(); + Assert.IsType(model); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/ApiTestsBase.cs new file mode 100644 index 00000000000..db85f0288e9 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/ApiTestsBase.cs @@ -0,0 +1,77 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using Microsoft.Extensions.Hosting; +using UseSourceGeneration.Client; +using UseSourceGeneration.Extensions; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace UseSourceGeneration.Test.Api +{ + /// + /// Base class for API tests + /// + public class ApiTestsBase + { + protected readonly IHost _host; + + public ApiTestsBase(string[] args) + { + _host = CreateHostBuilder(args).Build(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, services, options) => + { + string apiKeyTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken = new(apiKeyTokenValue, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken); + + string bearerTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); + BearerToken bearerToken = new(bearerTokenValue, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken); + + string basicTokenUsername = context.Configuration[""] ?? throw new Exception("Username not found."); + string basicTokenPassword = context.Configuration[""] ?? throw new Exception("Password not found."); + BasicToken basicToken = new(basicTokenUsername, basicTokenPassword, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken); + + HttpSigningConfiguration config = new("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken = new(config, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken); + + string oauthTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); + OAuthToken oauthToken = new(oauthTokenValue, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken); + }); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/DefaultApiTests.cs new file mode 100644 index 00000000000..c9b96924e70 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/DefaultApiTests.cs @@ -0,0 +1,85 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace UseSourceGeneration.Test.Api +{ + /// + /// Class for testing DefaultApi + /// + public sealed class DefaultApiTests : ApiTestsBase + { + private readonly IDefaultApi _instance; + + public DefaultApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + /// + /// Test FooGet + /// + [Fact (Skip = "not implemented")] + public async Task FooGetAsyncTest() + { + var response = await _instance.FooGetAsync(); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test GetCountry + /// + [Fact (Skip = "not implemented")] + public async Task GetCountryAsyncTest() + { + string country = default!; + await _instance.GetCountryAsync(country); + } + + /// + /// Test Hello + /// + [Fact (Skip = "not implemented")] + public async Task HelloAsyncTest() + { + var response = await _instance.HelloAsync(); + var model = response.AsModel(); + Assert.IsType>(model); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/DependencyInjectionTests.cs new file mode 100644 index 00000000000..6ddf22ddedd --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/DependencyInjectionTests.cs @@ -0,0 +1,231 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using System.Collections.Generic; +using System.Security.Cryptography; +using UseSourceGeneration.Client; +using UseSourceGeneration.Api; +using UseSourceGeneration.Extensions; +using Xunit; + +namespace UseSourceGeneration.Test.Api +{ + /// + /// Tests the dependency injection. + /// + public class DependencyInjectionTest + { + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + { + ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken); + + BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken); + + BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken); + + HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken); + + OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken); + }) + .Build(); + + private readonly IHost _hostUsingConfigureWithAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + { + ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken); + + BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken); + + BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken); + + HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken); + + OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken); + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }) + .Build(); + + private readonly IHost _hostUsingAddWithoutAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + { + services.AddApi(options => + { + ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken); + + BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken); + + BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken); + + HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken); + + OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken); + }); + }) + .Build(); + + private readonly IHost _hostUsingAddWithAClient = + Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + { + services.AddApi(options => + { + ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken); + + BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken); + + BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken); + + HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken); + + OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken); + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }); + }) + .Build(); + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithAClientTest() + { + var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); + + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + + var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(fakeApi.HttpClient.BaseAddress != null); + + var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); + + var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(petApi.HttpClient.BaseAddress != null); + + var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(storeApi.HttpClient.BaseAddress != null); + + var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(userApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithoutAClientTest() + { + var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); + + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + + var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(fakeApi.HttpClient.BaseAddress != null); + + var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); + + var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(petApi.HttpClient.BaseAddress != null); + + var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(storeApi.HttpClient.BaseAddress != null); + + var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(userApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithAClientTest() + { + var anotherFakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); + + var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + + var fakeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(fakeApi.HttpClient.BaseAddress != null); + + var fakeClassnameTags123Api = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); + + var petApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(petApi.HttpClient.BaseAddress != null); + + var storeApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(storeApi.HttpClient.BaseAddress != null); + + var userApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(userApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithoutAClientTest() + { + var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); + + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + + var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(fakeApi.HttpClient.BaseAddress != null); + + var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); + + var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(petApi.HttpClient.BaseAddress != null); + + var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(storeApi.HttpClient.BaseAddress != null); + + var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(userApi.HttpClient.BaseAddress != null); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/FakeApiTests.cs new file mode 100644 index 00000000000..82b0ab64736 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/FakeApiTests.cs @@ -0,0 +1,251 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace UseSourceGeneration.Test.Api +{ + /// + /// Class for testing FakeApi + /// + public sealed class FakeApiTests : ApiTestsBase + { + private readonly IFakeApi _instance; + + public FakeApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + /// + /// Test FakeHealthGet + /// + [Fact (Skip = "not implemented")] + public async Task FakeHealthGetAsyncTest() + { + var response = await _instance.FakeHealthGetAsync(); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test FakeOuterBooleanSerialize + /// + [Fact (Skip = "not implemented")] + public async Task FakeOuterBooleanSerializeAsyncTest() + { + Client.Option body = default!; + var response = await _instance.FakeOuterBooleanSerializeAsync(body); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test FakeOuterCompositeSerialize + /// + [Fact (Skip = "not implemented")] + public async Task FakeOuterCompositeSerializeAsyncTest() + { + Client.Option outerComposite = default!; + var response = await _instance.FakeOuterCompositeSerializeAsync(outerComposite); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test FakeOuterNumberSerialize + /// + [Fact (Skip = "not implemented")] + public async Task FakeOuterNumberSerializeAsyncTest() + { + Client.Option body = default!; + var response = await _instance.FakeOuterNumberSerializeAsync(body); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test FakeOuterStringSerialize + /// + [Fact (Skip = "not implemented")] + public async Task FakeOuterStringSerializeAsyncTest() + { + Guid requiredStringUuid = default!; + Client.Option body = default!; + var response = await _instance.FakeOuterStringSerializeAsync(requiredStringUuid, body); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test GetArrayOfEnums + /// + [Fact (Skip = "not implemented")] + public async Task GetArrayOfEnumsAsyncTest() + { + var response = await _instance.GetArrayOfEnumsAsync(); + var model = response.AsModel(); + Assert.IsType>(model); + } + + /// + /// Test TestBodyWithFileSchema + /// + [Fact (Skip = "not implemented")] + public async Task TestBodyWithFileSchemaAsyncTest() + { + FileSchemaTestClass fileSchemaTestClass = default!; + await _instance.TestBodyWithFileSchemaAsync(fileSchemaTestClass); + } + + /// + /// Test TestBodyWithQueryParams + /// + [Fact (Skip = "not implemented")] + public async Task TestBodyWithQueryParamsAsyncTest() + { + User user = default!; + string query = default!; + await _instance.TestBodyWithQueryParamsAsync(user, query); + } + + /// + /// Test TestClientModel + /// + [Fact (Skip = "not implemented")] + public async Task TestClientModelAsyncTest() + { + ModelClient modelClient = default!; + var response = await _instance.TestClientModelAsync(modelClient); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test TestEndpointParameters + /// + [Fact (Skip = "not implemented")] + public async Task TestEndpointParametersAsyncTest() + { + byte[] varByte = default!; + decimal number = default!; + double varDouble = default!; + string patternWithoutDelimiter = default!; + Client.Option date = default!; + Client.Option binary = default!; + Client.Option varFloat = default!; + Client.Option integer = default!; + Client.Option int32 = default!; + Client.Option int64 = default!; + Client.Option varString = default!; + Client.Option password = default!; + Client.Option callback = default!; + Client.Option dateTime = default!; + await _instance.TestEndpointParametersAsync(varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); + } + + /// + /// Test TestEnumParameters + /// + [Fact (Skip = "not implemented")] + public async Task TestEnumParametersAsyncTest() + { + Client.Option> enumHeaderStringArray = default!; + Client.Option> enumQueryStringArray = default!; + Client.Option enumQueryDouble = default!; + Client.Option enumQueryInteger = default!; + Client.Option> enumFormStringArray = default!; + Client.Option enumHeaderString = default!; + Client.Option enumQueryString = default!; + Client.Option enumFormString = default!; + await _instance.TestEnumParametersAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + } + + /// + /// Test TestGroupParameters + /// + [Fact (Skip = "not implemented")] + public async Task TestGroupParametersAsyncTest() + { + bool requiredBooleanGroup = default!; + int requiredStringGroup = default!; + long requiredInt64Group = default!; + Client.Option booleanGroup = default!; + Client.Option stringGroup = default!; + Client.Option int64Group = default!; + await _instance.TestGroupParametersAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + } + + /// + /// Test TestInlineAdditionalProperties + /// + [Fact (Skip = "not implemented")] + public async Task TestInlineAdditionalPropertiesAsyncTest() + { + Dictionary requestBody = default!; + await _instance.TestInlineAdditionalPropertiesAsync(requestBody); + } + + /// + /// Test TestJsonFormData + /// + [Fact (Skip = "not implemented")] + public async Task TestJsonFormDataAsyncTest() + { + string param = default!; + string param2 = default!; + await _instance.TestJsonFormDataAsync(param, param2); + } + + /// + /// Test TestQueryParameterCollectionFormat + /// + [Fact (Skip = "not implemented")] + public async Task TestQueryParameterCollectionFormatAsyncTest() + { + List pipe = default!; + List ioutil = default!; + List http = default!; + List url = default!; + List context = default!; + string requiredNotNullable = default!; + string? requiredNullable = default!; + Client.Option notRequiredNotNullable = default!; + Client.Option notRequiredNullable = default!; + await _instance.TestQueryParameterCollectionFormatAsync(pipe, ioutil, http, url, context, requiredNotNullable, requiredNullable, notRequiredNotNullable, notRequiredNullable); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/FakeClassnameTags123ApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/FakeClassnameTags123ApiTests.cs new file mode 100644 index 00000000000..5945828914d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/FakeClassnameTags123ApiTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace UseSourceGeneration.Test.Api +{ + /// + /// Class for testing FakeClassnameTags123Api + /// + public sealed class FakeClassnameTags123ApiTests : ApiTestsBase + { + private readonly IFakeClassnameTags123Api _instance; + + public FakeClassnameTags123ApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + /// + /// Test TestClassname + /// + [Fact (Skip = "not implemented")] + public async Task TestClassnameAsyncTest() + { + ModelClient modelClient = default!; + var response = await _instance.TestClassnameAsync(modelClient); + var model = response.AsModel(); + Assert.IsType(model); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/PetApiTests.cs new file mode 100644 index 00000000000..6075d6e5e73 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/PetApiTests.cs @@ -0,0 +1,160 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace UseSourceGeneration.Test.Api +{ + /// + /// Class for testing PetApi + /// + public sealed class PetApiTests : ApiTestsBase + { + private readonly IPetApi _instance; + + public PetApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + /// + /// Test AddPet + /// + [Fact (Skip = "not implemented")] + public async Task AddPetAsyncTest() + { + Pet pet = default!; + await _instance.AddPetAsync(pet); + } + + /// + /// Test DeletePet + /// + [Fact (Skip = "not implemented")] + public async Task DeletePetAsyncTest() + { + long petId = default!; + Client.Option apiKey = default!; + await _instance.DeletePetAsync(petId, apiKey); + } + + /// + /// Test FindPetsByStatus + /// + [Fact (Skip = "not implemented")] + public async Task FindPetsByStatusAsyncTest() + { + List status = default!; + var response = await _instance.FindPetsByStatusAsync(status); + var model = response.AsModel(); + Assert.IsType>(model); + } + + /// + /// Test FindPetsByTags + /// + [Fact (Skip = "not implemented")] + public async Task FindPetsByTagsAsyncTest() + { + List tags = default!; + var response = await _instance.FindPetsByTagsAsync(tags); + var model = response.AsModel(); + Assert.IsType>(model); + } + + /// + /// Test GetPetById + /// + [Fact (Skip = "not implemented")] + public async Task GetPetByIdAsyncTest() + { + long petId = default!; + var response = await _instance.GetPetByIdAsync(petId); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test UpdatePet + /// + [Fact (Skip = "not implemented")] + public async Task UpdatePetAsyncTest() + { + Pet pet = default!; + await _instance.UpdatePetAsync(pet); + } + + /// + /// Test UpdatePetWithForm + /// + [Fact (Skip = "not implemented")] + public async Task UpdatePetWithFormAsyncTest() + { + long petId = default!; + Client.Option name = default!; + Client.Option status = default!; + await _instance.UpdatePetWithFormAsync(petId, name, status); + } + + /// + /// Test UploadFile + /// + [Fact (Skip = "not implemented")] + public async Task UploadFileAsyncTest() + { + long petId = default!; + Client.Option file = default!; + Client.Option additionalMetadata = default!; + var response = await _instance.UploadFileAsync(petId, file, additionalMetadata); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test UploadFileWithRequiredFile + /// + [Fact (Skip = "not implemented")] + public async Task UploadFileWithRequiredFileAsyncTest() + { + System.IO.Stream requiredFile = default!; + long petId = default!; + Client.Option additionalMetadata = default!; + var response = await _instance.UploadFileWithRequiredFileAsync(requiredFile, petId, additionalMetadata); + var model = response.AsModel(); + Assert.IsType(model); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/StoreApiTests.cs new file mode 100644 index 00000000000..3320fae2c17 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/StoreApiTests.cs @@ -0,0 +1,98 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace UseSourceGeneration.Test.Api +{ + /// + /// Class for testing StoreApi + /// + public sealed class StoreApiTests : ApiTestsBase + { + private readonly IStoreApi _instance; + + public StoreApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + /// + /// Test DeleteOrder + /// + [Fact (Skip = "not implemented")] + public async Task DeleteOrderAsyncTest() + { + string orderId = default!; + await _instance.DeleteOrderAsync(orderId); + } + + /// + /// Test GetInventory + /// + [Fact (Skip = "not implemented")] + public async Task GetInventoryAsyncTest() + { + var response = await _instance.GetInventoryAsync(); + var model = response.AsModel(); + Assert.IsType>(model); + } + + /// + /// Test GetOrderById + /// + [Fact (Skip = "not implemented")] + public async Task GetOrderByIdAsyncTest() + { + long orderId = default!; + var response = await _instance.GetOrderByIdAsync(orderId); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test PlaceOrder + /// + [Fact (Skip = "not implemented")] + public async Task PlaceOrderAsyncTest() + { + Order order = default!; + var response = await _instance.PlaceOrderAsync(order); + var model = response.AsModel(); + Assert.IsType(model); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/UserApiTests.cs new file mode 100644 index 00000000000..ebc81624667 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/UserApiTests.cs @@ -0,0 +1,138 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace UseSourceGeneration.Test.Api +{ + /// + /// Class for testing UserApi + /// + public sealed class UserApiTests : ApiTestsBase + { + private readonly IUserApi _instance; + + public UserApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + /// + /// Test CreateUser + /// + [Fact (Skip = "not implemented")] + public async Task CreateUserAsyncTest() + { + User user = default!; + await _instance.CreateUserAsync(user); + } + + /// + /// Test CreateUsersWithArrayInput + /// + [Fact (Skip = "not implemented")] + public async Task CreateUsersWithArrayInputAsyncTest() + { + List user = default!; + await _instance.CreateUsersWithArrayInputAsync(user); + } + + /// + /// Test CreateUsersWithListInput + /// + [Fact (Skip = "not implemented")] + public async Task CreateUsersWithListInputAsyncTest() + { + List user = default!; + await _instance.CreateUsersWithListInputAsync(user); + } + + /// + /// Test DeleteUser + /// + [Fact (Skip = "not implemented")] + public async Task DeleteUserAsyncTest() + { + string username = default!; + await _instance.DeleteUserAsync(username); + } + + /// + /// Test GetUserByName + /// + [Fact (Skip = "not implemented")] + public async Task GetUserByNameAsyncTest() + { + string username = default!; + var response = await _instance.GetUserByNameAsync(username); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test LoginUser + /// + [Fact (Skip = "not implemented")] + public async Task LoginUserAsyncTest() + { + string username = default!; + string password = default!; + var response = await _instance.LoginUserAsync(username, password); + var model = response.AsModel(); + Assert.IsType(model); + } + + /// + /// Test LogoutUser + /// + [Fact (Skip = "not implemented")] + public async Task LogoutUserAsyncTest() + { + await _instance.LogoutUserAsync(); + } + + /// + /// Test UpdateUser + /// + [Fact (Skip = "not implemented")] + public async Task UpdateUserAsyncTest() + { + User user = default!; + string username = default!; + await _instance.UpdateUserAsync(user, username); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ActivityOutputElementRepresentationTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ActivityOutputElementRepresentationTests.cs new file mode 100644 index 00000000000..7a12db64784 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ActivityOutputElementRepresentationTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ActivityOutputElementRepresentation + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ActivityOutputElementRepresentationTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ActivityOutputElementRepresentation + //private ActivityOutputElementRepresentation instance; + + public ActivityOutputElementRepresentationTests() + { + // TODO uncomment below to create an instance of ActivityOutputElementRepresentation + //instance = new ActivityOutputElementRepresentation(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ActivityOutputElementRepresentation + /// + [Fact] + public void ActivityOutputElementRepresentationInstanceTest() + { + // TODO uncomment below to test "IsType" ActivityOutputElementRepresentation + //Assert.IsType(instance); + } + + /// + /// Test the property 'Prop1' + /// + [Fact] + public void Prop1Test() + { + // TODO unit test for the property 'Prop1' + } + + /// + /// Test the property 'Prop2' + /// + [Fact] + public void Prop2Test() + { + // TODO unit test for the property 'Prop2' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ActivityTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ActivityTests.cs new file mode 100644 index 00000000000..0229b0bd89b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ActivityTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Activity + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ActivityTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Activity + //private Activity instance; + + public ActivityTests() + { + // TODO uncomment below to create an instance of Activity + //instance = new Activity(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Activity + /// + [Fact] + public void ActivityInstanceTest() + { + // TODO uncomment below to test "IsType" Activity + //Assert.IsType(instance); + } + + /// + /// Test the property 'ActivityOutputs' + /// + [Fact] + public void ActivityOutputsTest() + { + // TODO unit test for the property 'ActivityOutputs' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AdditionalPropertiesClassTests.cs new file mode 100644 index 00000000000..e8f1ddf5e8c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AdditionalPropertiesClassTests.cs @@ -0,0 +1,128 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing AdditionalPropertiesClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AdditionalPropertiesClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for AdditionalPropertiesClass + //private AdditionalPropertiesClass instance; + + public AdditionalPropertiesClassTests() + { + // TODO uncomment below to create an instance of AdditionalPropertiesClass + //instance = new AdditionalPropertiesClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of AdditionalPropertiesClass + /// + [Fact] + public void AdditionalPropertiesClassInstanceTest() + { + // TODO uncomment below to test "IsType" AdditionalPropertiesClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'EmptyMap' + /// + [Fact] + public void EmptyMapTest() + { + // TODO unit test for the property 'EmptyMap' + } + + /// + /// Test the property 'MapOfMapProperty' + /// + [Fact] + public void MapOfMapPropertyTest() + { + // TODO unit test for the property 'MapOfMapProperty' + } + + /// + /// Test the property 'MapProperty' + /// + [Fact] + public void MapPropertyTest() + { + // TODO unit test for the property 'MapProperty' + } + + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype1' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype1Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype1' + } + + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype2' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype2Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype2' + } + + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype3' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype3Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype3' + } + + /// + /// Test the property 'MapWithUndeclaredPropertiesString' + /// + [Fact] + public void MapWithUndeclaredPropertiesStringTest() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesString' + } + + /// + /// Test the property 'Anytype1' + /// + [Fact] + public void Anytype1Test() + { + // TODO unit test for the property 'Anytype1' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AnimalTests.cs new file mode 100644 index 00000000000..8c8620f54da --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AnimalTests.cs @@ -0,0 +1,94 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Animal + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AnimalTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Animal + //private Animal instance; + + public AnimalTests() + { + // TODO uncomment below to create an instance of Animal + //instance = new Animal(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Animal + /// + [Fact] + public void AnimalInstanceTest() + { + // TODO uncomment below to test "IsType" Animal + //Assert.IsType(instance); + } + + /// + /// Test deserialize a Cat from type Animal + /// + [Fact] + public void CatDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Cat from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); + } + + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ApiResponseTests.cs new file mode 100644 index 00000000000..9c5e20b20dd --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ApiResponseTests.cs @@ -0,0 +1,83 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ApiResponse + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ApiResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ApiResponse + //private ApiResponse instance; + + public ApiResponseTests() + { + // TODO uncomment below to create an instance of ApiResponse + //instance = new ApiResponse(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ApiResponse + /// + [Fact] + public void ApiResponseInstanceTest() + { + // TODO uncomment below to test "IsType" ApiResponse + //Assert.IsType(instance); + } + + /// + /// Test the property 'Code' + /// + [Fact] + public void CodeTest() + { + // TODO unit test for the property 'Code' + } + + /// + /// Test the property 'Message' + /// + [Fact] + public void MessageTest() + { + // TODO unit test for the property 'Message' + } + + /// + /// Test the property 'Type' + /// + [Fact] + public void TypeTest() + { + // TODO unit test for the property 'Type' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AppleReqTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AppleReqTests.cs new file mode 100644 index 00000000000..6444661ac82 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AppleReqTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing AppleReq + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AppleReqTests : IDisposable + { + // TODO uncomment below to declare an instance variable for AppleReq + //private AppleReq instance; + + public AppleReqTests() + { + // TODO uncomment below to create an instance of AppleReq + //instance = new AppleReq(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of AppleReq + /// + [Fact] + public void AppleReqInstanceTest() + { + // TODO uncomment below to test "IsType" AppleReq + //Assert.IsType(instance); + } + + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + + /// + /// Test the property 'Mealy' + /// + [Fact] + public void MealyTest() + { + // TODO unit test for the property 'Mealy' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AppleTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AppleTests.cs new file mode 100644 index 00000000000..aef17eaa9d6 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AppleTests.cs @@ -0,0 +1,83 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Apple + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AppleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Apple + //private Apple instance; + + public AppleTests() + { + // TODO uncomment below to create an instance of Apple + //instance = new Apple(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Apple + /// + [Fact] + public void AppleInstanceTest() + { + // TODO uncomment below to test "IsType" Apple + //Assert.IsType(instance); + } + + /// + /// Test the property 'ColorCode' + /// + [Fact] + public void ColorCodeTest() + { + // TODO unit test for the property 'ColorCode' + } + + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + + /// + /// Test the property 'Origin' + /// + [Fact] + public void OriginTest() + { + // TODO unit test for the property 'Origin' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs new file mode 100644 index 00000000000..c9f94b65ee7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ArrayOfArrayOfNumberOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ArrayOfArrayOfNumberOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ArrayOfArrayOfNumberOnly + //private ArrayOfArrayOfNumberOnly instance; + + public ArrayOfArrayOfNumberOnlyTests() + { + // TODO uncomment below to create an instance of ArrayOfArrayOfNumberOnly + //instance = new ArrayOfArrayOfNumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ArrayOfArrayOfNumberOnly + /// + [Fact] + public void ArrayOfArrayOfNumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" ArrayOfArrayOfNumberOnly + //Assert.IsType(instance); + } + + /// + /// Test the property 'ArrayArrayNumber' + /// + [Fact] + public void ArrayArrayNumberTest() + { + // TODO unit test for the property 'ArrayArrayNumber' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ArrayOfNumberOnlyTests.cs new file mode 100644 index 00000000000..cafcec99131 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ArrayOfNumberOnlyTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ArrayOfNumberOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ArrayOfNumberOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ArrayOfNumberOnly + //private ArrayOfNumberOnly instance; + + public ArrayOfNumberOnlyTests() + { + // TODO uncomment below to create an instance of ArrayOfNumberOnly + //instance = new ArrayOfNumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ArrayOfNumberOnly + /// + [Fact] + public void ArrayOfNumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" ArrayOfNumberOnly + //Assert.IsType(instance); + } + + /// + /// Test the property 'ArrayNumber' + /// + [Fact] + public void ArrayNumberTest() + { + // TODO unit test for the property 'ArrayNumber' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ArrayTestTests.cs new file mode 100644 index 00000000000..5a0f85a63a4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ArrayTestTests.cs @@ -0,0 +1,83 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ArrayTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ArrayTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ArrayTest + //private ArrayTest instance; + + public ArrayTestTests() + { + // TODO uncomment below to create an instance of ArrayTest + //instance = new ArrayTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ArrayTest + /// + [Fact] + public void ArrayTestInstanceTest() + { + // TODO uncomment below to test "IsType" ArrayTest + //Assert.IsType(instance); + } + + /// + /// Test the property 'ArrayArrayOfInteger' + /// + [Fact] + public void ArrayArrayOfIntegerTest() + { + // TODO unit test for the property 'ArrayArrayOfInteger' + } + + /// + /// Test the property 'ArrayArrayOfModel' + /// + [Fact] + public void ArrayArrayOfModelTest() + { + // TODO unit test for the property 'ArrayArrayOfModel' + } + + /// + /// Test the property 'ArrayOfString' + /// + [Fact] + public void ArrayOfStringTest() + { + // TODO unit test for the property 'ArrayOfString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/BananaReqTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/BananaReqTests.cs new file mode 100644 index 00000000000..32c80ff0e00 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/BananaReqTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing BananaReq + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BananaReqTests : IDisposable + { + // TODO uncomment below to declare an instance variable for BananaReq + //private BananaReq instance; + + public BananaReqTests() + { + // TODO uncomment below to create an instance of BananaReq + //instance = new BananaReq(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of BananaReq + /// + [Fact] + public void BananaReqInstanceTest() + { + // TODO uncomment below to test "IsType" BananaReq + //Assert.IsType(instance); + } + + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + + /// + /// Test the property 'Sweet' + /// + [Fact] + public void SweetTest() + { + // TODO unit test for the property 'Sweet' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/BananaTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/BananaTests.cs new file mode 100644 index 00000000000..103fee92cac --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/BananaTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Banana + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BananaTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Banana + //private Banana instance; + + public BananaTests() + { + // TODO uncomment below to create an instance of Banana + //instance = new Banana(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Banana + /// + [Fact] + public void BananaInstanceTest() + { + // TODO uncomment below to test "IsType" Banana + //Assert.IsType(instance); + } + + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/BasquePigTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/BasquePigTests.cs new file mode 100644 index 00000000000..56a724ad972 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/BasquePigTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing BasquePig + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BasquePigTests : IDisposable + { + // TODO uncomment below to declare an instance variable for BasquePig + //private BasquePig instance; + + public BasquePigTests() + { + // TODO uncomment below to create an instance of BasquePig + //instance = new BasquePig(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of BasquePig + /// + [Fact] + public void BasquePigInstanceTest() + { + // TODO uncomment below to test "IsType" BasquePig + //Assert.IsType(instance); + } + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/CapitalizationTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/CapitalizationTests.cs new file mode 100644 index 00000000000..bc354b5f872 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/CapitalizationTests.cs @@ -0,0 +1,110 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Capitalization + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CapitalizationTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Capitalization + //private Capitalization instance; + + public CapitalizationTests() + { + // TODO uncomment below to create an instance of Capitalization + //instance = new Capitalization(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Capitalization + /// + [Fact] + public void CapitalizationInstanceTest() + { + // TODO uncomment below to test "IsType" Capitalization + //Assert.IsType(instance); + } + + /// + /// Test the property 'ATT_NAME' + /// + [Fact] + public void ATT_NAMETest() + { + // TODO unit test for the property 'ATT_NAME' + } + + /// + /// Test the property 'CapitalCamel' + /// + [Fact] + public void CapitalCamelTest() + { + // TODO unit test for the property 'CapitalCamel' + } + + /// + /// Test the property 'CapitalSnake' + /// + [Fact] + public void CapitalSnakeTest() + { + // TODO unit test for the property 'CapitalSnake' + } + + /// + /// Test the property 'SCAETHFlowPoints' + /// + [Fact] + public void SCAETHFlowPointsTest() + { + // TODO unit test for the property 'SCAETHFlowPoints' + } + + /// + /// Test the property 'SmallCamel' + /// + [Fact] + public void SmallCamelTest() + { + // TODO unit test for the property 'SmallCamel' + } + + /// + /// Test the property 'SmallSnake' + /// + [Fact] + public void SmallSnakeTest() + { + // TODO unit test for the property 'SmallSnake' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/CatTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/CatTests.cs new file mode 100644 index 00000000000..a8d67c5ae92 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/CatTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Cat + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CatTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Cat + //private Cat instance; + + public CatTests() + { + // TODO uncomment below to create an instance of Cat + //instance = new Cat(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Cat + /// + [Fact] + public void CatInstanceTest() + { + // TODO uncomment below to test "IsType" Cat + //Assert.IsType(instance); + } + + /// + /// Test the property 'Declawed' + /// + [Fact] + public void DeclawedTest() + { + // TODO unit test for the property 'Declawed' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/CategoryTests.cs new file mode 100644 index 00000000000..0a70d3d2f3a --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/CategoryTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Category + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CategoryTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Category + //private Category instance; + + public CategoryTests() + { + // TODO uncomment below to create an instance of Category + //instance = new Category(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Category + /// + [Fact] + public void CategoryInstanceTest() + { + // TODO uncomment below to test "IsType" Category + //Assert.IsType(instance); + } + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ChildCatTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ChildCatTests.cs new file mode 100644 index 00000000000..8db19ef4258 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ChildCatTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ChildCat + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ChildCatTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ChildCat + //private ChildCat instance; + + public ChildCatTests() + { + // TODO uncomment below to create an instance of ChildCat + //instance = new ChildCat(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ChildCat + /// + [Fact] + public void ChildCatInstanceTest() + { + // TODO uncomment below to test "IsType" ChildCat + //Assert.IsType(instance); + } + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + + /// + /// Test the property 'PetType' + /// + [Fact] + public void PetTypeTest() + { + // TODO unit test for the property 'PetType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ClassModelTests.cs new file mode 100644 index 00000000000..a661c8e22b2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ClassModelTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ClassModel + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ClassModelTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ClassModel + //private ClassModel instance; + + public ClassModelTests() + { + // TODO uncomment below to create an instance of ClassModel + //instance = new ClassModel(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ClassModel + /// + [Fact] + public void ClassModelInstanceTest() + { + // TODO uncomment below to test "IsType" ClassModel + //Assert.IsType(instance); + } + + /// + /// Test the property 'VarClass' + /// + [Fact] + public void VarClassTest() + { + // TODO unit test for the property 'VarClass' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ComplexQuadrilateralTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ComplexQuadrilateralTests.cs new file mode 100644 index 00000000000..b8ea8f0030f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ComplexQuadrilateralTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ComplexQuadrilateral + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ComplexQuadrilateralTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ComplexQuadrilateral + //private ComplexQuadrilateral instance; + + public ComplexQuadrilateralTests() + { + // TODO uncomment below to create an instance of ComplexQuadrilateral + //instance = new ComplexQuadrilateral(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ComplexQuadrilateral + /// + [Fact] + public void ComplexQuadrilateralInstanceTest() + { + // TODO uncomment below to test "IsType" ComplexQuadrilateral + //Assert.IsType(instance); + } + + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DanishPigTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DanishPigTests.cs new file mode 100644 index 00000000000..0dce8b9e5f8 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DanishPigTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing DanishPig + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DanishPigTests : IDisposable + { + // TODO uncomment below to declare an instance variable for DanishPig + //private DanishPig instance; + + public DanishPigTests() + { + // TODO uncomment below to create an instance of DanishPig + //instance = new DanishPig(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DanishPig + /// + [Fact] + public void DanishPigInstanceTest() + { + // TODO uncomment below to test "IsType" DanishPig + //Assert.IsType(instance); + } + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DateOnlyClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DateOnlyClassTests.cs new file mode 100644 index 00000000000..7c003ca6acd --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DateOnlyClassTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing DateOnlyClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DateOnlyClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for DateOnlyClass + //private DateOnlyClass instance; + + public DateOnlyClassTests() + { + // TODO uncomment below to create an instance of DateOnlyClass + //instance = new DateOnlyClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DateOnlyClass + /// + [Fact] + public void DateOnlyClassInstanceTest() + { + // TODO uncomment below to test "IsType" DateOnlyClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'DateOnlyProperty' + /// + [Fact] + public void DateOnlyPropertyTest() + { + // TODO unit test for the property 'DateOnlyProperty' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DeprecatedObjectTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DeprecatedObjectTests.cs new file mode 100644 index 00000000000..6f3b97375c9 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DeprecatedObjectTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing DeprecatedObject + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DeprecatedObjectTests : IDisposable + { + // TODO uncomment below to declare an instance variable for DeprecatedObject + //private DeprecatedObject instance; + + public DeprecatedObjectTests() + { + // TODO uncomment below to create an instance of DeprecatedObject + //instance = new DeprecatedObject(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DeprecatedObject + /// + [Fact] + public void DeprecatedObjectInstanceTest() + { + // TODO uncomment below to test "IsType" DeprecatedObject + //Assert.IsType(instance); + } + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DogTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DogTests.cs new file mode 100644 index 00000000000..dfee38a6de8 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DogTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Dog + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DogTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Dog + //private Dog instance; + + public DogTests() + { + // TODO uncomment below to create an instance of Dog + //instance = new Dog(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Dog + /// + [Fact] + public void DogInstanceTest() + { + // TODO uncomment below to test "IsType" Dog + //Assert.IsType(instance); + } + + /// + /// Test the property 'Breed' + /// + [Fact] + public void BreedTest() + { + // TODO unit test for the property 'Breed' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DrawingTests.cs new file mode 100644 index 00000000000..cb15054ec7d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DrawingTests.cs @@ -0,0 +1,92 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Drawing + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DrawingTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Drawing + //private Drawing instance; + + public DrawingTests() + { + // TODO uncomment below to create an instance of Drawing + //instance = new Drawing(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Drawing + /// + [Fact] + public void DrawingInstanceTest() + { + // TODO uncomment below to test "IsType" Drawing + //Assert.IsType(instance); + } + + /// + /// Test the property 'MainShape' + /// + [Fact] + public void MainShapeTest() + { + // TODO unit test for the property 'MainShape' + } + + /// + /// Test the property 'Shapes' + /// + [Fact] + public void ShapesTest() + { + // TODO unit test for the property 'Shapes' + } + + /// + /// Test the property 'NullableShape' + /// + [Fact] + public void NullableShapeTest() + { + // TODO unit test for the property 'NullableShape' + } + + /// + /// Test the property 'ShapeOrNull' + /// + [Fact] + public void ShapeOrNullTest() + { + // TODO unit test for the property 'ShapeOrNull' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumArraysTests.cs new file mode 100644 index 00000000000..7f5342994dd --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumArraysTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing EnumArrays + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EnumArraysTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EnumArrays + //private EnumArrays instance; + + public EnumArraysTests() + { + // TODO uncomment below to create an instance of EnumArrays + //instance = new EnumArrays(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EnumArrays + /// + [Fact] + public void EnumArraysInstanceTest() + { + // TODO uncomment below to test "IsType" EnumArrays + //Assert.IsType(instance); + } + + /// + /// Test the property 'ArrayEnum' + /// + [Fact] + public void ArrayEnumTest() + { + // TODO unit test for the property 'ArrayEnum' + } + + /// + /// Test the property 'JustSymbol' + /// + [Fact] + public void JustSymbolTest() + { + // TODO unit test for the property 'JustSymbol' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumClassTests.cs new file mode 100644 index 00000000000..fa12e28c9af --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumClassTests.cs @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing EnumClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EnumClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EnumClass + //private EnumClass instance; + + public EnumClassTests() + { + // TODO uncomment below to create an instance of EnumClass + //instance = new EnumClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EnumClass + /// + [Fact] + public void EnumClassInstanceTest() + { + // TODO uncomment below to test "IsType" EnumClass + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumTestTests.cs new file mode 100644 index 00000000000..4935820c78d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumTestTests.cs @@ -0,0 +1,137 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing EnumTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EnumTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EnumTest + //private EnumTest instance; + + public EnumTestTests() + { + // TODO uncomment below to create an instance of EnumTest + //instance = new EnumTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EnumTest + /// + [Fact] + public void EnumTestInstanceTest() + { + // TODO uncomment below to test "IsType" EnumTest + //Assert.IsType(instance); + } + + /// + /// Test the property 'EnumInteger' + /// + [Fact] + public void EnumIntegerTest() + { + // TODO unit test for the property 'EnumInteger' + } + + /// + /// Test the property 'EnumIntegerOnly' + /// + [Fact] + public void EnumIntegerOnlyTest() + { + // TODO unit test for the property 'EnumIntegerOnly' + } + + /// + /// Test the property 'EnumNumber' + /// + [Fact] + public void EnumNumberTest() + { + // TODO unit test for the property 'EnumNumber' + } + + /// + /// Test the property 'EnumString' + /// + [Fact] + public void EnumStringTest() + { + // TODO unit test for the property 'EnumString' + } + + /// + /// Test the property 'EnumStringRequired' + /// + [Fact] + public void EnumStringRequiredTest() + { + // TODO unit test for the property 'EnumStringRequired' + } + + /// + /// Test the property 'OuterEnumDefaultValue' + /// + [Fact] + public void OuterEnumDefaultValueTest() + { + // TODO unit test for the property 'OuterEnumDefaultValue' + } + + /// + /// Test the property 'OuterEnumInteger' + /// + [Fact] + public void OuterEnumIntegerTest() + { + // TODO unit test for the property 'OuterEnumInteger' + } + + /// + /// Test the property 'OuterEnumIntegerDefaultValue' + /// + [Fact] + public void OuterEnumIntegerDefaultValueTest() + { + // TODO unit test for the property 'OuterEnumIntegerDefaultValue' + } + + /// + /// Test the property 'OuterEnum' + /// + [Fact] + public void OuterEnumTest() + { + // TODO unit test for the property 'OuterEnum' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EquilateralTriangleTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EquilateralTriangleTests.cs new file mode 100644 index 00000000000..c6b3856eef8 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EquilateralTriangleTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing EquilateralTriangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EquilateralTriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EquilateralTriangle + //private EquilateralTriangle instance; + + public EquilateralTriangleTests() + { + // TODO uncomment below to create an instance of EquilateralTriangle + //instance = new EquilateralTriangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EquilateralTriangle + /// + [Fact] + public void EquilateralTriangleInstanceTest() + { + // TODO uncomment below to test "IsType" EquilateralTriangle + //Assert.IsType(instance); + } + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FileSchemaTestClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FileSchemaTestClassTests.cs new file mode 100644 index 00000000000..f9ee48b46f4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FileSchemaTestClassTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing FileSchemaTestClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FileSchemaTestClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FileSchemaTestClass + //private FileSchemaTestClass instance; + + public FileSchemaTestClassTests() + { + // TODO uncomment below to create an instance of FileSchemaTestClass + //instance = new FileSchemaTestClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FileSchemaTestClass + /// + [Fact] + public void FileSchemaTestClassInstanceTest() + { + // TODO uncomment below to test "IsType" FileSchemaTestClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'File' + /// + [Fact] + public void FileTest() + { + // TODO unit test for the property 'File' + } + + /// + /// Test the property 'Files' + /// + [Fact] + public void FilesTest() + { + // TODO unit test for the property 'Files' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FileTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FileTests.cs new file mode 100644 index 00000000000..f5fb803fc4f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FileTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing File + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FileTests : IDisposable + { + // TODO uncomment below to declare an instance variable for File + //private File instance; + + public FileTests() + { + // TODO uncomment below to create an instance of File + //instance = new File(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of File + /// + [Fact] + public void FileInstanceTest() + { + // TODO uncomment below to test "IsType" File + //Assert.IsType(instance); + } + + /// + /// Test the property 'SourceURI' + /// + [Fact] + public void SourceURITest() + { + // TODO unit test for the property 'SourceURI' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FooGetDefaultResponseTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FooGetDefaultResponseTests.cs new file mode 100644 index 00000000000..6fa740d76fd --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FooGetDefaultResponseTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing FooGetDefaultResponse + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FooGetDefaultResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FooGetDefaultResponse + //private FooGetDefaultResponse instance; + + public FooGetDefaultResponseTests() + { + // TODO uncomment below to create an instance of FooGetDefaultResponse + //instance = new FooGetDefaultResponse(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FooGetDefaultResponse + /// + [Fact] + public void FooGetDefaultResponseInstanceTest() + { + // TODO uncomment below to test "IsType" FooGetDefaultResponse + //Assert.IsType(instance); + } + + /// + /// Test the property 'VarString' + /// + [Fact] + public void VarStringTest() + { + // TODO unit test for the property 'VarString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FooTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FooTests.cs new file mode 100644 index 00000000000..6d33940a116 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FooTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Foo + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FooTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Foo + //private Foo instance; + + public FooTests() + { + // TODO uncomment below to create an instance of Foo + //instance = new Foo(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Foo + /// + [Fact] + public void FooInstanceTest() + { + // TODO uncomment below to test "IsType" Foo + //Assert.IsType(instance); + } + + /// + /// Test the property 'Bar' + /// + [Fact] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FormatTestTests.cs new file mode 100644 index 00000000000..3c21562aaf1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FormatTestTests.cs @@ -0,0 +1,227 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing FormatTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FormatTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FormatTest + //private FormatTest instance; + + public FormatTestTests() + { + // TODO uncomment below to create an instance of FormatTest + //instance = new FormatTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FormatTest + /// + [Fact] + public void FormatTestInstanceTest() + { + // TODO uncomment below to test "IsType" FormatTest + //Assert.IsType(instance); + } + + /// + /// Test the property 'Binary' + /// + [Fact] + public void BinaryTest() + { + // TODO unit test for the property 'Binary' + } + + /// + /// Test the property 'VarByte' + /// + [Fact] + public void VarByteTest() + { + // TODO unit test for the property 'VarByte' + } + + /// + /// Test the property 'Date' + /// + [Fact] + public void DateTest() + { + // TODO unit test for the property 'Date' + } + + /// + /// Test the property 'DateTime' + /// + [Fact] + public void DateTimeTest() + { + // TODO unit test for the property 'DateTime' + } + + /// + /// Test the property 'VarDecimal' + /// + [Fact] + public void VarDecimalTest() + { + // TODO unit test for the property 'VarDecimal' + } + + /// + /// Test the property 'VarDouble' + /// + [Fact] + public void VarDoubleTest() + { + // TODO unit test for the property 'VarDouble' + } + + /// + /// Test the property 'VarFloat' + /// + [Fact] + public void VarFloatTest() + { + // TODO unit test for the property 'VarFloat' + } + + /// + /// Test the property 'Int32' + /// + [Fact] + public void Int32Test() + { + // TODO unit test for the property 'Int32' + } + + /// + /// Test the property 'Int64' + /// + [Fact] + public void Int64Test() + { + // TODO unit test for the property 'Int64' + } + + /// + /// Test the property 'Integer' + /// + [Fact] + public void IntegerTest() + { + // TODO unit test for the property 'Integer' + } + + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + + /// + /// Test the property 'PatternWithBackslash' + /// + [Fact] + public void PatternWithBackslashTest() + { + // TODO unit test for the property 'PatternWithBackslash' + } + + /// + /// Test the property 'PatternWithDigits' + /// + [Fact] + public void PatternWithDigitsTest() + { + // TODO unit test for the property 'PatternWithDigits' + } + + /// + /// Test the property 'PatternWithDigitsAndDelimiter' + /// + [Fact] + public void PatternWithDigitsAndDelimiterTest() + { + // TODO unit test for the property 'PatternWithDigitsAndDelimiter' + } + + /// + /// Test the property 'VarString' + /// + [Fact] + public void VarStringTest() + { + // TODO unit test for the property 'VarString' + } + + /// + /// Test the property 'UnsignedInteger' + /// + [Fact] + public void UnsignedIntegerTest() + { + // TODO unit test for the property 'UnsignedInteger' + } + + /// + /// Test the property 'UnsignedLong' + /// + [Fact] + public void UnsignedLongTest() + { + // TODO unit test for the property 'UnsignedLong' + } + + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FruitReqTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FruitReqTests.cs new file mode 100644 index 00000000000..911eb54fb83 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FruitReqTests.cs @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing FruitReq + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FruitReqTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FruitReq + //private FruitReq instance; + + public FruitReqTests() + { + // TODO uncomment below to create an instance of FruitReq + //instance = new FruitReq(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FruitReq + /// + [Fact] + public void FruitReqInstanceTest() + { + // TODO uncomment below to test "IsType" FruitReq + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FruitTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FruitTests.cs new file mode 100644 index 00000000000..14a2959fb69 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FruitTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Fruit + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FruitTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Fruit + //private Fruit instance; + + public FruitTests() + { + // TODO uncomment below to create an instance of Fruit + //instance = new Fruit(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Fruit + /// + [Fact] + public void FruitInstanceTest() + { + // TODO uncomment below to test "IsType" Fruit + //Assert.IsType(instance); + } + + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/GmFruitTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/GmFruitTests.cs new file mode 100644 index 00000000000..dc42b78bd33 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/GmFruitTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing GmFruit + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class GmFruitTests : IDisposable + { + // TODO uncomment below to declare an instance variable for GmFruit + //private GmFruit instance; + + public GmFruitTests() + { + // TODO uncomment below to create an instance of GmFruit + //instance = new GmFruit(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of GmFruit + /// + [Fact] + public void GmFruitInstanceTest() + { + // TODO uncomment below to test "IsType" GmFruit + //Assert.IsType(instance); + } + + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/GrandparentAnimalTests.cs new file mode 100644 index 00000000000..79d5512d5bb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/GrandparentAnimalTests.cs @@ -0,0 +1,85 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing GrandparentAnimal + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class GrandparentAnimalTests : IDisposable + { + // TODO uncomment below to declare an instance variable for GrandparentAnimal + //private GrandparentAnimal instance; + + public GrandparentAnimalTests() + { + // TODO uncomment below to create an instance of GrandparentAnimal + //instance = new GrandparentAnimal(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of GrandparentAnimal + /// + [Fact] + public void GrandparentAnimalInstanceTest() + { + // TODO uncomment below to test "IsType" GrandparentAnimal + //Assert.IsType(instance); + } + + /// + /// Test deserialize a ChildCat from type ParentPet + /// + [Fact] + public void ChildCatDeserializeFromParentPetTest() + { + // TODO uncomment below to test deserialize a ChildCat from type ParentPet + //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + } + + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); + } + + /// + /// Test the property 'PetType' + /// + [Fact] + public void PetTypeTest() + { + // TODO unit test for the property 'PetType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/HasOnlyReadOnlyTests.cs new file mode 100644 index 00000000000..01cd5de5b18 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/HasOnlyReadOnlyTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing HasOnlyReadOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class HasOnlyReadOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for HasOnlyReadOnly + //private HasOnlyReadOnly instance; + + public HasOnlyReadOnlyTests() + { + // TODO uncomment below to create an instance of HasOnlyReadOnly + //instance = new HasOnlyReadOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of HasOnlyReadOnly + /// + [Fact] + public void HasOnlyReadOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" HasOnlyReadOnly + //Assert.IsType(instance); + } + + /// + /// Test the property 'Bar' + /// + [Fact] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + + /// + /// Test the property 'Foo' + /// + [Fact] + public void FooTest() + { + // TODO unit test for the property 'Foo' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/HealthCheckResultTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/HealthCheckResultTests.cs new file mode 100644 index 00000000000..89c5e2e6c7e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/HealthCheckResultTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing HealthCheckResult + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class HealthCheckResultTests : IDisposable + { + // TODO uncomment below to declare an instance variable for HealthCheckResult + //private HealthCheckResult instance; + + public HealthCheckResultTests() + { + // TODO uncomment below to create an instance of HealthCheckResult + //instance = new HealthCheckResult(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of HealthCheckResult + /// + [Fact] + public void HealthCheckResultInstanceTest() + { + // TODO uncomment below to test "IsType" HealthCheckResult + //Assert.IsType(instance); + } + + /// + /// Test the property 'NullableMessage' + /// + [Fact] + public void NullableMessageTest() + { + // TODO unit test for the property 'NullableMessage' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/IsoscelesTriangleTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/IsoscelesTriangleTests.cs new file mode 100644 index 00000000000..340168db537 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/IsoscelesTriangleTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing IsoscelesTriangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class IsoscelesTriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for IsoscelesTriangle + //private IsoscelesTriangle instance; + + public IsoscelesTriangleTests() + { + // TODO uncomment below to create an instance of IsoscelesTriangle + //instance = new IsoscelesTriangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of IsoscelesTriangle + /// + [Fact] + public void IsoscelesTriangleInstanceTest() + { + // TODO uncomment below to test "IsType" IsoscelesTriangle + //Assert.IsType(instance); + } + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ListTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ListTests.cs new file mode 100644 index 00000000000..9ad6d070448 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ListTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing List + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ListTests : IDisposable + { + // TODO uncomment below to declare an instance variable for List + //private List instance; + + public ListTests() + { + // TODO uncomment below to create an instance of List + //instance = new List(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of List + /// + [Fact] + public void ListInstanceTest() + { + // TODO uncomment below to test "IsType" List + //Assert.IsType(instance); + } + + /// + /// Test the property 'Var123List' + /// + [Fact] + public void Var123ListTest() + { + // TODO unit test for the property 'Var123List' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/LiteralStringClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/LiteralStringClassTests.cs new file mode 100644 index 00000000000..6ff0c1490fc --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/LiteralStringClassTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing LiteralStringClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class LiteralStringClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for LiteralStringClass + //private LiteralStringClass instance; + + public LiteralStringClassTests() + { + // TODO uncomment below to create an instance of LiteralStringClass + //instance = new LiteralStringClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of LiteralStringClass + /// + [Fact] + public void LiteralStringClassInstanceTest() + { + // TODO uncomment below to test "IsType" LiteralStringClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'EscapedLiteralString' + /// + [Fact] + public void EscapedLiteralStringTest() + { + // TODO unit test for the property 'EscapedLiteralString' + } + + /// + /// Test the property 'UnescapedLiteralString' + /// + [Fact] + public void UnescapedLiteralStringTest() + { + // TODO unit test for the property 'UnescapedLiteralString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/MammalTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/MammalTests.cs new file mode 100644 index 00000000000..336d28470c1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/MammalTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Mammal + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class MammalTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Mammal + //private Mammal instance; + + public MammalTests() + { + // TODO uncomment below to create an instance of Mammal + //instance = new Mammal(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Mammal + /// + [Fact] + public void MammalInstanceTest() + { + // TODO uncomment below to test "IsType" Mammal + //Assert.IsType(instance); + } + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/MapTestTests.cs new file mode 100644 index 00000000000..b7dc94927f2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/MapTestTests.cs @@ -0,0 +1,92 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing MapTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class MapTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for MapTest + //private MapTest instance; + + public MapTestTests() + { + // TODO uncomment below to create an instance of MapTest + //instance = new MapTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of MapTest + /// + [Fact] + public void MapTestInstanceTest() + { + // TODO uncomment below to test "IsType" MapTest + //Assert.IsType(instance); + } + + /// + /// Test the property 'DirectMap' + /// + [Fact] + public void DirectMapTest() + { + // TODO unit test for the property 'DirectMap' + } + + /// + /// Test the property 'IndirectMap' + /// + [Fact] + public void IndirectMapTest() + { + // TODO unit test for the property 'IndirectMap' + } + + /// + /// Test the property 'MapMapOfString' + /// + [Fact] + public void MapMapOfStringTest() + { + // TODO unit test for the property 'MapMapOfString' + } + + /// + /// Test the property 'MapOfEnumString' + /// + [Fact] + public void MapOfEnumStringTest() + { + // TODO unit test for the property 'MapOfEnumString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs new file mode 100644 index 00000000000..777d675d291 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -0,0 +1,92 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing MixedPropertiesAndAdditionalPropertiesClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class MixedPropertiesAndAdditionalPropertiesClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for MixedPropertiesAndAdditionalPropertiesClass + //private MixedPropertiesAndAdditionalPropertiesClass instance; + + public MixedPropertiesAndAdditionalPropertiesClassTests() + { + // TODO uncomment below to create an instance of MixedPropertiesAndAdditionalPropertiesClass + //instance = new MixedPropertiesAndAdditionalPropertiesClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of MixedPropertiesAndAdditionalPropertiesClass + /// + [Fact] + public void MixedPropertiesAndAdditionalPropertiesClassInstanceTest() + { + // TODO uncomment below to test "IsType" MixedPropertiesAndAdditionalPropertiesClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'DateTime' + /// + [Fact] + public void DateTimeTest() + { + // TODO unit test for the property 'DateTime' + } + + /// + /// Test the property 'Map' + /// + [Fact] + public void MapTest() + { + // TODO unit test for the property 'Map' + } + + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } + + /// + /// Test the property 'UuidWithPattern' + /// + [Fact] + public void UuidWithPatternTest() + { + // TODO unit test for the property 'UuidWithPattern' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/Model200ResponseTests.cs new file mode 100644 index 00000000000..63c513e5ca7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/Model200ResponseTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Model200Response + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class Model200ResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Model200Response + //private Model200Response instance; + + public Model200ResponseTests() + { + // TODO uncomment below to create an instance of Model200Response + //instance = new Model200Response(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Model200Response + /// + [Fact] + public void Model200ResponseInstanceTest() + { + // TODO uncomment below to test "IsType" Model200Response + //Assert.IsType(instance); + } + + /// + /// Test the property 'VarClass' + /// + [Fact] + public void VarClassTest() + { + // TODO unit test for the property 'VarClass' + } + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ModelClientTests.cs new file mode 100644 index 00000000000..22adf349710 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ModelClientTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ModelClient + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ModelClientTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ModelClient + //private ModelClient instance; + + public ModelClientTests() + { + // TODO uncomment below to create an instance of ModelClient + //instance = new ModelClient(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ModelClient + /// + [Fact] + public void ModelClientInstanceTest() + { + // TODO uncomment below to test "IsType" ModelClient + //Assert.IsType(instance); + } + + /// + /// Test the property 'VarClient' + /// + [Fact] + public void VarClientTest() + { + // TODO unit test for the property 'VarClient' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NameTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NameTests.cs new file mode 100644 index 00000000000..20bc94c727f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NameTests.cs @@ -0,0 +1,92 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Name + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NameTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Name + //private Name instance; + + public NameTests() + { + // TODO uncomment below to create an instance of Name + //instance = new Name(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Name + /// + [Fact] + public void NameInstanceTest() + { + // TODO uncomment below to test "IsType" Name + //Assert.IsType(instance); + } + + /// + /// Test the property 'VarName' + /// + [Fact] + public void VarNameTest() + { + // TODO unit test for the property 'VarName' + } + + /// + /// Test the property 'Property' + /// + [Fact] + public void PropertyTest() + { + // TODO unit test for the property 'Property' + } + + /// + /// Test the property 'SnakeCase' + /// + [Fact] + public void SnakeCaseTest() + { + // TODO unit test for the property 'SnakeCase' + } + + /// + /// Test the property 'Var123Number' + /// + [Fact] + public void Var123NumberTest() + { + // TODO unit test for the property 'Var123Number' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NotificationtestGetElementsV1ResponseMPayloadTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NotificationtestGetElementsV1ResponseMPayloadTests.cs new file mode 100644 index 00000000000..0ae9a47601a --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NotificationtestGetElementsV1ResponseMPayloadTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing NotificationtestGetElementsV1ResponseMPayload + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NotificationtestGetElementsV1ResponseMPayloadTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NotificationtestGetElementsV1ResponseMPayload + //private NotificationtestGetElementsV1ResponseMPayload instance; + + public NotificationtestGetElementsV1ResponseMPayloadTests() + { + // TODO uncomment below to create an instance of NotificationtestGetElementsV1ResponseMPayload + //instance = new NotificationtestGetElementsV1ResponseMPayload(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NotificationtestGetElementsV1ResponseMPayload + /// + [Fact] + public void NotificationtestGetElementsV1ResponseMPayloadInstanceTest() + { + // TODO uncomment below to test "IsType" NotificationtestGetElementsV1ResponseMPayload + //Assert.IsType(instance); + } + + /// + /// Test the property 'AObjVariableobject' + /// + [Fact] + public void AObjVariableobjectTest() + { + // TODO unit test for the property 'AObjVariableobject' + } + + /// + /// Test the property 'PkiNotificationtestID' + /// + [Fact] + public void PkiNotificationtestIDTest() + { + // TODO unit test for the property 'PkiNotificationtestID' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableClassTests.cs new file mode 100644 index 00000000000..54ae0050d22 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableClassTests.cs @@ -0,0 +1,164 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing NullableClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NullableClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NullableClass + //private NullableClass instance; + + public NullableClassTests() + { + // TODO uncomment below to create an instance of NullableClass + //instance = new NullableClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NullableClass + /// + [Fact] + public void NullableClassInstanceTest() + { + // TODO uncomment below to test "IsType" NullableClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'ArrayItemsNullable' + /// + [Fact] + public void ArrayItemsNullableTest() + { + // TODO unit test for the property 'ArrayItemsNullable' + } + + /// + /// Test the property 'ObjectItemsNullable' + /// + [Fact] + public void ObjectItemsNullableTest() + { + // TODO unit test for the property 'ObjectItemsNullable' + } + + /// + /// Test the property 'ArrayAndItemsNullableProp' + /// + [Fact] + public void ArrayAndItemsNullablePropTest() + { + // TODO unit test for the property 'ArrayAndItemsNullableProp' + } + + /// + /// Test the property 'ArrayNullableProp' + /// + [Fact] + public void ArrayNullablePropTest() + { + // TODO unit test for the property 'ArrayNullableProp' + } + + /// + /// Test the property 'BooleanProp' + /// + [Fact] + public void BooleanPropTest() + { + // TODO unit test for the property 'BooleanProp' + } + + /// + /// Test the property 'DateProp' + /// + [Fact] + public void DatePropTest() + { + // TODO unit test for the property 'DateProp' + } + + /// + /// Test the property 'DatetimeProp' + /// + [Fact] + public void DatetimePropTest() + { + // TODO unit test for the property 'DatetimeProp' + } + + /// + /// Test the property 'IntegerProp' + /// + [Fact] + public void IntegerPropTest() + { + // TODO unit test for the property 'IntegerProp' + } + + /// + /// Test the property 'NumberProp' + /// + [Fact] + public void NumberPropTest() + { + // TODO unit test for the property 'NumberProp' + } + + /// + /// Test the property 'ObjectAndItemsNullableProp' + /// + [Fact] + public void ObjectAndItemsNullablePropTest() + { + // TODO unit test for the property 'ObjectAndItemsNullableProp' + } + + /// + /// Test the property 'ObjectNullableProp' + /// + [Fact] + public void ObjectNullablePropTest() + { + // TODO unit test for the property 'ObjectNullableProp' + } + + /// + /// Test the property 'StringProp' + /// + [Fact] + public void StringPropTest() + { + // TODO unit test for the property 'StringProp' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableGuidClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableGuidClassTests.cs new file mode 100644 index 00000000000..06d6e9484cb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableGuidClassTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing NullableGuidClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NullableGuidClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NullableGuidClass + //private NullableGuidClass instance; + + public NullableGuidClassTests() + { + // TODO uncomment below to create an instance of NullableGuidClass + //instance = new NullableGuidClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NullableGuidClass + /// + [Fact] + public void NullableGuidClassInstanceTest() + { + // TODO uncomment below to test "IsType" NullableGuidClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableShapeTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableShapeTests.cs new file mode 100644 index 00000000000..9cbafbaa5bb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableShapeTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing NullableShape + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NullableShapeTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NullableShape + //private NullableShape instance; + + public NullableShapeTests() + { + // TODO uncomment below to create an instance of NullableShape + //instance = new NullableShape(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NullableShape + /// + [Fact] + public void NullableShapeInstanceTest() + { + // TODO uncomment below to test "IsType" NullableShape + //Assert.IsType(instance); + } + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NumberOnlyTests.cs new file mode 100644 index 00000000000..702137413f7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NumberOnlyTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing NumberOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NumberOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NumberOnly + //private NumberOnly instance; + + public NumberOnlyTests() + { + // TODO uncomment below to create an instance of NumberOnly + //instance = new NumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NumberOnly + /// + [Fact] + public void NumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" NumberOnly + //Assert.IsType(instance); + } + + /// + /// Test the property 'JustNumber' + /// + [Fact] + public void JustNumberTest() + { + // TODO unit test for the property 'JustNumber' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ObjectWithDeprecatedFieldsTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ObjectWithDeprecatedFieldsTests.cs new file mode 100644 index 00000000000..718fe3006f2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ObjectWithDeprecatedFieldsTests.cs @@ -0,0 +1,92 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ObjectWithDeprecatedFields + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ObjectWithDeprecatedFieldsTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ObjectWithDeprecatedFields + //private ObjectWithDeprecatedFields instance; + + public ObjectWithDeprecatedFieldsTests() + { + // TODO uncomment below to create an instance of ObjectWithDeprecatedFields + //instance = new ObjectWithDeprecatedFields(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ObjectWithDeprecatedFields + /// + [Fact] + public void ObjectWithDeprecatedFieldsInstanceTest() + { + // TODO uncomment below to test "IsType" ObjectWithDeprecatedFields + //Assert.IsType(instance); + } + + /// + /// Test the property 'Bars' + /// + [Fact] + public void BarsTest() + { + // TODO unit test for the property 'Bars' + } + + /// + /// Test the property 'DeprecatedRef' + /// + [Fact] + public void DeprecatedRefTest() + { + // TODO unit test for the property 'DeprecatedRef' + } + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OneOfStringTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OneOfStringTests.cs new file mode 100644 index 00000000000..8973c4b4a8b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OneOfStringTests.cs @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing OneOfString + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OneOfStringTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OneOfString + //private OneOfString instance; + + public OneOfStringTests() + { + // TODO uncomment below to create an instance of OneOfString + //instance = new OneOfString(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OneOfString + /// + [Fact] + public void OneOfStringInstanceTest() + { + // TODO uncomment below to test "IsType" OneOfString + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OrderTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OrderTests.cs new file mode 100644 index 00000000000..cab96781726 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OrderTests.cs @@ -0,0 +1,110 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Order + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OrderTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Order + //private Order instance; + + public OrderTests() + { + // TODO uncomment below to create an instance of Order + //instance = new Order(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Order + /// + [Fact] + public void OrderInstanceTest() + { + // TODO uncomment below to test "IsType" Order + //Assert.IsType(instance); + } + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + + /// + /// Test the property 'PetId' + /// + [Fact] + public void PetIdTest() + { + // TODO unit test for the property 'PetId' + } + + /// + /// Test the property 'Quantity' + /// + [Fact] + public void QuantityTest() + { + // TODO unit test for the property 'Quantity' + } + + /// + /// Test the property 'ShipDate' + /// + [Fact] + public void ShipDateTest() + { + // TODO unit test for the property 'ShipDate' + } + + /// + /// Test the property 'Status' + /// + [Fact] + public void StatusTest() + { + // TODO unit test for the property 'Status' + } + + /// + /// Test the property 'Complete' + /// + [Fact] + public void CompleteTest() + { + // TODO unit test for the property 'Complete' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterCompositeTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterCompositeTests.cs new file mode 100644 index 00000000000..01cf2d510e7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterCompositeTests.cs @@ -0,0 +1,83 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing OuterComposite + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterCompositeTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterComposite + //private OuterComposite instance; + + public OuterCompositeTests() + { + // TODO uncomment below to create an instance of OuterComposite + //instance = new OuterComposite(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterComposite + /// + [Fact] + public void OuterCompositeInstanceTest() + { + // TODO uncomment below to test "IsType" OuterComposite + //Assert.IsType(instance); + } + + /// + /// Test the property 'MyBoolean' + /// + [Fact] + public void MyBooleanTest() + { + // TODO unit test for the property 'MyBoolean' + } + + /// + /// Test the property 'MyNumber' + /// + [Fact] + public void MyNumberTest() + { + // TODO unit test for the property 'MyNumber' + } + + /// + /// Test the property 'MyString' + /// + [Fact] + public void MyStringTest() + { + // TODO unit test for the property 'MyString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumDefaultValueTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumDefaultValueTests.cs new file mode 100644 index 00000000000..5894d6b7c76 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumDefaultValueTests.cs @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing OuterEnumDefaultValue + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumDefaultValueTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnumDefaultValue + //private OuterEnumDefaultValue instance; + + public OuterEnumDefaultValueTests() + { + // TODO uncomment below to create an instance of OuterEnumDefaultValue + //instance = new OuterEnumDefaultValue(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnumDefaultValue + /// + [Fact] + public void OuterEnumDefaultValueInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnumDefaultValue + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumIntegerDefaultValueTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumIntegerDefaultValueTests.cs new file mode 100644 index 00000000000..a76b4c40f29 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumIntegerDefaultValueTests.cs @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing OuterEnumIntegerDefaultValue + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumIntegerDefaultValueTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnumIntegerDefaultValue + //private OuterEnumIntegerDefaultValue instance; + + public OuterEnumIntegerDefaultValueTests() + { + // TODO uncomment below to create an instance of OuterEnumIntegerDefaultValue + //instance = new OuterEnumIntegerDefaultValue(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnumIntegerDefaultValue + /// + [Fact] + public void OuterEnumIntegerDefaultValueInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnumIntegerDefaultValue + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumIntegerTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumIntegerTests.cs new file mode 100644 index 00000000000..453fb21a17b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumIntegerTests.cs @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing OuterEnumInteger + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumIntegerTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnumInteger + //private OuterEnumInteger instance; + + public OuterEnumIntegerTests() + { + // TODO uncomment below to create an instance of OuterEnumInteger + //instance = new OuterEnumInteger(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnumInteger + /// + [Fact] + public void OuterEnumIntegerInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnumInteger + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumTestTests.cs new file mode 100644 index 00000000000..5801f387435 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumTestTests.cs @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing OuterEnumTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnumTest + //private OuterEnumTest instance; + + public OuterEnumTestTests() + { + // TODO uncomment below to create an instance of OuterEnumTest + //instance = new OuterEnumTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnumTest + /// + [Fact] + public void OuterEnumTestInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnumTest + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumTests.cs new file mode 100644 index 00000000000..7719c1bb4c2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OuterEnumTests.cs @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing OuterEnum + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnum + //private OuterEnum instance; + + public OuterEnumTests() + { + // TODO uncomment below to create an instance of OuterEnum + //instance = new OuterEnum(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnum + /// + [Fact] + public void OuterEnumInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnum + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ParentPetTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ParentPetTests.cs new file mode 100644 index 00000000000..926e5da4316 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ParentPetTests.cs @@ -0,0 +1,66 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ParentPet + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ParentPetTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ParentPet + //private ParentPet instance; + + public ParentPetTests() + { + // TODO uncomment below to create an instance of ParentPet + //instance = new ParentPet(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ParentPet + /// + [Fact] + public void ParentPetInstanceTest() + { + // TODO uncomment below to test "IsType" ParentPet + //Assert.IsType(instance); + } + + /// + /// Test deserialize a ChildCat from type ParentPet + /// + [Fact] + public void ChildCatDeserializeFromParentPetTest() + { + // TODO uncomment below to test deserialize a ChildCat from type ParentPet + //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PetTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PetTests.cs new file mode 100644 index 00000000000..750f806d61d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PetTests.cs @@ -0,0 +1,110 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Pet + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PetTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Pet + //private Pet instance; + + public PetTests() + { + // TODO uncomment below to create an instance of Pet + //instance = new Pet(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Pet + /// + [Fact] + public void PetInstanceTest() + { + // TODO uncomment below to test "IsType" Pet + //Assert.IsType(instance); + } + + /// + /// Test the property 'Category' + /// + [Fact] + public void CategoryTest() + { + // TODO unit test for the property 'Category' + } + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + + /// + /// Test the property 'PhotoUrls' + /// + [Fact] + public void PhotoUrlsTest() + { + // TODO unit test for the property 'PhotoUrls' + } + + /// + /// Test the property 'Status' + /// + [Fact] + public void StatusTest() + { + // TODO unit test for the property 'Status' + } + + /// + /// Test the property 'Tags' + /// + [Fact] + public void TagsTest() + { + // TODO unit test for the property 'Tags' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PigTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PigTests.cs new file mode 100644 index 00000000000..76819c50df6 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PigTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Pig + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PigTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Pig + //private Pig instance; + + public PigTests() + { + // TODO uncomment below to create an instance of Pig + //instance = new Pig(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Pig + /// + [Fact] + public void PigInstanceTest() + { + // TODO uncomment below to test "IsType" Pig + //Assert.IsType(instance); + } + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PolymorphicPropertyTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PolymorphicPropertyTests.cs new file mode 100644 index 00000000000..f142c70d150 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PolymorphicPropertyTests.cs @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing PolymorphicProperty + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PolymorphicPropertyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for PolymorphicProperty + //private PolymorphicProperty instance; + + public PolymorphicPropertyTests() + { + // TODO uncomment below to create an instance of PolymorphicProperty + //instance = new PolymorphicProperty(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of PolymorphicProperty + /// + [Fact] + public void PolymorphicPropertyInstanceTest() + { + // TODO uncomment below to test "IsType" PolymorphicProperty + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/QuadrilateralInterfaceTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/QuadrilateralInterfaceTests.cs new file mode 100644 index 00000000000..de38453ff45 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/QuadrilateralInterfaceTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing QuadrilateralInterface + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class QuadrilateralInterfaceTests : IDisposable + { + // TODO uncomment below to declare an instance variable for QuadrilateralInterface + //private QuadrilateralInterface instance; + + public QuadrilateralInterfaceTests() + { + // TODO uncomment below to create an instance of QuadrilateralInterface + //instance = new QuadrilateralInterface(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of QuadrilateralInterface + /// + [Fact] + public void QuadrilateralInterfaceInstanceTest() + { + // TODO uncomment below to test "IsType" QuadrilateralInterface + //Assert.IsType(instance); + } + + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/QuadrilateralTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/QuadrilateralTests.cs new file mode 100644 index 00000000000..32dc6ee97c2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/QuadrilateralTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Quadrilateral + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class QuadrilateralTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Quadrilateral + //private Quadrilateral instance; + + public QuadrilateralTests() + { + // TODO uncomment below to create an instance of Quadrilateral + //instance = new Quadrilateral(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Quadrilateral + /// + [Fact] + public void QuadrilateralInstanceTest() + { + // TODO uncomment below to test "IsType" Quadrilateral + //Assert.IsType(instance); + } + + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ReadOnlyFirstTests.cs new file mode 100644 index 00000000000..68773d8908f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ReadOnlyFirstTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ReadOnlyFirst + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ReadOnlyFirstTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ReadOnlyFirst + //private ReadOnlyFirst instance; + + public ReadOnlyFirstTests() + { + // TODO uncomment below to create an instance of ReadOnlyFirst + //instance = new ReadOnlyFirst(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ReadOnlyFirst + /// + [Fact] + public void ReadOnlyFirstInstanceTest() + { + // TODO uncomment below to test "IsType" ReadOnlyFirst + //Assert.IsType(instance); + } + + /// + /// Test the property 'Bar' + /// + [Fact] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + + /// + /// Test the property 'Baz' + /// + [Fact] + public void BazTest() + { + // TODO unit test for the property 'Baz' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ReturnTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ReturnTests.cs new file mode 100644 index 00000000000..5d7eada1292 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ReturnTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Return + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ReturnTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Return + //private Return instance; + + public ReturnTests() + { + // TODO uncomment below to create an instance of Return + //instance = new Return(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Return + /// + [Fact] + public void ReturnInstanceTest() + { + // TODO uncomment below to test "IsType" Return + //Assert.IsType(instance); + } + + /// + /// Test the property 'VarReturn' + /// + [Fact] + public void VarReturnTest() + { + // TODO unit test for the property 'VarReturn' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/RolesReportsHashRoleTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/RolesReportsHashRoleTests.cs new file mode 100644 index 00000000000..4e74ff59d87 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/RolesReportsHashRoleTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing RolesReportsHashRole + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RolesReportsHashRoleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RolesReportsHashRole + //private RolesReportsHashRole instance; + + public RolesReportsHashRoleTests() + { + // TODO uncomment below to create an instance of RolesReportsHashRole + //instance = new RolesReportsHashRole(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RolesReportsHashRole + /// + [Fact] + public void RolesReportsHashRoleInstanceTest() + { + // TODO uncomment below to test "IsType" RolesReportsHashRole + //Assert.IsType(instance); + } + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/RolesReportsHashTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/RolesReportsHashTests.cs new file mode 100644 index 00000000000..88c06bff69c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/RolesReportsHashTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing RolesReportsHash + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RolesReportsHashTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RolesReportsHash + //private RolesReportsHash instance; + + public RolesReportsHashTests() + { + // TODO uncomment below to create an instance of RolesReportsHash + //instance = new RolesReportsHash(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RolesReportsHash + /// + [Fact] + public void RolesReportsHashInstanceTest() + { + // TODO uncomment below to test "IsType" RolesReportsHash + //Assert.IsType(instance); + } + + /// + /// Test the property 'Role' + /// + [Fact] + public void RoleTest() + { + // TODO unit test for the property 'Role' + } + + /// + /// Test the property 'RoleUuid' + /// + [Fact] + public void RoleUuidTest() + { + // TODO unit test for the property 'RoleUuid' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ScaleneTriangleTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ScaleneTriangleTests.cs new file mode 100644 index 00000000000..de7c5f855d4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ScaleneTriangleTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ScaleneTriangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ScaleneTriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ScaleneTriangle + //private ScaleneTriangle instance; + + public ScaleneTriangleTests() + { + // TODO uncomment below to create an instance of ScaleneTriangle + //instance = new ScaleneTriangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ScaleneTriangle + /// + [Fact] + public void ScaleneTriangleInstanceTest() + { + // TODO uncomment below to test "IsType" ScaleneTriangle + //Assert.IsType(instance); + } + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ShapeInterfaceTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ShapeInterfaceTests.cs new file mode 100644 index 00000000000..d8fe659143b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ShapeInterfaceTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ShapeInterface + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ShapeInterfaceTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ShapeInterface + //private ShapeInterface instance; + + public ShapeInterfaceTests() + { + // TODO uncomment below to create an instance of ShapeInterface + //instance = new ShapeInterface(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ShapeInterface + /// + [Fact] + public void ShapeInterfaceInstanceTest() + { + // TODO uncomment below to test "IsType" ShapeInterface + //Assert.IsType(instance); + } + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ShapeOrNullTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ShapeOrNullTests.cs new file mode 100644 index 00000000000..fa50d3b1455 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ShapeOrNullTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ShapeOrNull + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ShapeOrNullTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ShapeOrNull + //private ShapeOrNull instance; + + public ShapeOrNullTests() + { + // TODO uncomment below to create an instance of ShapeOrNull + //instance = new ShapeOrNull(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ShapeOrNull + /// + [Fact] + public void ShapeOrNullInstanceTest() + { + // TODO uncomment below to test "IsType" ShapeOrNull + //Assert.IsType(instance); + } + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ShapeTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ShapeTests.cs new file mode 100644 index 00000000000..391ef539676 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ShapeTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Shape + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ShapeTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Shape + //private Shape instance; + + public ShapeTests() + { + // TODO uncomment below to create an instance of Shape + //instance = new Shape(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Shape + /// + [Fact] + public void ShapeInstanceTest() + { + // TODO uncomment below to test "IsType" Shape + //Assert.IsType(instance); + } + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/SimpleQuadrilateralTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/SimpleQuadrilateralTests.cs new file mode 100644 index 00000000000..8574a053f29 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/SimpleQuadrilateralTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing SimpleQuadrilateral + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class SimpleQuadrilateralTests : IDisposable + { + // TODO uncomment below to declare an instance variable for SimpleQuadrilateral + //private SimpleQuadrilateral instance; + + public SimpleQuadrilateralTests() + { + // TODO uncomment below to create an instance of SimpleQuadrilateral + //instance = new SimpleQuadrilateral(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of SimpleQuadrilateral + /// + [Fact] + public void SimpleQuadrilateralInstanceTest() + { + // TODO uncomment below to test "IsType" SimpleQuadrilateral + //Assert.IsType(instance); + } + + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/SpecialModelNameTests.cs new file mode 100644 index 00000000000..043740b1cc9 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/SpecialModelNameTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing SpecialModelName + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class SpecialModelNameTests : IDisposable + { + // TODO uncomment below to declare an instance variable for SpecialModelName + //private SpecialModelName instance; + + public SpecialModelNameTests() + { + // TODO uncomment below to create an instance of SpecialModelName + //instance = new SpecialModelName(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of SpecialModelName + /// + [Fact] + public void SpecialModelNameInstanceTest() + { + // TODO uncomment below to test "IsType" SpecialModelName + //Assert.IsType(instance); + } + + /// + /// Test the property 'VarSpecialModelName' + /// + [Fact] + public void VarSpecialModelNameTest() + { + // TODO unit test for the property 'VarSpecialModelName' + } + + /// + /// Test the property 'SpecialPropertyName' + /// + [Fact] + public void SpecialPropertyNameTest() + { + // TODO unit test for the property 'SpecialPropertyName' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TagTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TagTests.cs new file mode 100644 index 00000000000..6e4ae1ec9a2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TagTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Tag + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TagTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Tag + //private Tag instance; + + public TagTests() + { + // TODO uncomment below to create an instance of Tag + //instance = new Tag(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Tag + /// + [Fact] + public void TagInstanceTest() + { + // TODO uncomment below to test "IsType" Tag + //Assert.IsType(instance); + } + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TestCollectionEndingWithWordListObjectTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TestCollectionEndingWithWordListObjectTests.cs new file mode 100644 index 00000000000..6f2b896b440 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TestCollectionEndingWithWordListObjectTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing TestCollectionEndingWithWordListObject + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TestCollectionEndingWithWordListObjectTests : IDisposable + { + // TODO uncomment below to declare an instance variable for TestCollectionEndingWithWordListObject + //private TestCollectionEndingWithWordListObject instance; + + public TestCollectionEndingWithWordListObjectTests() + { + // TODO uncomment below to create an instance of TestCollectionEndingWithWordListObject + //instance = new TestCollectionEndingWithWordListObject(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of TestCollectionEndingWithWordListObject + /// + [Fact] + public void TestCollectionEndingWithWordListObjectInstanceTest() + { + // TODO uncomment below to test "IsType" TestCollectionEndingWithWordListObject + //Assert.IsType(instance); + } + + /// + /// Test the property 'TestCollectionEndingWithWordList' + /// + [Fact] + public void TestCollectionEndingWithWordListTest() + { + // TODO unit test for the property 'TestCollectionEndingWithWordList' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TestCollectionEndingWithWordListTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TestCollectionEndingWithWordListTests.cs new file mode 100644 index 00000000000..816ce50a0f8 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TestCollectionEndingWithWordListTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing TestCollectionEndingWithWordList + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TestCollectionEndingWithWordListTests : IDisposable + { + // TODO uncomment below to declare an instance variable for TestCollectionEndingWithWordList + //private TestCollectionEndingWithWordList instance; + + public TestCollectionEndingWithWordListTests() + { + // TODO uncomment below to create an instance of TestCollectionEndingWithWordList + //instance = new TestCollectionEndingWithWordList(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of TestCollectionEndingWithWordList + /// + [Fact] + public void TestCollectionEndingWithWordListInstanceTest() + { + // TODO uncomment below to test "IsType" TestCollectionEndingWithWordList + //Assert.IsType(instance); + } + + /// + /// Test the property 'Value' + /// + [Fact] + public void ValueTest() + { + // TODO unit test for the property 'Value' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TriangleInterfaceTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TriangleInterfaceTests.cs new file mode 100644 index 00000000000..491c9dafb9e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TriangleInterfaceTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing TriangleInterface + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TriangleInterfaceTests : IDisposable + { + // TODO uncomment below to declare an instance variable for TriangleInterface + //private TriangleInterface instance; + + public TriangleInterfaceTests() + { + // TODO uncomment below to create an instance of TriangleInterface + //instance = new TriangleInterface(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of TriangleInterface + /// + [Fact] + public void TriangleInterfaceInstanceTest() + { + // TODO uncomment below to test "IsType" TriangleInterface + //Assert.IsType(instance); + } + + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TriangleTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TriangleTests.cs new file mode 100644 index 00000000000..79f0001419a --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/TriangleTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Triangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Triangle + //private Triangle instance; + + public TriangleTests() + { + // TODO uncomment below to create an instance of Triangle + //instance = new Triangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Triangle + /// + [Fact] + public void TriangleInstanceTest() + { + // TODO uncomment below to test "IsType" Triangle + //Assert.IsType(instance); + } + + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/UserTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/UserTests.cs new file mode 100644 index 00000000000..d2e4d27334d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/UserTests.cs @@ -0,0 +1,164 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing User + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class UserTests : IDisposable + { + // TODO uncomment below to declare an instance variable for User + //private User instance; + + public UserTests() + { + // TODO uncomment below to create an instance of User + //instance = new User(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of User + /// + [Fact] + public void UserInstanceTest() + { + // TODO uncomment below to test "IsType" User + //Assert.IsType(instance); + } + + /// + /// Test the property 'Email' + /// + [Fact] + public void EmailTest() + { + // TODO unit test for the property 'Email' + } + + /// + /// Test the property 'FirstName' + /// + [Fact] + public void FirstNameTest() + { + // TODO unit test for the property 'FirstName' + } + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + + /// + /// Test the property 'LastName' + /// + [Fact] + public void LastNameTest() + { + // TODO unit test for the property 'LastName' + } + + /// + /// Test the property 'ObjectWithNoDeclaredProps' + /// + [Fact] + public void ObjectWithNoDeclaredPropsTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredProps' + } + + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + + /// + /// Test the property 'Phone' + /// + [Fact] + public void PhoneTest() + { + // TODO unit test for the property 'Phone' + } + + /// + /// Test the property 'UserStatus' + /// + [Fact] + public void UserStatusTest() + { + // TODO unit test for the property 'UserStatus' + } + + /// + /// Test the property 'Username' + /// + [Fact] + public void UsernameTest() + { + // TODO unit test for the property 'Username' + } + + /// + /// Test the property 'AnyTypeProp' + /// + [Fact] + public void AnyTypePropTest() + { + // TODO unit test for the property 'AnyTypeProp' + } + + /// + /// Test the property 'AnyTypePropNullable' + /// + [Fact] + public void AnyTypePropNullableTest() + { + // TODO unit test for the property 'AnyTypePropNullable' + } + + /// + /// Test the property 'ObjectWithNoDeclaredPropsNullable' + /// + [Fact] + public void ObjectWithNoDeclaredPropsNullableTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/WhaleTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/WhaleTests.cs new file mode 100644 index 00000000000..3485c7389b2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/WhaleTests.cs @@ -0,0 +1,83 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Whale + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class WhaleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Whale + //private Whale instance; + + public WhaleTests() + { + // TODO uncomment below to create an instance of Whale + //instance = new Whale(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Whale + /// + [Fact] + public void WhaleInstanceTest() + { + // TODO uncomment below to test "IsType" Whale + //Assert.IsType(instance); + } + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + /// + /// Test the property 'HasBaleen' + /// + [Fact] + public void HasBaleenTest() + { + // TODO unit test for the property 'HasBaleen' + } + + /// + /// Test the property 'HasTeeth' + /// + [Fact] + public void HasTeethTest() + { + // TODO unit test for the property 'HasTeeth' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ZebraTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ZebraTests.cs new file mode 100644 index 00000000000..ef9d6305c7b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ZebraTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing Zebra + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ZebraTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Zebra + //private Zebra instance; + + public ZebraTests() + { + // TODO uncomment below to create an instance of Zebra + //instance = new Zebra(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Zebra + /// + [Fact] + public void ZebraInstanceTest() + { + // TODO uncomment below to test "IsType" Zebra + //Assert.IsType(instance); + } + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + /// + /// Test the property 'Type' + /// + [Fact] + public void TypeTest() + { + // TODO unit test for the property 'Type' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ZeroBasedEnumClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ZeroBasedEnumClassTests.cs new file mode 100644 index 00000000000..83acf9e32fe --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ZeroBasedEnumClassTests.cs @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ZeroBasedEnumClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ZeroBasedEnumClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ZeroBasedEnumClass + //private ZeroBasedEnumClass instance; + + public ZeroBasedEnumClassTests() + { + // TODO uncomment below to create an instance of ZeroBasedEnumClass + //instance = new ZeroBasedEnumClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ZeroBasedEnumClass + /// + [Fact] + public void ZeroBasedEnumClassInstanceTest() + { + // TODO uncomment below to test "IsType" ZeroBasedEnumClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'ZeroBasedEnum' + /// + [Fact] + public void ZeroBasedEnumTest() + { + // TODO unit test for the property 'ZeroBasedEnum' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ZeroBasedEnumTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ZeroBasedEnumTests.cs new file mode 100644 index 00000000000..acd13767aaf --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/ZeroBasedEnumTests.cs @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing ZeroBasedEnum + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ZeroBasedEnumTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ZeroBasedEnum + //private ZeroBasedEnum instance; + + public ZeroBasedEnumTests() + { + // TODO uncomment below to create an instance of ZeroBasedEnum + //instance = new ZeroBasedEnum(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ZeroBasedEnum + /// + [Fact] + public void ZeroBasedEnumInstanceTest() + { + // TODO uncomment below to test "IsType" ZeroBasedEnum + //Assert.IsType(instance); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/README.md new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/UseSourceGeneration.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/UseSourceGeneration.Test.csproj new file mode 100644 index 00000000000..eb88d9d320f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/UseSourceGeneration.Test.csproj @@ -0,0 +1,20 @@ + + + + UseSourceGeneration.Test + UseSourceGeneration.Test + net7.0 + false + enable + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/AnotherFakeApi.cs new file mode 100644 index 00000000000..cf6063040ff --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/AnotherFakeApi.cs @@ -0,0 +1,312 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using UseSourceGeneration.Client; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + +namespace UseSourceGeneration.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IAnotherFakeApi : IApi + { + /// + /// The class containing the events + /// + AnotherFakeApiEvents Events { get; } + + /// + /// To test special tags + /// + /// + /// To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<ModelClient>> + Task> Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default); + + /// + /// To test special tags + /// + /// + /// To test special tags and operation ID starting with number + /// + /// client model + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>ModelClient>?> + Task?> Call123TestSpecialTagsOrDefaultAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public class AnotherFakeApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler>? OnCall123TestSpecialTags; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCall123TestSpecialTags; + + internal void ExecuteOnCall123TestSpecialTags(ApiResponse apiResponse) + { + OnCall123TestSpecialTags?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCall123TestSpecialTags(Exception exception) + { + OnErrorCall123TestSpecialTags?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class AnotherFakeApi : IAnotherFakeApi + { + private JsonSerializerOptions _jsonSerializerOptions; + private ModelClientDeserializationContext _modelClientDeserializationContext; + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public AnotherFakeApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider ApiKeyProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BearerTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BasicTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider HttpSignatureTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public AnotherFakeApi(ILogger logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AnotherFakeApiEvents anotherFakeApiEvents, + ModelClientDeserializationContext modelClientDeserializationContext, + TokenProvider apiKeyProvider, + TokenProvider bearerTokenProvider, + TokenProvider basicTokenProvider, + TokenProvider httpSignatureTokenProvider, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + _modelClientDeserializationContext = modelClientDeserializationContext; + Logger = logger; + HttpClient = httpClient; + Events = anotherFakeApiEvents; + ApiKeyProvider = apiKeyProvider; + BearerTokenProvider = bearerTokenProvider; + BasicTokenProvider = basicTokenProvider; + HttpSignatureTokenProvider = httpSignatureTokenProvider; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCall123TestSpecialTags(ModelClient modelClient); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCall123TestSpecialTags(ModelClient modelClient) + { + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCall123TestSpecialTagsDefaultImplementation(ApiResponse apiResponseLocalVar, ModelClient modelClient) + { + bool suppressDefaultLog = false; + AfterCall123TestSpecialTags(ref suppressDefaultLog, apiResponseLocalVar, modelClient); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCall123TestSpecialTags(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, ModelClient modelClient); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCall123TestSpecialTagsDefaultImplementation(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + bool suppressDefaultLog = false; + OnErrorCall123TestSpecialTags(ref suppressDefaultLog, exception, pathFormat, path, modelClient); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCall123TestSpecialTags(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, ModelClient modelClient); + + /// + /// To test special tags To test special tags and operation ID starting with number + /// + /// client model + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> Call123TestSpecialTagsOrDefaultAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await Call123TestSpecialTagsAsync(modelClient, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// To test special tags To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCall123TestSpecialTags(modelClient); + + FormatCall123TestSpecialTags(modelClient); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/another-fake/dummy"; + + httpRequestMessageLocalVar.Content = (modelClient as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/another-fake/dummy", requestedAtLocalVar, _modelClientDeserializationContext.ModelClient); + + AfterCall123TestSpecialTagsDefaultImplementation(apiResponseLocalVar, modelClient); + + Events.ExecuteOnCall123TestSpecialTags(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCall123TestSpecialTagsDefaultImplementation(e, "/another-fake/dummy", uriBuilderLocalVar.Path, modelClient); + Events.ExecuteOnErrorCall123TestSpecialTags(e); + throw; + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/DefaultApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/DefaultApi.cs new file mode 100644 index 00000000000..6a7814a941d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/DefaultApi.cs @@ -0,0 +1,936 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using UseSourceGeneration.Client; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + +namespace UseSourceGeneration.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IDefaultApi : IApi + { + /// + /// The class containing the events + /// + DefaultApiEvents Events { get; } + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<FooGetDefaultResponse>> + Task> FooGetAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>FooGetDefaultResponse>?> + Task?> FooGetOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> GetCountryAsync(string country, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> GetCountryOrDefaultAsync(string country, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Hello + /// + /// + /// Hello + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<List<Guid>>> + Task>> HelloAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// Hello + /// + /// + /// Hello + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>List<Guid>>?> + Task>?> HelloOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<List<List<RolesReportsHash>>>> + Task>>> RolesReportGetAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>List<List<RolesReportsHash>>>?> + Task>>?> RolesReportGetOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// Retrieve an existing Notificationtest's Elements + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<NotificationtestGetElementsV1ResponseMPayload>> + Task> TestAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// Retrieve an existing Notificationtest's Elements + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>NotificationtestGetElementsV1ResponseMPayload>?> + Task?> TestOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public class DefaultApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler>? OnFooGet; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFooGet; + + internal void ExecuteOnFooGet(ApiResponse apiResponse) + { + OnFooGet?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFooGet(Exception exception) + { + OnErrorFooGet?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnGetCountry; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetCountry; + + internal void ExecuteOnGetCountry(ApiResponse apiResponse) + { + OnGetCountry?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetCountry(Exception exception) + { + OnErrorGetCountry?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>>? OnHello; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorHello; + + internal void ExecuteOnHello(ApiResponse> apiResponse) + { + OnHello?.Invoke(this, new ApiResponseEventArgs>(apiResponse)); + } + + internal void ExecuteOnErrorHello(Exception exception) + { + OnErrorHello?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>>>? OnRolesReportGet; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorRolesReportGet; + + internal void ExecuteOnRolesReportGet(ApiResponse>> apiResponse) + { + OnRolesReportGet?.Invoke(this, new ApiResponseEventArgs>>(apiResponse)); + } + + internal void ExecuteOnErrorRolesReportGet(Exception exception) + { + OnErrorRolesReportGet?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTest; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTest; + + internal void ExecuteOnTest(ApiResponse apiResponse) + { + OnTest?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTest(Exception exception) + { + OnErrorTest?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class DefaultApi : IDefaultApi + { + private JsonSerializerOptions _jsonSerializerOptions; + private FooGetDefaultResponseDeserializationContext _fooGetDefaultResponseDeserializationContext; + private NotificationtestGetElementsV1ResponseMPayloadDeserializationContext _notificationtestGetElementsV1ResponseMPayloadDeserializationContext; + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public DefaultApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider ApiKeyProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BearerTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BasicTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider HttpSignatureTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi(ILogger logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, DefaultApiEvents defaultApiEvents, + FooGetDefaultResponseDeserializationContext fooGetDefaultResponseDeserializationContext, + NotificationtestGetElementsV1ResponseMPayloadDeserializationContext notificationtestGetElementsV1ResponseMPayloadDeserializationContext, + TokenProvider apiKeyProvider, + TokenProvider bearerTokenProvider, + TokenProvider basicTokenProvider, + TokenProvider httpSignatureTokenProvider, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + _fooGetDefaultResponseDeserializationContext = fooGetDefaultResponseDeserializationContext; + _notificationtestGetElementsV1ResponseMPayloadDeserializationContext = notificationtestGetElementsV1ResponseMPayloadDeserializationContext; + Logger = logger; + HttpClient = httpClient; + Events = defaultApiEvents; + ApiKeyProvider = apiKeyProvider; + BearerTokenProvider = bearerTokenProvider; + BasicTokenProvider = basicTokenProvider; + HttpSignatureTokenProvider = httpSignatureTokenProvider; + OauthTokenProvider = oauthTokenProvider; + } + + /// + /// Processes the server response + /// + /// + private void AfterFooGetDefaultImplementation(ApiResponse apiResponseLocalVar) + { + bool suppressDefaultLog = false; + AfterFooGet(ref suppressDefaultLog, apiResponseLocalVar); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + partial void AfterFooGet(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + private void OnErrorFooGetDefaultImplementation(Exception exception, string pathFormat, string path) + { + bool suppressDefaultLog = false; + OnErrorFooGet(ref suppressDefaultLog, exception, pathFormat, path); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + partial void OnErrorFooGet(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path); + + /// + /// + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> FooGetOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FooGetAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> FooGetAsync(System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/foo"; + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/foo", requestedAtLocalVar, _fooGetDefaultResponseDeserializationContext.FooGetDefaultResponse); + + AfterFooGetDefaultImplementation(apiResponseLocalVar); + + Events.ExecuteOnFooGet(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFooGetDefaultImplementation(e, "/foo", uriBuilderLocalVar.Path); + Events.ExecuteOnErrorFooGet(e); + throw; + } + } + + partial void FormatGetCountry(ref string country); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetCountry(string country) + { + if (country == null) + throw new ArgumentNullException(nameof(country)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetCountryDefaultImplementation(ApiResponse apiResponseLocalVar, string country) + { + bool suppressDefaultLog = false; + AfterGetCountry(ref suppressDefaultLog, apiResponseLocalVar, country); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetCountry(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, string country); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetCountryDefaultImplementation(Exception exception, string pathFormat, string path, string country) + { + bool suppressDefaultLog = false; + OnErrorGetCountry(ref suppressDefaultLog, exception, pathFormat, path, country); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetCountry(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, string country); + + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> GetCountryOrDefaultAsync(string country, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetCountryAsync(country, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// + /// + /// Thrown when fails to make API call + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> GetCountryAsync(string country, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetCountry(country); + + FormatGetCountry(ref country); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/country"; + + MultipartContent multipartContentLocalVar = new MultipartContent(); + + httpRequestMessageLocalVar.Content = multipartContentLocalVar; + + List> formParameterLocalVars = new List>(); + + multipartContentLocalVar.Add(new FormUrlEncodedContent(formParameterLocalVars)); + + formParameterLocalVars.Add(new KeyValuePair("country", ClientUtils.ParameterToString(country))); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/country", requestedAtLocalVar, _jsonSerializerOptions); + + AfterGetCountryDefaultImplementation(apiResponseLocalVar, country); + + Events.ExecuteOnGetCountry(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetCountryDefaultImplementation(e, "/country", uriBuilderLocalVar.Path, country); + Events.ExecuteOnErrorGetCountry(e); + throw; + } + } + + /// + /// Processes the server response + /// + /// + private void AfterHelloDefaultImplementation(ApiResponse> apiResponseLocalVar) + { + bool suppressDefaultLog = false; + AfterHello(ref suppressDefaultLog, apiResponseLocalVar); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + partial void AfterHello(ref bool suppressDefaultLog, ApiResponse> apiResponseLocalVar); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + private void OnErrorHelloDefaultImplementation(Exception exception, string pathFormat, string path) + { + bool suppressDefaultLog = false; + OnErrorHello(ref suppressDefaultLog, exception, pathFormat, path); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + partial void OnErrorHello(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path); + + /// + /// Hello Hello + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>?> HelloOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await HelloAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Hello Hello + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>> HelloAsync(System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/hello"; + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse> apiResponseLocalVar = new ApiResponse>(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/hello", requestedAtLocalVar, _jsonSerializerOptions); + + AfterHelloDefaultImplementation(apiResponseLocalVar); + + Events.ExecuteOnHello(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorHelloDefaultImplementation(e, "/hello", uriBuilderLocalVar.Path); + Events.ExecuteOnErrorHello(e); + throw; + } + } + + /// + /// Processes the server response + /// + /// + private void AfterRolesReportGetDefaultImplementation(ApiResponse>> apiResponseLocalVar) + { + bool suppressDefaultLog = false; + AfterRolesReportGet(ref suppressDefaultLog, apiResponseLocalVar); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + partial void AfterRolesReportGet(ref bool suppressDefaultLog, ApiResponse>> apiResponseLocalVar); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + private void OnErrorRolesReportGetDefaultImplementation(Exception exception, string pathFormat, string path) + { + bool suppressDefaultLog = false; + OnErrorRolesReportGet(ref suppressDefaultLog, exception, pathFormat, path); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + partial void OnErrorRolesReportGet(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path); + + /// + /// + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>>?> RolesReportGetOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await RolesReportGetAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>>> RolesReportGetAsync(System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/roles/report"; + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse>> apiResponseLocalVar = new ApiResponse>>(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/roles/report", requestedAtLocalVar, _jsonSerializerOptions); + + AfterRolesReportGetDefaultImplementation(apiResponseLocalVar); + + Events.ExecuteOnRolesReportGet(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorRolesReportGetDefaultImplementation(e, "/roles/report", uriBuilderLocalVar.Path); + Events.ExecuteOnErrorRolesReportGet(e); + throw; + } + } + + /// + /// Processes the server response + /// + /// + private void AfterTestDefaultImplementation(ApiResponse apiResponseLocalVar) + { + bool suppressDefaultLog = false; + AfterTest(ref suppressDefaultLog, apiResponseLocalVar); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + partial void AfterTest(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + private void OnErrorTestDefaultImplementation(Exception exception, string pathFormat, string path) + { + bool suppressDefaultLog = false; + OnErrorTest(ref suppressDefaultLog, exception, pathFormat, path); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + partial void OnErrorTest(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path); + + /// + /// Retrieve an existing Notificationtest's Elements + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Retrieve an existing Notificationtest's Elements + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestAsync(System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/test"; + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/test", requestedAtLocalVar, _notificationtestGetElementsV1ResponseMPayloadDeserializationContext.NotificationtestGetElementsV1ResponseMPayload); + + AfterTestDefaultImplementation(apiResponseLocalVar); + + Events.ExecuteOnTest(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestDefaultImplementation(e, "/test", uriBuilderLocalVar.Path); + Events.ExecuteOnErrorTest(e); + throw; + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeApi.cs new file mode 100644 index 00000000000..0e32bae1700 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeApi.cs @@ -0,0 +1,3337 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using UseSourceGeneration.Client; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + +namespace UseSourceGeneration.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IFakeApi : IApi + { + /// + /// The class containing the events + /// + FakeApiEvents Events { get; } + + /// + /// Health check endpoint + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<HealthCheckResult>> + Task> FakeHealthGetAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// Health check endpoint + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>HealthCheckResult>?> + Task?> FakeHealthGetOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<bool>> + Task> FakeOuterBooleanSerializeAsync(Option body = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Input boolean as post body (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>bool>?> + Task?> FakeOuterBooleanSerializeOrDefaultAsync(Option body = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<OuterComposite>> + Task> FakeOuterCompositeSerializeAsync(Option outerComposite = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Input composite as post body (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>OuterComposite>?> + Task?> FakeOuterCompositeSerializeOrDefaultAsync(Option outerComposite = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<decimal>> + Task> FakeOuterNumberSerializeAsync(Option body = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Input number as post body (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>decimal>?> + Task?> FakeOuterNumberSerializeOrDefaultAsync(Option body = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Required UUID String + /// Input string as post body (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<string>> + Task> FakeOuterStringSerializeAsync(Guid requiredStringUuid, Option body = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Required UUID String + /// Input string as post body (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>string>?> + Task?> FakeOuterStringSerializeOrDefaultAsync(Guid requiredStringUuid, Option body = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Array of Enums + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<List<OuterEnum>>> + Task>> GetArrayOfEnumsAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// Array of Enums + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>List<OuterEnum>>?> + Task>?> GetArrayOfEnumsOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> TestBodyWithFileSchemaOrDefaultAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> TestBodyWithQueryParamsAsync(User user, string query, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> TestBodyWithQueryParamsOrDefaultAsync(User user, string query, System.Threading.CancellationToken cancellationToken = default); + + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<ModelClient>> + Task> TestClientModelAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default); + + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// client model + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>ModelClient>?> + Task?> TestClientModelOrDefaultAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string) (optional, default to -efg) + /// Form parameter enum test (string) (optional, default to -efg) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> TestEnumParametersAsync(Option> enumHeaderStringArray = default, Option> enumQueryStringArray = default, Option enumQueryDouble = default, Option enumQueryInteger = default, Option> enumFormStringArray = default, Option enumHeaderString = default, Option enumQueryString = default, Option enumFormString = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Header parameter enum test (string array) (optional) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string) (optional, default to -efg) + /// Form parameter enum test (string) (optional, default to -efg) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> TestEnumParametersOrDefaultAsync(Option> enumHeaderStringArray = default, Option> enumQueryStringArray = default, Option enumQueryDouble = default, Option enumQueryInteger = default, Option> enumFormStringArray = default, Option enumHeaderString = default, Option enumQueryString = default, Option enumFormString = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Fake endpoint to test group parameters (optional) + /// + /// + /// Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required Boolean in group parameters + /// Required String in group parameters + /// Required Integer in group parameters + /// Boolean in group parameters (optional) + /// String in group parameters (optional) + /// Integer in group parameters (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> TestGroupParametersAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, Option booleanGroup = default, Option stringGroup = default, Option int64Group = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Fake endpoint to test group parameters (optional) + /// + /// + /// Fake endpoint to test group parameters (optional) + /// + /// Required Boolean in group parameters + /// Required String in group parameters + /// Required Integer in group parameters + /// Boolean in group parameters (optional) + /// String in group parameters (optional) + /// Integer in group parameters (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> TestGroupParametersOrDefaultAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, Option booleanGroup = default, Option stringGroup = default, Option int64Group = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// test inline additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> TestInlineAdditionalPropertiesAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default); + + /// + /// test inline additionalProperties + /// + /// + /// + /// + /// request body + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> TestInlineAdditionalPropertiesOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default); + + /// + /// test json serialization of form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> TestJsonFormDataAsync(string param, string param2, System.Threading.CancellationToken cancellationToken = default); + + /// + /// test json serialization of form data + /// + /// + /// + /// + /// field1 + /// field2 + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> TestJsonFormDataOrDefaultAsync(string param, string param2, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// + /// + /// (optional) + /// (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, string requiredNotNullable, string? requiredNullable = default, Option notRequiredNotNullable = default, Option notRequiredNullable = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// To test the collection format in query parameters + /// + /// + /// + /// + /// + /// + /// + /// + /// (optional) + /// (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> TestQueryParameterCollectionFormatOrDefaultAsync(List pipe, List ioutil, List http, List url, List context, string requiredNotNullable, string? requiredNullable = default, Option notRequiredNotNullable = default, Option notRequiredNullable = default, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public class FakeApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler>? OnFakeHealthGet; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFakeHealthGet; + + internal void ExecuteOnFakeHealthGet(ApiResponse apiResponse) + { + OnFakeHealthGet?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFakeHealthGet(Exception exception) + { + OnErrorFakeHealthGet?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnFakeOuterBooleanSerialize; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFakeOuterBooleanSerialize; + + internal void ExecuteOnFakeOuterBooleanSerialize(ApiResponse apiResponse) + { + OnFakeOuterBooleanSerialize?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFakeOuterBooleanSerialize(Exception exception) + { + OnErrorFakeOuterBooleanSerialize?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnFakeOuterCompositeSerialize; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFakeOuterCompositeSerialize; + + internal void ExecuteOnFakeOuterCompositeSerialize(ApiResponse apiResponse) + { + OnFakeOuterCompositeSerialize?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFakeOuterCompositeSerialize(Exception exception) + { + OnErrorFakeOuterCompositeSerialize?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnFakeOuterNumberSerialize; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFakeOuterNumberSerialize; + + internal void ExecuteOnFakeOuterNumberSerialize(ApiResponse apiResponse) + { + OnFakeOuterNumberSerialize?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFakeOuterNumberSerialize(Exception exception) + { + OnErrorFakeOuterNumberSerialize?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnFakeOuterStringSerialize; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFakeOuterStringSerialize; + + internal void ExecuteOnFakeOuterStringSerialize(ApiResponse apiResponse) + { + OnFakeOuterStringSerialize?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFakeOuterStringSerialize(Exception exception) + { + OnErrorFakeOuterStringSerialize?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>>? OnGetArrayOfEnums; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetArrayOfEnums; + + internal void ExecuteOnGetArrayOfEnums(ApiResponse> apiResponse) + { + OnGetArrayOfEnums?.Invoke(this, new ApiResponseEventArgs>(apiResponse)); + } + + internal void ExecuteOnErrorGetArrayOfEnums(Exception exception) + { + OnErrorGetArrayOfEnums?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTestBodyWithFileSchema; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestBodyWithFileSchema; + + internal void ExecuteOnTestBodyWithFileSchema(ApiResponse apiResponse) + { + OnTestBodyWithFileSchema?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestBodyWithFileSchema(Exception exception) + { + OnErrorTestBodyWithFileSchema?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTestBodyWithQueryParams; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestBodyWithQueryParams; + + internal void ExecuteOnTestBodyWithQueryParams(ApiResponse apiResponse) + { + OnTestBodyWithQueryParams?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestBodyWithQueryParams(Exception exception) + { + OnErrorTestBodyWithQueryParams?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTestClientModel; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestClientModel; + + internal void ExecuteOnTestClientModel(ApiResponse apiResponse) + { + OnTestClientModel?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestClientModel(Exception exception) + { + OnErrorTestClientModel?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTestEndpointParameters; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestEndpointParameters; + + internal void ExecuteOnTestEndpointParameters(ApiResponse apiResponse) + { + OnTestEndpointParameters?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestEndpointParameters(Exception exception) + { + OnErrorTestEndpointParameters?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTestEnumParameters; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestEnumParameters; + + internal void ExecuteOnTestEnumParameters(ApiResponse apiResponse) + { + OnTestEnumParameters?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestEnumParameters(Exception exception) + { + OnErrorTestEnumParameters?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTestGroupParameters; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestGroupParameters; + + internal void ExecuteOnTestGroupParameters(ApiResponse apiResponse) + { + OnTestGroupParameters?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestGroupParameters(Exception exception) + { + OnErrorTestGroupParameters?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTestInlineAdditionalProperties; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestInlineAdditionalProperties; + + internal void ExecuteOnTestInlineAdditionalProperties(ApiResponse apiResponse) + { + OnTestInlineAdditionalProperties?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestInlineAdditionalProperties(Exception exception) + { + OnErrorTestInlineAdditionalProperties?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTestJsonFormData; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestJsonFormData; + + internal void ExecuteOnTestJsonFormData(ApiResponse apiResponse) + { + OnTestJsonFormData?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestJsonFormData(Exception exception) + { + OnErrorTestJsonFormData?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTestQueryParameterCollectionFormat; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestQueryParameterCollectionFormat; + + internal void ExecuteOnTestQueryParameterCollectionFormat(ApiResponse apiResponse) + { + OnTestQueryParameterCollectionFormat?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestQueryParameterCollectionFormat(Exception exception) + { + OnErrorTestQueryParameterCollectionFormat?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class FakeApi : IFakeApi + { + private JsonSerializerOptions _jsonSerializerOptions; + private HealthCheckResultDeserializationContext _healthCheckResultDeserializationContext; + private OuterCompositeDeserializationContext _outerCompositeDeserializationContext; + private ModelClientDeserializationContext _modelClientDeserializationContext; + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public FakeApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider ApiKeyProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BearerTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BasicTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider HttpSignatureTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeApi(ILogger logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, FakeApiEvents fakeApiEvents, + HealthCheckResultDeserializationContext healthCheckResultDeserializationContext, + OuterCompositeDeserializationContext outerCompositeDeserializationContext, + ModelClientDeserializationContext modelClientDeserializationContext, + TokenProvider apiKeyProvider, + TokenProvider bearerTokenProvider, + TokenProvider basicTokenProvider, + TokenProvider httpSignatureTokenProvider, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + _healthCheckResultDeserializationContext = healthCheckResultDeserializationContext; + _outerCompositeDeserializationContext = outerCompositeDeserializationContext; + _modelClientDeserializationContext = modelClientDeserializationContext; + Logger = logger; + HttpClient = httpClient; + Events = fakeApiEvents; + ApiKeyProvider = apiKeyProvider; + BearerTokenProvider = bearerTokenProvider; + BasicTokenProvider = basicTokenProvider; + HttpSignatureTokenProvider = httpSignatureTokenProvider; + OauthTokenProvider = oauthTokenProvider; + } + + /// + /// Processes the server response + /// + /// + private void AfterFakeHealthGetDefaultImplementation(ApiResponse apiResponseLocalVar) + { + bool suppressDefaultLog = false; + AfterFakeHealthGet(ref suppressDefaultLog, apiResponseLocalVar); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + partial void AfterFakeHealthGet(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + private void OnErrorFakeHealthGetDefaultImplementation(Exception exception, string pathFormat, string path) + { + bool suppressDefaultLog = false; + OnErrorFakeHealthGet(ref suppressDefaultLog, exception, pathFormat, path); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + partial void OnErrorFakeHealthGet(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path); + + /// + /// Health check endpoint + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> FakeHealthGetOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FakeHealthGetAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> FakeHealthGetAsync(System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/health"; + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/health", requestedAtLocalVar, _healthCheckResultDeserializationContext.HealthCheckResult); + + AfterFakeHealthGetDefaultImplementation(apiResponseLocalVar); + + Events.ExecuteOnFakeHealthGet(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFakeHealthGetDefaultImplementation(e, "/fake/health", uriBuilderLocalVar.Path); + Events.ExecuteOnErrorFakeHealthGet(e); + throw; + } + } + + partial void FormatFakeOuterBooleanSerialize(ref Option body); + + /// + /// Processes the server response + /// + /// + /// + private void AfterFakeOuterBooleanSerializeDefaultImplementation(ApiResponse apiResponseLocalVar, Option body) + { + bool suppressDefaultLog = false; + AfterFakeOuterBooleanSerialize(ref suppressDefaultLog, apiResponseLocalVar, body); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterFakeOuterBooleanSerialize(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, Option body); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorFakeOuterBooleanSerializeDefaultImplementation(Exception exception, string pathFormat, string path, Option body) + { + bool suppressDefaultLog = false; + OnErrorFakeOuterBooleanSerialize(ref suppressDefaultLog, exception, pathFormat, path, body); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorFakeOuterBooleanSerialize(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Option body); + + /// + /// Test serialization of outer boolean types + /// + /// Input boolean as post body (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> FakeOuterBooleanSerializeOrDefaultAsync(Option body = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FakeOuterBooleanSerializeAsync(body, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> FakeOuterBooleanSerializeAsync(Option body = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + FormatFakeOuterBooleanSerialize(ref body); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/outer/boolean"; + + if (body.IsSet) + httpRequestMessageLocalVar.Content = (body.Value as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(body.Value, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "*/*" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/outer/boolean", requestedAtLocalVar, _jsonSerializerOptions); + + AfterFakeOuterBooleanSerializeDefaultImplementation(apiResponseLocalVar, body); + + Events.ExecuteOnFakeOuterBooleanSerialize(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFakeOuterBooleanSerializeDefaultImplementation(e, "/fake/outer/boolean", uriBuilderLocalVar.Path, body); + Events.ExecuteOnErrorFakeOuterBooleanSerialize(e); + throw; + } + } + + partial void FormatFakeOuterCompositeSerialize(Option outerComposite); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFakeOuterCompositeSerialize(Option outerComposite) + { + if (outerComposite.IsSet && outerComposite.Value == null) + throw new ArgumentNullException(nameof(outerComposite)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterFakeOuterCompositeSerializeDefaultImplementation(ApiResponse apiResponseLocalVar, Option outerComposite) + { + bool suppressDefaultLog = false; + AfterFakeOuterCompositeSerialize(ref suppressDefaultLog, apiResponseLocalVar, outerComposite); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterFakeOuterCompositeSerialize(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, Option outerComposite); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorFakeOuterCompositeSerializeDefaultImplementation(Exception exception, string pathFormat, string path, Option outerComposite) + { + bool suppressDefaultLog = false; + OnErrorFakeOuterCompositeSerialize(ref suppressDefaultLog, exception, pathFormat, path, outerComposite); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorFakeOuterCompositeSerialize(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Option outerComposite); + + /// + /// Test serialization of object with outer number type + /// + /// Input composite as post body (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> FakeOuterCompositeSerializeOrDefaultAsync(Option outerComposite = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FakeOuterCompositeSerializeAsync(outerComposite, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> FakeOuterCompositeSerializeAsync(Option outerComposite = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFakeOuterCompositeSerialize(outerComposite); + + FormatFakeOuterCompositeSerialize(outerComposite); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/outer/composite"; + + if (outerComposite.IsSet) + httpRequestMessageLocalVar.Content = (outerComposite.Value as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(outerComposite.Value, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "*/*" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/outer/composite", requestedAtLocalVar, _outerCompositeDeserializationContext.OuterComposite); + + AfterFakeOuterCompositeSerializeDefaultImplementation(apiResponseLocalVar, outerComposite); + + Events.ExecuteOnFakeOuterCompositeSerialize(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFakeOuterCompositeSerializeDefaultImplementation(e, "/fake/outer/composite", uriBuilderLocalVar.Path, outerComposite); + Events.ExecuteOnErrorFakeOuterCompositeSerialize(e); + throw; + } + } + + partial void FormatFakeOuterNumberSerialize(ref Option body); + + /// + /// Processes the server response + /// + /// + /// + private void AfterFakeOuterNumberSerializeDefaultImplementation(ApiResponse apiResponseLocalVar, Option body) + { + bool suppressDefaultLog = false; + AfterFakeOuterNumberSerialize(ref suppressDefaultLog, apiResponseLocalVar, body); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterFakeOuterNumberSerialize(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, Option body); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorFakeOuterNumberSerializeDefaultImplementation(Exception exception, string pathFormat, string path, Option body) + { + bool suppressDefaultLog = false; + OnErrorFakeOuterNumberSerialize(ref suppressDefaultLog, exception, pathFormat, path, body); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorFakeOuterNumberSerialize(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Option body); + + /// + /// Test serialization of outer number types + /// + /// Input number as post body (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> FakeOuterNumberSerializeOrDefaultAsync(Option body = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FakeOuterNumberSerializeAsync(body, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> FakeOuterNumberSerializeAsync(Option body = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + FormatFakeOuterNumberSerialize(ref body); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/outer/number"; + + if (body.IsSet) + httpRequestMessageLocalVar.Content = (body.Value as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(body.Value, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "*/*" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/outer/number", requestedAtLocalVar, _jsonSerializerOptions); + + AfterFakeOuterNumberSerializeDefaultImplementation(apiResponseLocalVar, body); + + Events.ExecuteOnFakeOuterNumberSerialize(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFakeOuterNumberSerializeDefaultImplementation(e, "/fake/outer/number", uriBuilderLocalVar.Path, body); + Events.ExecuteOnErrorFakeOuterNumberSerialize(e); + throw; + } + } + + partial void FormatFakeOuterStringSerialize(ref Guid requiredStringUuid, ref Option body); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFakeOuterStringSerialize(Option body) + { + if (body.IsSet && body.Value == null) + throw new ArgumentNullException(nameof(body)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterFakeOuterStringSerializeDefaultImplementation(ApiResponse apiResponseLocalVar, Guid requiredStringUuid, Option body) + { + bool suppressDefaultLog = false; + AfterFakeOuterStringSerialize(ref suppressDefaultLog, apiResponseLocalVar, requiredStringUuid, body); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterFakeOuterStringSerialize(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, Guid requiredStringUuid, Option body); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorFakeOuterStringSerializeDefaultImplementation(Exception exception, string pathFormat, string path, Guid requiredStringUuid, Option body) + { + bool suppressDefaultLog = false; + OnErrorFakeOuterStringSerialize(ref suppressDefaultLog, exception, pathFormat, path, requiredStringUuid, body); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFakeOuterStringSerialize(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Guid requiredStringUuid, Option body); + + /// + /// Test serialization of outer string types + /// + /// Required UUID String + /// Input string as post body (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> FakeOuterStringSerializeOrDefaultAsync(Guid requiredStringUuid, Option body = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FakeOuterStringSerializeAsync(requiredStringUuid, body, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Required UUID String + /// Input string as post body (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> FakeOuterStringSerializeAsync(Guid requiredStringUuid, Option body = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFakeOuterStringSerialize(body); + + FormatFakeOuterStringSerialize(ref requiredStringUuid, ref body); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/outer/string"; + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryStringLocalVar["required_string_uuid"] = requiredStringUuid.ToString(); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + if (body.IsSet) + httpRequestMessageLocalVar.Content = (body.Value as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(body.Value, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "*/*" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/outer/string", requestedAtLocalVar, _jsonSerializerOptions); + + AfterFakeOuterStringSerializeDefaultImplementation(apiResponseLocalVar, requiredStringUuid, body); + + Events.ExecuteOnFakeOuterStringSerialize(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFakeOuterStringSerializeDefaultImplementation(e, "/fake/outer/string", uriBuilderLocalVar.Path, requiredStringUuid, body); + Events.ExecuteOnErrorFakeOuterStringSerialize(e); + throw; + } + } + + /// + /// Processes the server response + /// + /// + private void AfterGetArrayOfEnumsDefaultImplementation(ApiResponse> apiResponseLocalVar) + { + bool suppressDefaultLog = false; + AfterGetArrayOfEnums(ref suppressDefaultLog, apiResponseLocalVar); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + partial void AfterGetArrayOfEnums(ref bool suppressDefaultLog, ApiResponse> apiResponseLocalVar); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + private void OnErrorGetArrayOfEnumsDefaultImplementation(Exception exception, string pathFormat, string path) + { + bool suppressDefaultLog = false; + OnErrorGetArrayOfEnums(ref suppressDefaultLog, exception, pathFormat, path); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + partial void OnErrorGetArrayOfEnums(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path); + + /// + /// Array of Enums + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>?> GetArrayOfEnumsOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetArrayOfEnumsAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>> GetArrayOfEnumsAsync(System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/array-of-enums"; + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse> apiResponseLocalVar = new ApiResponse>(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/array-of-enums", requestedAtLocalVar, _jsonSerializerOptions); + + AfterGetArrayOfEnumsDefaultImplementation(apiResponseLocalVar); + + Events.ExecuteOnGetArrayOfEnums(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetArrayOfEnumsDefaultImplementation(e, "/fake/array-of-enums", uriBuilderLocalVar.Path); + Events.ExecuteOnErrorGetArrayOfEnums(e); + throw; + } + } + + partial void FormatTestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateTestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) + { + if (fileSchemaTestClass == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterTestBodyWithFileSchemaDefaultImplementation(ApiResponse apiResponseLocalVar, FileSchemaTestClass fileSchemaTestClass) + { + bool suppressDefaultLog = false; + AfterTestBodyWithFileSchema(ref suppressDefaultLog, apiResponseLocalVar, fileSchemaTestClass); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterTestBodyWithFileSchema(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, FileSchemaTestClass fileSchemaTestClass); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorTestBodyWithFileSchemaDefaultImplementation(Exception exception, string pathFormat, string path, FileSchemaTestClass fileSchemaTestClass) + { + bool suppressDefaultLog = false; + OnErrorTestBodyWithFileSchema(ref suppressDefaultLog, exception, pathFormat, path, fileSchemaTestClass); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorTestBodyWithFileSchema(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, FileSchemaTestClass fileSchemaTestClass); + + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestBodyWithFileSchemaOrDefaultAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestBodyWithFileSchemaAsync(fileSchemaTestClass, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestBodyWithFileSchema(fileSchemaTestClass); + + FormatTestBodyWithFileSchema(fileSchemaTestClass); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/body-with-file-schema"; + + httpRequestMessageLocalVar.Content = (fileSchemaTestClass as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(fileSchemaTestClass, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/body-with-file-schema", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestBodyWithFileSchemaDefaultImplementation(apiResponseLocalVar, fileSchemaTestClass); + + Events.ExecuteOnTestBodyWithFileSchema(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestBodyWithFileSchemaDefaultImplementation(e, "/fake/body-with-file-schema", uriBuilderLocalVar.Path, fileSchemaTestClass); + Events.ExecuteOnErrorTestBodyWithFileSchema(e); + throw; + } + } + + partial void FormatTestBodyWithQueryParams(User user, ref string query); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateTestBodyWithQueryParams(User user, string query) + { + if (user == null) + throw new ArgumentNullException(nameof(user)); + + if (query == null) + throw new ArgumentNullException(nameof(query)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterTestBodyWithQueryParamsDefaultImplementation(ApiResponse apiResponseLocalVar, User user, string query) + { + bool suppressDefaultLog = false; + AfterTestBodyWithQueryParams(ref suppressDefaultLog, apiResponseLocalVar, user, query); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterTestBodyWithQueryParams(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, User user, string query); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorTestBodyWithQueryParamsDefaultImplementation(Exception exception, string pathFormat, string path, User user, string query) + { + bool suppressDefaultLog = false; + OnErrorTestBodyWithQueryParams(ref suppressDefaultLog, exception, pathFormat, path, user, query); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorTestBodyWithQueryParams(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, User user, string query); + + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestBodyWithQueryParamsOrDefaultAsync(User user, string query, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestBodyWithQueryParamsAsync(user, query, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestBodyWithQueryParamsAsync(User user, string query, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestBodyWithQueryParams(user, query); + + FormatTestBodyWithQueryParams(user, ref query); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/body-with-query-params"; + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryStringLocalVar["query"] = query.ToString(); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + httpRequestMessageLocalVar.Content = (user as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/body-with-query-params", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestBodyWithQueryParamsDefaultImplementation(apiResponseLocalVar, user, query); + + Events.ExecuteOnTestBodyWithQueryParams(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestBodyWithQueryParamsDefaultImplementation(e, "/fake/body-with-query-params", uriBuilderLocalVar.Path, user, query); + Events.ExecuteOnErrorTestBodyWithQueryParams(e); + throw; + } + } + + partial void FormatTestClientModel(ModelClient modelClient); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateTestClientModel(ModelClient modelClient) + { + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterTestClientModelDefaultImplementation(ApiResponse apiResponseLocalVar, ModelClient modelClient) + { + bool suppressDefaultLog = false; + AfterTestClientModel(ref suppressDefaultLog, apiResponseLocalVar, modelClient); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterTestClientModel(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, ModelClient modelClient); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorTestClientModelDefaultImplementation(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + bool suppressDefaultLog = false; + OnErrorTestClientModel(ref suppressDefaultLog, exception, pathFormat, path, modelClient); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorTestClientModel(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, ModelClient modelClient); + + /// + /// To test \"client\" model To test \"client\" model + /// + /// client model + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestClientModelOrDefaultAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestClientModelAsync(modelClient, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestClientModelAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestClientModel(modelClient); + + FormatTestClientModel(modelClient); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake"; + + httpRequestMessageLocalVar.Content = (modelClient as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake", requestedAtLocalVar, _modelClientDeserializationContext.ModelClient); + + AfterTestClientModelDefaultImplementation(apiResponseLocalVar, modelClient); + + Events.ExecuteOnTestClientModel(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestClientModelDefaultImplementation(e, "/fake", uriBuilderLocalVar.Path, modelClient); + Events.ExecuteOnErrorTestClientModel(e); + throw; + } + } + + partial void FormatTestEndpointParameters(ref byte[] varByte, ref decimal number, ref double varDouble, ref string patternWithoutDelimiter, ref Option date, ref Option binary, ref Option varFloat, ref Option integer, ref Option int32, ref Option int64, ref Option varString, ref Option password, ref Option callback, ref Option dateTime); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + private void ValidateTestEndpointParameters(byte[] varByte, string patternWithoutDelimiter, Option binary, Option varString, Option password, Option callback) + { + if (varByte == null) + throw new ArgumentNullException(nameof(varByte)); + + if (patternWithoutDelimiter == null) + throw new ArgumentNullException(nameof(patternWithoutDelimiter)); + + if (binary.IsSet && binary.Value == null) + throw new ArgumentNullException(nameof(binary)); + + if (varString.IsSet && varString.Value == null) + throw new ArgumentNullException(nameof(varString)); + + if (password.IsSet && password.Value == null) + throw new ArgumentNullException(nameof(password)); + + if (callback.IsSet && callback.Value == null) + throw new ArgumentNullException(nameof(callback)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterTestEndpointParametersDefaultImplementation(ApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) + { + bool suppressDefaultLog = false; + AfterTestEndpointParameters(ref suppressDefaultLog, apiResponseLocalVar, varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterTestEndpointParameters(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorTestEndpointParametersDefaultImplementation(Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) + { + bool suppressDefaultLog = false; + OnErrorTestEndpointParameters(ref suppressDefaultLog, exception, pathFormat, path, varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorTestEndpointParameters(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestEndpointParametersAsync(varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestEndpointParameters(varByte, patternWithoutDelimiter, binary, varString, password, callback); + + FormatTestEndpointParameters(ref varByte, ref number, ref varDouble, ref patternWithoutDelimiter, ref date, ref binary, ref varFloat, ref integer, ref int32, ref int64, ref varString, ref password, ref callback, ref dateTime); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake"; + + MultipartContent multipartContentLocalVar = new MultipartContent(); + + httpRequestMessageLocalVar.Content = multipartContentLocalVar; + + List> formParameterLocalVars = new List>(); + + multipartContentLocalVar.Add(new FormUrlEncodedContent(formParameterLocalVars)); + + formParameterLocalVars.Add(new KeyValuePair("byte", ClientUtils.ParameterToString(varByte))); + + formParameterLocalVars.Add(new KeyValuePair("number", ClientUtils.ParameterToString(number))); + + formParameterLocalVars.Add(new KeyValuePair("double", ClientUtils.ParameterToString(varDouble))); + + formParameterLocalVars.Add(new KeyValuePair("pattern_without_delimiter", ClientUtils.ParameterToString(patternWithoutDelimiter))); + + if (date.IsSet) + formParameterLocalVars.Add(new KeyValuePair("date", ClientUtils.ParameterToString(date.Value))); + + if (binary.IsSet) + multipartContentLocalVar.Add(new StreamContent(binary.Value)); + + if (varFloat.IsSet) + formParameterLocalVars.Add(new KeyValuePair("float", ClientUtils.ParameterToString(varFloat.Value))); + + if (integer.IsSet) + formParameterLocalVars.Add(new KeyValuePair("integer", ClientUtils.ParameterToString(integer.Value))); + + if (int32.IsSet) + formParameterLocalVars.Add(new KeyValuePair("int32", ClientUtils.ParameterToString(int32.Value))); + + if (int64.IsSet) + formParameterLocalVars.Add(new KeyValuePair("int64", ClientUtils.ParameterToString(int64.Value))); + + if (varString.IsSet) + formParameterLocalVars.Add(new KeyValuePair("string", ClientUtils.ParameterToString(varString.Value))); + + if (password.IsSet) + formParameterLocalVars.Add(new KeyValuePair("password", ClientUtils.ParameterToString(password.Value))); + + if (callback.IsSet) + formParameterLocalVars.Add(new KeyValuePair("callback", ClientUtils.ParameterToString(callback.Value))); + + if (dateTime.IsSet) + formParameterLocalVars.Add(new KeyValuePair("dateTime", ClientUtils.ParameterToString(dateTime.Value))); + + List tokenBaseLocalVars = new List(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + BasicToken basicTokenLocalVar = (BasicToken) await BasicTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(basicTokenLocalVar); + + basicTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestEndpointParametersDefaultImplementation(apiResponseLocalVar, varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); + + Events.ExecuteOnTestEndpointParameters(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestEndpointParametersDefaultImplementation(e, "/fake", uriBuilderLocalVar.Path, varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); + Events.ExecuteOnErrorTestEndpointParameters(e); + throw; + } + } + + partial void FormatTestEnumParameters(Option> enumHeaderStringArray, Option> enumQueryStringArray, ref Option enumQueryDouble, ref Option enumQueryInteger, Option> enumFormStringArray, ref Option enumHeaderString, ref Option enumQueryString, ref Option enumFormString); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + private void ValidateTestEnumParameters(Option> enumHeaderStringArray, Option> enumQueryStringArray, Option> enumFormStringArray, Option enumHeaderString, Option enumQueryString, Option enumFormString) + { + if (enumHeaderStringArray.IsSet && enumHeaderStringArray.Value == null) + throw new ArgumentNullException(nameof(enumHeaderStringArray)); + + if (enumQueryStringArray.IsSet && enumQueryStringArray.Value == null) + throw new ArgumentNullException(nameof(enumQueryStringArray)); + + if (enumFormStringArray.IsSet && enumFormStringArray.Value == null) + throw new ArgumentNullException(nameof(enumFormStringArray)); + + if (enumHeaderString.IsSet && enumHeaderString.Value == null) + throw new ArgumentNullException(nameof(enumHeaderString)); + + if (enumQueryString.IsSet && enumQueryString.Value == null) + throw new ArgumentNullException(nameof(enumQueryString)); + + if (enumFormString.IsSet && enumFormString.Value == null) + throw new ArgumentNullException(nameof(enumFormString)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterTestEnumParametersDefaultImplementation(ApiResponse apiResponseLocalVar, Option> enumHeaderStringArray, Option> enumQueryStringArray, Option enumQueryDouble, Option enumQueryInteger, Option> enumFormStringArray, Option enumHeaderString, Option enumQueryString, Option enumFormString) + { + bool suppressDefaultLog = false; + AfterTestEnumParameters(ref suppressDefaultLog, apiResponseLocalVar, enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterTestEnumParameters(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, Option> enumHeaderStringArray, Option> enumQueryStringArray, Option enumQueryDouble, Option enumQueryInteger, Option> enumFormStringArray, Option enumHeaderString, Option enumQueryString, Option enumFormString); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorTestEnumParametersDefaultImplementation(Exception exception, string pathFormat, string path, Option> enumHeaderStringArray, Option> enumQueryStringArray, Option enumQueryDouble, Option enumQueryInteger, Option> enumFormStringArray, Option enumHeaderString, Option enumQueryString, Option enumFormString) + { + bool suppressDefaultLog = false; + OnErrorTestEnumParameters(ref suppressDefaultLog, exception, pathFormat, path, enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorTestEnumParameters(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Option> enumHeaderStringArray, Option> enumQueryStringArray, Option enumQueryDouble, Option enumQueryInteger, Option> enumFormStringArray, Option enumHeaderString, Option enumQueryString, Option enumFormString); + + /// + /// To test enum parameters To test enum parameters + /// + /// Header parameter enum test (string array) (optional) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string) (optional, default to -efg) + /// Form parameter enum test (string) (optional, default to -efg) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestEnumParametersOrDefaultAsync(Option> enumHeaderStringArray = default, Option> enumQueryStringArray = default, Option enumQueryDouble = default, Option enumQueryInteger = default, Option> enumFormStringArray = default, Option enumHeaderString = default, Option enumQueryString = default, Option enumFormString = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestEnumParametersAsync(enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string) (optional, default to -efg) + /// Form parameter enum test (string) (optional, default to -efg) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestEnumParametersAsync(Option> enumHeaderStringArray = default, Option> enumQueryStringArray = default, Option enumQueryDouble = default, Option enumQueryInteger = default, Option> enumFormStringArray = default, Option enumHeaderString = default, Option enumQueryString = default, Option enumFormString = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestEnumParameters(enumHeaderStringArray, enumQueryStringArray, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + + FormatTestEnumParameters(enumHeaderStringArray, enumQueryStringArray, ref enumQueryDouble, ref enumQueryInteger, enumFormStringArray, ref enumHeaderString, ref enumQueryString, ref enumFormString); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake"; + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (enumQueryStringArray.IsSet) + parseQueryStringLocalVar["enum_query_string_array"] = enumQueryStringArray.Value.ToString(); + + if (enumQueryDouble.IsSet) + parseQueryStringLocalVar["enum_query_double"] = enumQueryDouble.Value.ToString(); + + if (enumQueryInteger.IsSet) + parseQueryStringLocalVar["enum_query_integer"] = enumQueryInteger.Value.ToString(); + + if (enumQueryString.IsSet) + parseQueryStringLocalVar["enum_query_string"] = enumQueryString.Value.ToString(); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + if (enumHeaderStringArray.IsSet) + httpRequestMessageLocalVar.Headers.Add("enum_header_string_array", ClientUtils.ParameterToString(enumHeaderStringArray.Value)); + + if (enumHeaderString.IsSet) + httpRequestMessageLocalVar.Headers.Add("enum_header_string", ClientUtils.ParameterToString(enumHeaderString.Value)); + + MultipartContent multipartContentLocalVar = new MultipartContent(); + + httpRequestMessageLocalVar.Content = multipartContentLocalVar; + + List> formParameterLocalVars = new List>(); + + multipartContentLocalVar.Add(new FormUrlEncodedContent(formParameterLocalVars)); if (enumFormStringArray.IsSet) + formParameterLocalVars.Add(new KeyValuePair("enum_form_string_array", ClientUtils.ParameterToString(enumFormStringArray.Value))); + + if (enumFormString.IsSet) + formParameterLocalVars.Add(new KeyValuePair("enum_form_string", ClientUtils.ParameterToString(enumFormString.Value))); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestEnumParametersDefaultImplementation(apiResponseLocalVar, enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + + Events.ExecuteOnTestEnumParameters(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestEnumParametersDefaultImplementation(e, "/fake", uriBuilderLocalVar.Path, enumHeaderStringArray, enumQueryStringArray, enumQueryDouble, enumQueryInteger, enumFormStringArray, enumHeaderString, enumQueryString, enumFormString); + Events.ExecuteOnErrorTestEnumParameters(e); + throw; + } + } + + partial void FormatTestGroupParameters(ref bool requiredBooleanGroup, ref int requiredStringGroup, ref long requiredInt64Group, ref Option booleanGroup, ref Option stringGroup, ref Option int64Group); + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterTestGroupParametersDefaultImplementation(ApiResponse apiResponseLocalVar, bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, Option booleanGroup, Option stringGroup, Option int64Group) + { + bool suppressDefaultLog = false; + AfterTestGroupParameters(ref suppressDefaultLog, apiResponseLocalVar, requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterTestGroupParameters(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, Option booleanGroup, Option stringGroup, Option int64Group); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorTestGroupParametersDefaultImplementation(Exception exception, string pathFormat, string path, bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, Option booleanGroup, Option stringGroup, Option int64Group) + { + bool suppressDefaultLog = false; + OnErrorTestGroupParameters(ref suppressDefaultLog, exception, pathFormat, path, requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorTestGroupParameters(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, Option booleanGroup, Option stringGroup, Option int64Group); + + /// + /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) + /// + /// Required Boolean in group parameters + /// Required String in group parameters + /// Required Integer in group parameters + /// Boolean in group parameters (optional) + /// String in group parameters (optional) + /// Integer in group parameters (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestGroupParametersOrDefaultAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, Option booleanGroup = default, Option stringGroup = default, Option int64Group = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestGroupParametersAsync(requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required Boolean in group parameters + /// Required String in group parameters + /// Required Integer in group parameters + /// Boolean in group parameters (optional) + /// String in group parameters (optional) + /// Integer in group parameters (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestGroupParametersAsync(bool requiredBooleanGroup, int requiredStringGroup, long requiredInt64Group, Option booleanGroup = default, Option stringGroup = default, Option int64Group = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + FormatTestGroupParameters(ref requiredBooleanGroup, ref requiredStringGroup, ref requiredInt64Group, ref booleanGroup, ref stringGroup, ref int64Group); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake"; + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryStringLocalVar["required_string_group"] = requiredStringGroup.ToString(); + parseQueryStringLocalVar["required_int64_group"] = requiredInt64Group.ToString(); + + if (stringGroup.IsSet) + parseQueryStringLocalVar["string_group"] = stringGroup.Value.ToString(); + + if (int64Group.IsSet) + parseQueryStringLocalVar["int64_group"] = int64Group.Value.ToString(); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + httpRequestMessageLocalVar.Headers.Add("required_boolean_group", ClientUtils.ParameterToString(requiredBooleanGroup)); + + if (booleanGroup.IsSet) + httpRequestMessageLocalVar.Headers.Add("boolean_group", ClientUtils.ParameterToString(booleanGroup.Value)); + + List tokenBaseLocalVars = new List(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + BearerToken bearerTokenLocalVar = (BearerToken) await BearerTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(bearerTokenLocalVar); + + bearerTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestGroupParametersDefaultImplementation(apiResponseLocalVar, requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + + Events.ExecuteOnTestGroupParameters(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestGroupParametersDefaultImplementation(e, "/fake", uriBuilderLocalVar.Path, requiredBooleanGroup, requiredStringGroup, requiredInt64Group, booleanGroup, stringGroup, int64Group); + Events.ExecuteOnErrorTestGroupParameters(e); + throw; + } + } + + partial void FormatTestInlineAdditionalProperties(Dictionary requestBody); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateTestInlineAdditionalProperties(Dictionary requestBody) + { + if (requestBody == null) + throw new ArgumentNullException(nameof(requestBody)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterTestInlineAdditionalPropertiesDefaultImplementation(ApiResponse apiResponseLocalVar, Dictionary requestBody) + { + bool suppressDefaultLog = false; + AfterTestInlineAdditionalProperties(ref suppressDefaultLog, apiResponseLocalVar, requestBody); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterTestInlineAdditionalProperties(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, Dictionary requestBody); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorTestInlineAdditionalPropertiesDefaultImplementation(Exception exception, string pathFormat, string path, Dictionary requestBody) + { + bool suppressDefaultLog = false; + OnErrorTestInlineAdditionalProperties(ref suppressDefaultLog, exception, pathFormat, path, requestBody); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorTestInlineAdditionalProperties(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Dictionary requestBody); + + /// + /// test inline additionalProperties + /// + /// request body + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestInlineAdditionalPropertiesOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestInlineAdditionalPropertiesAsync(requestBody, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestInlineAdditionalPropertiesAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestInlineAdditionalProperties(requestBody); + + FormatTestInlineAdditionalProperties(requestBody); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/inline-additionalProperties"; + + httpRequestMessageLocalVar.Content = (requestBody as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(requestBody, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/inline-additionalProperties", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestInlineAdditionalPropertiesDefaultImplementation(apiResponseLocalVar, requestBody); + + Events.ExecuteOnTestInlineAdditionalProperties(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestInlineAdditionalPropertiesDefaultImplementation(e, "/fake/inline-additionalProperties", uriBuilderLocalVar.Path, requestBody); + Events.ExecuteOnErrorTestInlineAdditionalProperties(e); + throw; + } + } + + partial void FormatTestJsonFormData(ref string param, ref string param2); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateTestJsonFormData(string param, string param2) + { + if (param == null) + throw new ArgumentNullException(nameof(param)); + + if (param2 == null) + throw new ArgumentNullException(nameof(param2)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterTestJsonFormDataDefaultImplementation(ApiResponse apiResponseLocalVar, string param, string param2) + { + bool suppressDefaultLog = false; + AfterTestJsonFormData(ref suppressDefaultLog, apiResponseLocalVar, param, param2); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterTestJsonFormData(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, string param, string param2); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorTestJsonFormDataDefaultImplementation(Exception exception, string pathFormat, string path, string param, string param2) + { + bool suppressDefaultLog = false; + OnErrorTestJsonFormData(ref suppressDefaultLog, exception, pathFormat, path, param, param2); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorTestJsonFormData(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, string param, string param2); + + /// + /// test json serialization of form data + /// + /// field1 + /// field2 + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestJsonFormDataOrDefaultAsync(string param, string param2, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestJsonFormDataAsync(param, param2, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestJsonFormDataAsync(string param, string param2, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestJsonFormData(param, param2); + + FormatTestJsonFormData(ref param, ref param2); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/jsonFormData"; + + MultipartContent multipartContentLocalVar = new MultipartContent(); + + httpRequestMessageLocalVar.Content = multipartContentLocalVar; + + List> formParameterLocalVars = new List>(); + + multipartContentLocalVar.Add(new FormUrlEncodedContent(formParameterLocalVars)); + + formParameterLocalVars.Add(new KeyValuePair("param", ClientUtils.ParameterToString(param))); + + formParameterLocalVars.Add(new KeyValuePair("param2", ClientUtils.ParameterToString(param2))); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/jsonFormData", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestJsonFormDataDefaultImplementation(apiResponseLocalVar, param, param2); + + Events.ExecuteOnTestJsonFormData(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestJsonFormDataDefaultImplementation(e, "/fake/jsonFormData", uriBuilderLocalVar.Path, param, param2); + Events.ExecuteOnErrorTestJsonFormData(e); + throw; + } + } + + partial void FormatTestQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context, ref string requiredNotNullable, ref string? requiredNullable, ref Option notRequiredNotNullable, ref Option notRequiredNullable); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void ValidateTestQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context, string requiredNotNullable, Option notRequiredNotNullable) + { + if (pipe == null) + throw new ArgumentNullException(nameof(pipe)); + + if (ioutil == null) + throw new ArgumentNullException(nameof(ioutil)); + + if (http == null) + throw new ArgumentNullException(nameof(http)); + + if (url == null) + throw new ArgumentNullException(nameof(url)); + + if (context == null) + throw new ArgumentNullException(nameof(context)); + + if (requiredNotNullable == null) + throw new ArgumentNullException(nameof(requiredNotNullable)); + + if (notRequiredNotNullable.IsSet && notRequiredNotNullable.Value == null) + throw new ArgumentNullException(nameof(notRequiredNotNullable)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterTestQueryParameterCollectionFormatDefaultImplementation(ApiResponse apiResponseLocalVar, List pipe, List ioutil, List http, List url, List context, string requiredNotNullable, string? requiredNullable, Option notRequiredNotNullable, Option notRequiredNullable) + { + bool suppressDefaultLog = false; + AfterTestQueryParameterCollectionFormat(ref suppressDefaultLog, apiResponseLocalVar, pipe, ioutil, http, url, context, requiredNotNullable, requiredNullable, notRequiredNotNullable, notRequiredNullable); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterTestQueryParameterCollectionFormat(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, List pipe, List ioutil, List http, List url, List context, string requiredNotNullable, string? requiredNullable, Option notRequiredNotNullable, Option notRequiredNullable); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorTestQueryParameterCollectionFormatDefaultImplementation(Exception exception, string pathFormat, string path, List pipe, List ioutil, List http, List url, List context, string requiredNotNullable, string? requiredNullable, Option notRequiredNotNullable, Option notRequiredNullable) + { + bool suppressDefaultLog = false; + OnErrorTestQueryParameterCollectionFormat(ref suppressDefaultLog, exception, pathFormat, path, pipe, ioutil, http, url, context, requiredNotNullable, requiredNullable, notRequiredNotNullable, notRequiredNullable); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorTestQueryParameterCollectionFormat(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, List pipe, List ioutil, List http, List url, List context, string requiredNotNullable, string? requiredNullable, Option notRequiredNotNullable, Option notRequiredNullable); + + /// + /// To test the collection format in query parameters + /// + /// + /// + /// + /// + /// + /// + /// + /// (optional) + /// (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestQueryParameterCollectionFormatOrDefaultAsync(List pipe, List ioutil, List http, List url, List context, string requiredNotNullable, string? requiredNullable = default, Option notRequiredNotNullable = default, Option notRequiredNullable = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestQueryParameterCollectionFormatAsync(pipe, ioutil, http, url, context, requiredNotNullable, requiredNullable, notRequiredNotNullable, notRequiredNullable, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// + /// + /// (optional) + /// (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, string requiredNotNullable, string? requiredNullable = default, Option notRequiredNotNullable = default, Option notRequiredNullable = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestQueryParameterCollectionFormat(pipe, ioutil, http, url, context, requiredNotNullable, notRequiredNotNullable); + + FormatTestQueryParameterCollectionFormat(pipe, ioutil, http, url, context, ref requiredNotNullable, ref requiredNullable, ref notRequiredNotNullable, ref notRequiredNullable); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/test-query-parameters"; + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryStringLocalVar["pipe"] = pipe.ToString(); + parseQueryStringLocalVar["ioutil"] = ioutil.ToString(); + parseQueryStringLocalVar["http"] = http.ToString(); + parseQueryStringLocalVar["url"] = url.ToString(); + parseQueryStringLocalVar["context"] = context.ToString(); + parseQueryStringLocalVar["requiredNotNullable"] = requiredNotNullable.ToString(); + parseQueryStringLocalVar["requiredNullable"] = requiredNullable?.ToString(); + + if (notRequiredNotNullable.IsSet) + parseQueryStringLocalVar["notRequiredNotNullable"] = notRequiredNotNullable.Value.ToString(); + + if (notRequiredNullable.IsSet) + parseQueryStringLocalVar["notRequiredNullable"] = notRequiredNullable.Value?.ToString(); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/test-query-parameters", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestQueryParameterCollectionFormatDefaultImplementation(apiResponseLocalVar, pipe, ioutil, http, url, context, requiredNotNullable, requiredNullable, notRequiredNotNullable, notRequiredNullable); + + Events.ExecuteOnTestQueryParameterCollectionFormat(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestQueryParameterCollectionFormatDefaultImplementation(e, "/fake/test-query-parameters", uriBuilderLocalVar.Path, pipe, ioutil, http, url, context, requiredNotNullable, requiredNullable, notRequiredNotNullable, notRequiredNullable); + Events.ExecuteOnErrorTestQueryParameterCollectionFormat(e); + throw; + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeClassnameTags123Api.cs new file mode 100644 index 00000000000..43825e1856b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeClassnameTags123Api.cs @@ -0,0 +1,327 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using UseSourceGeneration.Client; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + +namespace UseSourceGeneration.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IFakeClassnameTags123Api : IApi + { + /// + /// The class containing the events + /// + FakeClassnameTags123ApiEvents Events { get; } + + /// + /// To test class name in snake case + /// + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<ModelClient>> + Task> TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default); + + /// + /// To test class name in snake case + /// + /// + /// To test class name in snake case + /// + /// client model + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>ModelClient>?> + Task?> TestClassnameOrDefaultAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public class FakeClassnameTags123ApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler>? OnTestClassname; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestClassname; + + internal void ExecuteOnTestClassname(ApiResponse apiResponse) + { + OnTestClassname?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestClassname(Exception exception) + { + OnErrorTestClassname?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class FakeClassnameTags123Api : IFakeClassnameTags123Api + { + private JsonSerializerOptions _jsonSerializerOptions; + private ModelClientDeserializationContext _modelClientDeserializationContext; + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public FakeClassnameTags123ApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider ApiKeyProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BearerTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BasicTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider HttpSignatureTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeClassnameTags123Api(ILogger logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, FakeClassnameTags123ApiEvents fakeClassnameTags123ApiEvents, + ModelClientDeserializationContext modelClientDeserializationContext, + TokenProvider apiKeyProvider, + TokenProvider bearerTokenProvider, + TokenProvider basicTokenProvider, + TokenProvider httpSignatureTokenProvider, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + _modelClientDeserializationContext = modelClientDeserializationContext; + Logger = logger; + HttpClient = httpClient; + Events = fakeClassnameTags123ApiEvents; + ApiKeyProvider = apiKeyProvider; + BearerTokenProvider = bearerTokenProvider; + BasicTokenProvider = basicTokenProvider; + HttpSignatureTokenProvider = httpSignatureTokenProvider; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatTestClassname(ModelClient modelClient); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateTestClassname(ModelClient modelClient) + { + if (modelClient == null) + throw new ArgumentNullException(nameof(modelClient)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterTestClassnameDefaultImplementation(ApiResponse apiResponseLocalVar, ModelClient modelClient) + { + bool suppressDefaultLog = false; + AfterTestClassname(ref suppressDefaultLog, apiResponseLocalVar, modelClient); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterTestClassname(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, ModelClient modelClient); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorTestClassnameDefaultImplementation(Exception exception, string pathFormat, string path, ModelClient modelClient) + { + bool suppressDefaultLog = false; + OnErrorTestClassname(ref suppressDefaultLog, exception, pathFormat, path, modelClient); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorTestClassname(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, ModelClient modelClient); + + /// + /// To test class name in snake case To test class name in snake case + /// + /// client model + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> TestClassnameOrDefaultAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestClassnameAsync(modelClient, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// To test class name in snake case To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestClassname(modelClient); + + FormatTestClassname(modelClient); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake_classname_test"; + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + httpRequestMessageLocalVar.Content = (modelClient as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + + ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(apiKeyTokenLocalVar); + apiKeyTokenLocalVar.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar, "api_key_query"); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake_classname_test", requestedAtLocalVar, _modelClientDeserializationContext.ModelClient); + + AfterTestClassnameDefaultImplementation(apiResponseLocalVar, modelClient); + + Events.ExecuteOnTestClassname(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestClassnameDefaultImplementation(e, "/fake_classname_test", uriBuilderLocalVar.Path, modelClient); + Events.ExecuteOnErrorTestClassname(e); + throw; + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/IApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/IApi.cs new file mode 100644 index 00000000000..ea92cc4b1ec --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/IApi.cs @@ -0,0 +1,15 @@ +using System.Net.Http; + +namespace UseSourceGeneration.Api +{ + /// + /// Any Api client + /// + public interface IApi + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/PetApi.cs new file mode 100644 index 00000000000..6ce306fc7db --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/PetApi.cs @@ -0,0 +1,2047 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using UseSourceGeneration.Client; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + +namespace UseSourceGeneration.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IPetApi : IApi + { + /// + /// The class containing the events + /// + PetApiEvents Events { get; } + + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> AddPetAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> AddPetOrDefaultAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> DeletePetAsync(long petId, Option apiKey = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Deletes a pet + /// + /// + /// + /// + /// Pet id to delete + /// (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> DeletePetOrDefaultAsync(long petId, Option apiKey = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<List<Pet>>> + Task>> FindPetsByStatusAsync(List status, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Status values that need to be considered for filter + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>List<Pet>>?> + Task>?> FindPetsByStatusOrDefaultAsync(List status, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<List<Pet>>> + Task>> FindPetsByTagsAsync(List tags, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>List<Pet>>?> + Task>?> FindPetsByTagsOrDefaultAsync(List tags, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<Pet>> + Task> GetPetByIdAsync(long petId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// ID of pet to return + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>Pet>?> + Task?> GetPetByIdOrDefaultAsync(long petId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> UpdatePetAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update an existing pet + /// + /// + /// + /// + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> UpdatePetOrDefaultAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> UpdatePetWithFormAsync(long petId, Option name = default, Option status = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> UpdatePetWithFormOrDefaultAsync(long petId, Option name = default, Option status = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// uploads an image + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload (optional) + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<ApiResponse>> + Task> UploadFileAsync(long petId, Option file = default, Option additionalMetadata = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// uploads an image + /// + /// + /// + /// + /// ID of pet to update + /// file to upload (optional) + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>ApiResponse>?> + Task?> UploadFileOrDefaultAsync(long petId, Option file = default, Option additionalMetadata = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// uploads an image (required) + /// + /// + /// + /// + /// Thrown when fails to make API call + /// file to upload + /// ID of pet to update + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<ApiResponse>> + Task> UploadFileWithRequiredFileAsync(System.IO.Stream requiredFile, long petId, Option additionalMetadata = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// uploads an image (required) + /// + /// + /// + /// + /// file to upload + /// ID of pet to update + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>ApiResponse>?> + Task?> UploadFileWithRequiredFileOrDefaultAsync(System.IO.Stream requiredFile, long petId, Option additionalMetadata = default, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public class PetApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler>? OnAddPet; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorAddPet; + + internal void ExecuteOnAddPet(ApiResponse apiResponse) + { + OnAddPet?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAddPet(Exception exception) + { + OnErrorAddPet?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnDeletePet; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeletePet; + + internal void ExecuteOnDeletePet(ApiResponse apiResponse) + { + OnDeletePet?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeletePet(Exception exception) + { + OnErrorDeletePet?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>>? OnFindPetsByStatus; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFindPetsByStatus; + + internal void ExecuteOnFindPetsByStatus(ApiResponse> apiResponse) + { + OnFindPetsByStatus?.Invoke(this, new ApiResponseEventArgs>(apiResponse)); + } + + internal void ExecuteOnErrorFindPetsByStatus(Exception exception) + { + OnErrorFindPetsByStatus?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>>? OnFindPetsByTags; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFindPetsByTags; + + internal void ExecuteOnFindPetsByTags(ApiResponse> apiResponse) + { + OnFindPetsByTags?.Invoke(this, new ApiResponseEventArgs>(apiResponse)); + } + + internal void ExecuteOnErrorFindPetsByTags(Exception exception) + { + OnErrorFindPetsByTags?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnGetPetById; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetPetById; + + internal void ExecuteOnGetPetById(ApiResponse apiResponse) + { + OnGetPetById?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetPetById(Exception exception) + { + OnErrorGetPetById?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnUpdatePet; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdatePet; + + internal void ExecuteOnUpdatePet(ApiResponse apiResponse) + { + OnUpdatePet?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdatePet(Exception exception) + { + OnErrorUpdatePet?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnUpdatePetWithForm; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdatePetWithForm; + + internal void ExecuteOnUpdatePetWithForm(ApiResponse apiResponse) + { + OnUpdatePetWithForm?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdatePetWithForm(Exception exception) + { + OnErrorUpdatePetWithForm?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnUploadFile; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUploadFile; + + internal void ExecuteOnUploadFile(ApiResponse apiResponse) + { + OnUploadFile?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUploadFile(Exception exception) + { + OnErrorUploadFile?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnUploadFileWithRequiredFile; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUploadFileWithRequiredFile; + + internal void ExecuteOnUploadFileWithRequiredFile(ApiResponse apiResponse) + { + OnUploadFileWithRequiredFile?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUploadFileWithRequiredFile(Exception exception) + { + OnErrorUploadFileWithRequiredFile?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class PetApi : IPetApi + { + private JsonSerializerOptions _jsonSerializerOptions; + private PetDeserializationContext _petDeserializationContext; + private ApiResponseDeserializationContext _apiResponseDeserializationContext; + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public PetApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider ApiKeyProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BearerTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BasicTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider HttpSignatureTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public PetApi(ILogger logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PetApiEvents petApiEvents, + PetDeserializationContext petDeserializationContext, + ApiResponseDeserializationContext apiResponseDeserializationContext, + TokenProvider apiKeyProvider, + TokenProvider bearerTokenProvider, + TokenProvider basicTokenProvider, + TokenProvider httpSignatureTokenProvider, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + _petDeserializationContext = petDeserializationContext; + _apiResponseDeserializationContext = apiResponseDeserializationContext; + Logger = logger; + HttpClient = httpClient; + Events = petApiEvents; + ApiKeyProvider = apiKeyProvider; + BearerTokenProvider = bearerTokenProvider; + BasicTokenProvider = basicTokenProvider; + HttpSignatureTokenProvider = httpSignatureTokenProvider; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatAddPet(Pet pet); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateAddPet(Pet pet) + { + if (pet == null) + throw new ArgumentNullException(nameof(pet)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterAddPetDefaultImplementation(ApiResponse apiResponseLocalVar, Pet pet) + { + bool suppressDefaultLog = false; + AfterAddPet(ref suppressDefaultLog, apiResponseLocalVar, pet); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterAddPet(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, Pet pet); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorAddPetDefaultImplementation(Exception exception, string pathFormat, string path, Pet pet) + { + bool suppressDefaultLog = false; + OnErrorAddPet(ref suppressDefaultLog, exception, pathFormat, path, pet); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorAddPet(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Pet pet); + + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> AddPetOrDefaultAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await AddPetAsync(pet, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> AddPetAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateAddPet(pet); + + FormatAddPet(pet); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + Uri urlLocalVar = httpRequestMessageLocalVar.RequestUri = new Uri("http://petstore.swagger.io/v2"); + uriBuilderLocalVar.Host = urlLocalVar.Authority; + uriBuilderLocalVar.Scheme = urlLocalVar.Scheme; + uriBuilderLocalVar.Path = urlLocalVar.AbsolutePath; + + httpRequestMessageLocalVar.Content = (pet as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(pet, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar); + + oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + + HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + + if (httpRequestMessageLocalVar.Content != null) { + string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + } + + string[] contentTypes = new string[] { + "application/json", + "application/xml" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/pet", requestedAtLocalVar, _jsonSerializerOptions); + + AfterAddPetDefaultImplementation(apiResponseLocalVar, pet); + + Events.ExecuteOnAddPet(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorAddPetDefaultImplementation(e, "/pet", uriBuilderLocalVar.Path, pet); + Events.ExecuteOnErrorAddPet(e); + throw; + } + } + + partial void FormatDeletePet(ref long petId, ref Option apiKey); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeletePet(Option apiKey) + { + if (apiKey.IsSet && apiKey.Value == null) + throw new ArgumentNullException(nameof(apiKey)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterDeletePetDefaultImplementation(ApiResponse apiResponseLocalVar, long petId, Option apiKey) + { + bool suppressDefaultLog = false; + AfterDeletePet(ref suppressDefaultLog, apiResponseLocalVar, petId, apiKey); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterDeletePet(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, long petId, Option apiKey); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorDeletePetDefaultImplementation(Exception exception, string pathFormat, string path, long petId, Option apiKey) + { + bool suppressDefaultLog = false; + OnErrorDeletePet(ref suppressDefaultLog, exception, pathFormat, path, petId, apiKey); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorDeletePet(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, long petId, Option apiKey); + + /// + /// Deletes a pet + /// + /// Pet id to delete + /// (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> DeletePetOrDefaultAsync(long petId, Option apiKey = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeletePetAsync(petId, apiKey, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> DeletePetAsync(long petId, Option apiKey = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeletePet(apiKey); + + FormatDeletePet(ref petId, ref apiKey); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); + + if (apiKey.IsSet) + httpRequestMessageLocalVar.Headers.Add("api_key", ClientUtils.ParameterToString(apiKey.Value)); + + List tokenBaseLocalVars = new List(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar); + + oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/pet/{petId}", requestedAtLocalVar, _jsonSerializerOptions); + + AfterDeletePetDefaultImplementation(apiResponseLocalVar, petId, apiKey); + + Events.ExecuteOnDeletePet(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeletePetDefaultImplementation(e, "/pet/{petId}", uriBuilderLocalVar.Path, petId, apiKey); + Events.ExecuteOnErrorDeletePet(e); + throw; + } + } + + partial void FormatFindPetsByStatus(List status); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFindPetsByStatus(List status) + { + if (status == null) + throw new ArgumentNullException(nameof(status)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterFindPetsByStatusDefaultImplementation(ApiResponse> apiResponseLocalVar, List status) + { + bool suppressDefaultLog = false; + AfterFindPetsByStatus(ref suppressDefaultLog, apiResponseLocalVar, status); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterFindPetsByStatus(ref bool suppressDefaultLog, ApiResponse> apiResponseLocalVar, List status); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorFindPetsByStatusDefaultImplementation(Exception exception, string pathFormat, string path, List status) + { + bool suppressDefaultLog = false; + OnErrorFindPetsByStatus(ref suppressDefaultLog, exception, pathFormat, path, status); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorFindPetsByStatus(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, List status); + + /// + /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// + /// Status values that need to be considered for filter + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>?> FindPetsByStatusOrDefaultAsync(List status, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FindPetsByStatusAsync(status, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>> FindPetsByStatusAsync(List status, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFindPetsByStatus(status); + + FormatFindPetsByStatus(status); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/pet/findByStatus"; + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryStringLocalVar["status"] = status.ToString(); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar); + + oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + + HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + + if (httpRequestMessageLocalVar.Content != null) { + string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + } + + string[] acceptLocalVars = new string[] { + "application/xml", + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse> apiResponseLocalVar = new ApiResponse>(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/pet/findByStatus", requestedAtLocalVar, _jsonSerializerOptions); + + AfterFindPetsByStatusDefaultImplementation(apiResponseLocalVar, status); + + Events.ExecuteOnFindPetsByStatus(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFindPetsByStatusDefaultImplementation(e, "/pet/findByStatus", uriBuilderLocalVar.Path, status); + Events.ExecuteOnErrorFindPetsByStatus(e); + throw; + } + } + + partial void FormatFindPetsByTags(List tags); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFindPetsByTags(List tags) + { + if (tags == null) + throw new ArgumentNullException(nameof(tags)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterFindPetsByTagsDefaultImplementation(ApiResponse> apiResponseLocalVar, List tags) + { + bool suppressDefaultLog = false; + AfterFindPetsByTags(ref suppressDefaultLog, apiResponseLocalVar, tags); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterFindPetsByTags(ref bool suppressDefaultLog, ApiResponse> apiResponseLocalVar, List tags); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorFindPetsByTagsDefaultImplementation(Exception exception, string pathFormat, string path, List tags) + { + bool suppressDefaultLog = false; + OnErrorFindPetsByTags(ref suppressDefaultLog, exception, pathFormat, path, tags); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorFindPetsByTags(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, List tags); + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>?> FindPetsByTagsOrDefaultAsync(List tags, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FindPetsByTagsAsync(tags, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>> FindPetsByTagsAsync(List tags, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFindPetsByTags(tags); + + FormatFindPetsByTags(tags); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/pet/findByTags"; + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryStringLocalVar["tags"] = tags.ToString(); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar); + + oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + + HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + + if (httpRequestMessageLocalVar.Content != null) { + string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + } + + string[] acceptLocalVars = new string[] { + "application/xml", + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse> apiResponseLocalVar = new ApiResponse>(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/pet/findByTags", requestedAtLocalVar, _jsonSerializerOptions); + + AfterFindPetsByTagsDefaultImplementation(apiResponseLocalVar, tags); + + Events.ExecuteOnFindPetsByTags(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFindPetsByTagsDefaultImplementation(e, "/pet/findByTags", uriBuilderLocalVar.Path, tags); + Events.ExecuteOnErrorFindPetsByTags(e); + throw; + } + } + + partial void FormatGetPetById(ref long petId); + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetPetByIdDefaultImplementation(ApiResponse apiResponseLocalVar, long petId) + { + bool suppressDefaultLog = false; + AfterGetPetById(ref suppressDefaultLog, apiResponseLocalVar, petId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetPetById(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, long petId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetPetByIdDefaultImplementation(Exception exception, string pathFormat, string path, long petId) + { + bool suppressDefaultLog = false; + OnErrorGetPetById(ref suppressDefaultLog, exception, pathFormat, path, petId); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetPetById(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, long petId); + + /// + /// Find pet by ID Returns a single pet + /// + /// ID of pet to return + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> GetPetByIdOrDefaultAsync(long petId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetPetByIdAsync(petId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> GetPetByIdAsync(long petId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + FormatGetPetById(ref petId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); + + List tokenBaseLocalVars = new List(); + + ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(apiKeyTokenLocalVar); + + apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "api_key"); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/xml", + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/pet/{petId}", requestedAtLocalVar, _petDeserializationContext.Pet); + + AfterGetPetByIdDefaultImplementation(apiResponseLocalVar, petId); + + Events.ExecuteOnGetPetById(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetPetByIdDefaultImplementation(e, "/pet/{petId}", uriBuilderLocalVar.Path, petId); + Events.ExecuteOnErrorGetPetById(e); + throw; + } + } + + partial void FormatUpdatePet(Pet pet); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateUpdatePet(Pet pet) + { + if (pet == null) + throw new ArgumentNullException(nameof(pet)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterUpdatePetDefaultImplementation(ApiResponse apiResponseLocalVar, Pet pet) + { + bool suppressDefaultLog = false; + AfterUpdatePet(ref suppressDefaultLog, apiResponseLocalVar, pet); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterUpdatePet(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, Pet pet); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorUpdatePetDefaultImplementation(Exception exception, string pathFormat, string path, Pet pet) + { + bool suppressDefaultLog = false; + OnErrorUpdatePet(ref suppressDefaultLog, exception, pathFormat, path, pet); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdatePet(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Pet pet); + + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> UpdatePetOrDefaultAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdatePetAsync(pet, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> UpdatePetAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdatePet(pet); + + FormatUpdatePet(pet); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + Uri urlLocalVar = httpRequestMessageLocalVar.RequestUri = new Uri("http://petstore.swagger.io/v2"); + uriBuilderLocalVar.Host = urlLocalVar.Authority; + uriBuilderLocalVar.Scheme = urlLocalVar.Scheme; + uriBuilderLocalVar.Path = urlLocalVar.AbsolutePath; + + httpRequestMessageLocalVar.Content = (pet as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(pet, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar); + + oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + + HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + + if (httpRequestMessageLocalVar.Content != null) { + string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + } + + string[] contentTypes = new string[] { + "application/json", + "application/xml" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/pet", requestedAtLocalVar, _jsonSerializerOptions); + + AfterUpdatePetDefaultImplementation(apiResponseLocalVar, pet); + + Events.ExecuteOnUpdatePet(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdatePetDefaultImplementation(e, "/pet", uriBuilderLocalVar.Path, pet); + Events.ExecuteOnErrorUpdatePet(e); + throw; + } + } + + partial void FormatUpdatePetWithForm(ref long petId, ref Option name, ref Option status); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdatePetWithForm(Option name, Option status) + { + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name)); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + private void AfterUpdatePetWithFormDefaultImplementation(ApiResponse apiResponseLocalVar, long petId, Option name, Option status) + { + bool suppressDefaultLog = false; + AfterUpdatePetWithForm(ref suppressDefaultLog, apiResponseLocalVar, petId, name, status); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + partial void AfterUpdatePetWithForm(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, long petId, Option name, Option status); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + private void OnErrorUpdatePetWithFormDefaultImplementation(Exception exception, string pathFormat, string path, long petId, Option name, Option status) + { + bool suppressDefaultLog = false; + OnErrorUpdatePetWithForm(ref suppressDefaultLog, exception, pathFormat, path, petId, name, status); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdatePetWithForm(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, long petId, Option name, Option status); + + /// + /// Updates a pet in the store with form data + /// + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> UpdatePetWithFormOrDefaultAsync(long petId, Option name = default, Option status = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdatePetWithFormAsync(petId, name, status, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> UpdatePetWithFormAsync(long petId, Option name = default, Option status = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdatePetWithForm(name, status); + + FormatUpdatePetWithForm(ref petId, ref name, ref status); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); + + MultipartContent multipartContentLocalVar = new MultipartContent(); + + httpRequestMessageLocalVar.Content = multipartContentLocalVar; + + List> formParameterLocalVars = new List>(); + + multipartContentLocalVar.Add(new FormUrlEncodedContent(formParameterLocalVars)); if (name.IsSet) + formParameterLocalVars.Add(new KeyValuePair("name", ClientUtils.ParameterToString(name.Value))); + + if (status.IsSet) + formParameterLocalVars.Add(new KeyValuePair("status", ClientUtils.ParameterToString(status.Value))); + + List tokenBaseLocalVars = new List(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar); + + oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/pet/{petId}", requestedAtLocalVar, _jsonSerializerOptions); + + AfterUpdatePetWithFormDefaultImplementation(apiResponseLocalVar, petId, name, status); + + Events.ExecuteOnUpdatePetWithForm(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdatePetWithFormDefaultImplementation(e, "/pet/{petId}", uriBuilderLocalVar.Path, petId, name, status); + Events.ExecuteOnErrorUpdatePetWithForm(e); + throw; + } + } + + partial void FormatUploadFile(ref long petId, ref Option file, ref Option additionalMetadata); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUploadFile(Option file, Option additionalMetadata) + { + if (file.IsSet && file.Value == null) + throw new ArgumentNullException(nameof(file)); + + if (additionalMetadata.IsSet && additionalMetadata.Value == null) + throw new ArgumentNullException(nameof(additionalMetadata)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + private void AfterUploadFileDefaultImplementation(ApiResponse apiResponseLocalVar, long petId, Option file, Option additionalMetadata) + { + bool suppressDefaultLog = false; + AfterUploadFile(ref suppressDefaultLog, apiResponseLocalVar, petId, file, additionalMetadata); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + partial void AfterUploadFile(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, long petId, Option file, Option additionalMetadata); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + private void OnErrorUploadFileDefaultImplementation(Exception exception, string pathFormat, string path, long petId, Option file, Option additionalMetadata) + { + bool suppressDefaultLog = false; + OnErrorUploadFile(ref suppressDefaultLog, exception, pathFormat, path, petId, file, additionalMetadata); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUploadFile(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, long petId, Option file, Option additionalMetadata); + + /// + /// uploads an image + /// + /// ID of pet to update + /// file to upload (optional) + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> UploadFileOrDefaultAsync(long petId, Option file = default, Option additionalMetadata = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UploadFileAsync(petId, file, additionalMetadata, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload (optional) + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> UploadFileAsync(long petId, Option file = default, Option additionalMetadata = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUploadFile(file, additionalMetadata); + + FormatUploadFile(ref petId, ref file, ref additionalMetadata); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}/uploadImage"; + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); + + MultipartContent multipartContentLocalVar = new MultipartContent(); + + httpRequestMessageLocalVar.Content = multipartContentLocalVar; + + List> formParameterLocalVars = new List>(); + + multipartContentLocalVar.Add(new FormUrlEncodedContent(formParameterLocalVars)); if (file.IsSet) + multipartContentLocalVar.Add(new StreamContent(file.Value)); + + if (additionalMetadata.IsSet) + formParameterLocalVars.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata.Value))); + + List tokenBaseLocalVars = new List(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar); + + oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "multipart/form-data" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/pet/{petId}/uploadImage", requestedAtLocalVar, _apiResponseDeserializationContext.ApiResponse); + + AfterUploadFileDefaultImplementation(apiResponseLocalVar, petId, file, additionalMetadata); + + Events.ExecuteOnUploadFile(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUploadFileDefaultImplementation(e, "/pet/{petId}/uploadImage", uriBuilderLocalVar.Path, petId, file, additionalMetadata); + Events.ExecuteOnErrorUploadFile(e); + throw; + } + } + + partial void FormatUploadFileWithRequiredFile(ref System.IO.Stream requiredFile, ref long petId, ref Option additionalMetadata); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUploadFileWithRequiredFile(System.IO.Stream requiredFile, Option additionalMetadata) + { + if (requiredFile == null) + throw new ArgumentNullException(nameof(requiredFile)); + + if (additionalMetadata.IsSet && additionalMetadata.Value == null) + throw new ArgumentNullException(nameof(additionalMetadata)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + private void AfterUploadFileWithRequiredFileDefaultImplementation(ApiResponse apiResponseLocalVar, System.IO.Stream requiredFile, long petId, Option additionalMetadata) + { + bool suppressDefaultLog = false; + AfterUploadFileWithRequiredFile(ref suppressDefaultLog, apiResponseLocalVar, requiredFile, petId, additionalMetadata); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + partial void AfterUploadFileWithRequiredFile(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, System.IO.Stream requiredFile, long petId, Option additionalMetadata); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + private void OnErrorUploadFileWithRequiredFileDefaultImplementation(Exception exception, string pathFormat, string path, System.IO.Stream requiredFile, long petId, Option additionalMetadata) + { + bool suppressDefaultLog = false; + OnErrorUploadFileWithRequiredFile(ref suppressDefaultLog, exception, pathFormat, path, requiredFile, petId, additionalMetadata); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUploadFileWithRequiredFile(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, System.IO.Stream requiredFile, long petId, Option additionalMetadata); + + /// + /// uploads an image (required) + /// + /// file to upload + /// ID of pet to update + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> UploadFileWithRequiredFileOrDefaultAsync(System.IO.Stream requiredFile, long petId, Option additionalMetadata = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UploadFileWithRequiredFileAsync(requiredFile, petId, additionalMetadata, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// file to upload + /// ID of pet to update + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> UploadFileWithRequiredFileAsync(System.IO.Stream requiredFile, long petId, Option additionalMetadata = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUploadFileWithRequiredFile(requiredFile, additionalMetadata); + + FormatUploadFileWithRequiredFile(ref requiredFile, ref petId, ref additionalMetadata); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/{petId}/uploadImageWithRequiredFile"; + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); + + MultipartContent multipartContentLocalVar = new MultipartContent(); + + httpRequestMessageLocalVar.Content = multipartContentLocalVar; + + List> formParameterLocalVars = new List>(); + + multipartContentLocalVar.Add(new FormUrlEncodedContent(formParameterLocalVars)); multipartContentLocalVar.Add(new StreamContent(requiredFile)); + + if (additionalMetadata.IsSet) + formParameterLocalVars.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata.Value))); + + List tokenBaseLocalVars = new List(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar); + + oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "multipart/form-data" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/{petId}/uploadImageWithRequiredFile", requestedAtLocalVar, _apiResponseDeserializationContext.ApiResponse); + + AfterUploadFileWithRequiredFileDefaultImplementation(apiResponseLocalVar, requiredFile, petId, additionalMetadata); + + Events.ExecuteOnUploadFileWithRequiredFile(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUploadFileWithRequiredFileDefaultImplementation(e, "/fake/{petId}/uploadImageWithRequiredFile", uriBuilderLocalVar.Path, requiredFile, petId, additionalMetadata); + Events.ExecuteOnErrorUploadFileWithRequiredFile(e); + throw; + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/StoreApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/StoreApi.cs new file mode 100644 index 00000000000..78c789c85b7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/StoreApi.cs @@ -0,0 +1,824 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using UseSourceGeneration.Client; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + +namespace UseSourceGeneration.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IStoreApi : IApi + { + /// + /// The class containing the events + /// + StoreApiEvents Events { get; } + + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> DeleteOrderAsync(string orderId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> DeleteOrderOrDefaultAsync(string orderId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<Dictionary<string, int>>> + Task>> GetInventoryAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>Dictionary<string, int>>?> + Task>?> GetInventoryOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<Order>> + Task> GetOrderByIdAsync(long orderId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + /// + /// ID of pet that needs to be fetched + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>Order>?> + Task?> GetOrderByIdOrDefaultAsync(long orderId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<Order>> + Task> PlaceOrderAsync(Order order, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// order placed for purchasing the pet + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>Order>?> + Task?> PlaceOrderOrDefaultAsync(Order order, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public class StoreApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler>? OnDeleteOrder; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteOrder; + + internal void ExecuteOnDeleteOrder(ApiResponse apiResponse) + { + OnDeleteOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteOrder(Exception exception) + { + OnErrorDeleteOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>>? OnGetInventory; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetInventory; + + internal void ExecuteOnGetInventory(ApiResponse> apiResponse) + { + OnGetInventory?.Invoke(this, new ApiResponseEventArgs>(apiResponse)); + } + + internal void ExecuteOnErrorGetInventory(Exception exception) + { + OnErrorGetInventory?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnGetOrderById; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetOrderById; + + internal void ExecuteOnGetOrderById(ApiResponse apiResponse) + { + OnGetOrderById?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetOrderById(Exception exception) + { + OnErrorGetOrderById?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnPlaceOrder; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorPlaceOrder; + + internal void ExecuteOnPlaceOrder(ApiResponse apiResponse) + { + OnPlaceOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorPlaceOrder(Exception exception) + { + OnErrorPlaceOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class StoreApi : IStoreApi + { + private JsonSerializerOptions _jsonSerializerOptions; + private OrderDeserializationContext _orderDeserializationContext; + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public StoreApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider ApiKeyProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BearerTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BasicTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider HttpSignatureTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public StoreApi(ILogger logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, StoreApiEvents storeApiEvents, + OrderDeserializationContext orderDeserializationContext, + TokenProvider apiKeyProvider, + TokenProvider bearerTokenProvider, + TokenProvider basicTokenProvider, + TokenProvider httpSignatureTokenProvider, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + _orderDeserializationContext = orderDeserializationContext; + Logger = logger; + HttpClient = httpClient; + Events = storeApiEvents; + ApiKeyProvider = apiKeyProvider; + BearerTokenProvider = bearerTokenProvider; + BasicTokenProvider = basicTokenProvider; + HttpSignatureTokenProvider = httpSignatureTokenProvider; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatDeleteOrder(ref string orderId); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteOrder(string orderId) + { + if (orderId == null) + throw new ArgumentNullException(nameof(orderId)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteOrderDefaultImplementation(ApiResponse apiResponseLocalVar, string orderId) + { + bool suppressDefaultLog = false; + AfterDeleteOrder(ref suppressDefaultLog, apiResponseLocalVar, orderId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteOrder(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, string orderId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteOrderDefaultImplementation(Exception exception, string pathFormat, string path, string orderId) + { + bool suppressDefaultLog = false; + OnErrorDeleteOrder(ref suppressDefaultLog, exception, pathFormat, path, orderId); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteOrder(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, string orderId); + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> DeleteOrderOrDefaultAsync(string orderId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteOrderAsync(orderId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> DeleteOrderAsync(string orderId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteOrder(orderId); + + FormatDeleteOrder(ref orderId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/store/order/{order_id}"; + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Border_id%7D", Uri.EscapeDataString(orderId.ToString())); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/store/order/{order_id}", requestedAtLocalVar, _jsonSerializerOptions); + + AfterDeleteOrderDefaultImplementation(apiResponseLocalVar, orderId); + + Events.ExecuteOnDeleteOrder(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteOrderDefaultImplementation(e, "/store/order/{order_id}", uriBuilderLocalVar.Path, orderId); + Events.ExecuteOnErrorDeleteOrder(e); + throw; + } + } + + /// + /// Processes the server response + /// + /// + private void AfterGetInventoryDefaultImplementation(ApiResponse> apiResponseLocalVar) + { + bool suppressDefaultLog = false; + AfterGetInventory(ref suppressDefaultLog, apiResponseLocalVar); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + partial void AfterGetInventory(ref bool suppressDefaultLog, ApiResponse> apiResponseLocalVar); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + private void OnErrorGetInventoryDefaultImplementation(Exception exception, string pathFormat, string path) + { + bool suppressDefaultLog = false; + OnErrorGetInventory(ref suppressDefaultLog, exception, pathFormat, path); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + partial void OnErrorGetInventory(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path); + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>?> GetInventoryOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetInventoryAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task>> GetInventoryAsync(System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/store/inventory"; + + List tokenBaseLocalVars = new List(); + + ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(apiKeyTokenLocalVar); + + apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "api_key"); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse> apiResponseLocalVar = new ApiResponse>(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/store/inventory", requestedAtLocalVar, _jsonSerializerOptions); + + AfterGetInventoryDefaultImplementation(apiResponseLocalVar); + + Events.ExecuteOnGetInventory(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetInventoryDefaultImplementation(e, "/store/inventory", uriBuilderLocalVar.Path); + Events.ExecuteOnErrorGetInventory(e); + throw; + } + } + + partial void FormatGetOrderById(ref long orderId); + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetOrderByIdDefaultImplementation(ApiResponse apiResponseLocalVar, long orderId) + { + bool suppressDefaultLog = false; + AfterGetOrderById(ref suppressDefaultLog, apiResponseLocalVar, orderId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetOrderById(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, long orderId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetOrderByIdDefaultImplementation(Exception exception, string pathFormat, string path, long orderId) + { + bool suppressDefaultLog = false; + OnErrorGetOrderById(ref suppressDefaultLog, exception, pathFormat, path, orderId); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetOrderById(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, long orderId); + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + /// + /// ID of pet that needs to be fetched + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> GetOrderByIdOrDefaultAsync(long orderId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetOrderByIdAsync(orderId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> GetOrderByIdAsync(long orderId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + FormatGetOrderById(ref orderId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/store/order/{order_id}"; + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Border_id%7D", Uri.EscapeDataString(orderId.ToString())); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/xml", + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/store/order/{order_id}", requestedAtLocalVar, _orderDeserializationContext.Order); + + AfterGetOrderByIdDefaultImplementation(apiResponseLocalVar, orderId); + + Events.ExecuteOnGetOrderById(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetOrderByIdDefaultImplementation(e, "/store/order/{order_id}", uriBuilderLocalVar.Path, orderId); + Events.ExecuteOnErrorGetOrderById(e); + throw; + } + } + + partial void FormatPlaceOrder(Order order); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidatePlaceOrder(Order order) + { + if (order == null) + throw new ArgumentNullException(nameof(order)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterPlaceOrderDefaultImplementation(ApiResponse apiResponseLocalVar, Order order) + { + bool suppressDefaultLog = false; + AfterPlaceOrder(ref suppressDefaultLog, apiResponseLocalVar, order); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterPlaceOrder(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, Order order); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorPlaceOrderDefaultImplementation(Exception exception, string pathFormat, string path, Order order) + { + bool suppressDefaultLog = false; + OnErrorPlaceOrder(ref suppressDefaultLog, exception, pathFormat, path, order); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorPlaceOrder(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Order order); + + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> PlaceOrderOrDefaultAsync(Order order, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await PlaceOrderAsync(order, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> PlaceOrderAsync(Order order, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidatePlaceOrder(order); + + FormatPlaceOrder(order); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/store/order"; + + httpRequestMessageLocalVar.Content = (order as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(order, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/xml", + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/store/order", requestedAtLocalVar, _orderDeserializationContext.Order); + + AfterPlaceOrderDefaultImplementation(apiResponseLocalVar, order); + + Events.ExecuteOnPlaceOrder(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorPlaceOrderDefaultImplementation(e, "/store/order", uriBuilderLocalVar.Path, order); + Events.ExecuteOnErrorPlaceOrder(e); + throw; + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/UserApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/UserApi.cs new file mode 100644 index 00000000000..48f91095f80 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/UserApi.cs @@ -0,0 +1,1575 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using UseSourceGeneration.Client; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + +namespace UseSourceGeneration.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IUserApi : IApi + { + /// + /// The class containing the events + /// + UserApiEvents Events { get; } + + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> CreateUserAsync(User user, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Created user object + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> CreateUserOrDefaultAsync(User user, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> CreateUsersWithArrayInputAsync(List user, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// List of user object + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> CreateUsersWithArrayInputOrDefaultAsync(List user, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> CreateUsersWithListInputAsync(List user, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// List of user object + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> CreateUsersWithListInputOrDefaultAsync(List user, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> DeleteUserAsync(string username, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> DeleteUserOrDefaultAsync(string username, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get user by user name + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<User>> + Task> GetUserByNameAsync(string username, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get user by user name + /// + /// + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>User>?> + Task?> GetUserByNameOrDefaultAsync(string username, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<string>> + Task> LoginUserAsync(string username, string password, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Logs user into the system + /// + /// + /// + /// + /// The user name for login + /// The password for login in clear text + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>string>?> + Task?> LoginUserOrDefaultAsync(string username, string password, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> LogoutUserAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> LogoutUserOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Updated user object + /// name that need to be deleted + /// Cancellation Token to cancel the request. + /// Task<ApiResponse<object>> + Task> UpdateUserAsync(User user, string username, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Updated user object + /// name that need to be deleted + /// Cancellation Token to cancel the request. + /// Task<ApiResponse>object>?> + Task?> UpdateUserOrDefaultAsync(User user, string username, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public class UserApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler>? OnCreateUser; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateUser; + + internal void ExecuteOnCreateUser(ApiResponse apiResponse) + { + OnCreateUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateUser(Exception exception) + { + OnErrorCreateUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnCreateUsersWithArrayInput; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateUsersWithArrayInput; + + internal void ExecuteOnCreateUsersWithArrayInput(ApiResponse apiResponse) + { + OnCreateUsersWithArrayInput?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateUsersWithArrayInput(Exception exception) + { + OnErrorCreateUsersWithArrayInput?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnCreateUsersWithListInput; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateUsersWithListInput; + + internal void ExecuteOnCreateUsersWithListInput(ApiResponse apiResponse) + { + OnCreateUsersWithListInput?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateUsersWithListInput(Exception exception) + { + OnErrorCreateUsersWithListInput?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnDeleteUser; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteUser; + + internal void ExecuteOnDeleteUser(ApiResponse apiResponse) + { + OnDeleteUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteUser(Exception exception) + { + OnErrorDeleteUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnGetUserByName; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetUserByName; + + internal void ExecuteOnGetUserByName(ApiResponse apiResponse) + { + OnGetUserByName?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetUserByName(Exception exception) + { + OnErrorGetUserByName?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnLoginUser; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorLoginUser; + + internal void ExecuteOnLoginUser(ApiResponse apiResponse) + { + OnLoginUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorLoginUser(Exception exception) + { + OnErrorLoginUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnLogoutUser; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorLogoutUser; + + internal void ExecuteOnLogoutUser(ApiResponse apiResponse) + { + OnLogoutUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorLogoutUser(Exception exception) + { + OnErrorLogoutUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler>? OnUpdateUser; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdateUser; + + internal void ExecuteOnUpdateUser(ApiResponse apiResponse) + { + OnUpdateUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateUser(Exception exception) + { + OnErrorUpdateUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class UserApi : IUserApi + { + private JsonSerializerOptions _jsonSerializerOptions; + private UserDeserializationContext _userDeserializationContext; + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public UserApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider ApiKeyProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BearerTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider BasicTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider HttpSignatureTokenProvider { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public UserApi(ILogger logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, UserApiEvents userApiEvents, + UserDeserializationContext userDeserializationContext, + TokenProvider apiKeyProvider, + TokenProvider bearerTokenProvider, + TokenProvider basicTokenProvider, + TokenProvider httpSignatureTokenProvider, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + _userDeserializationContext = userDeserializationContext; + Logger = logger; + HttpClient = httpClient; + Events = userApiEvents; + ApiKeyProvider = apiKeyProvider; + BearerTokenProvider = bearerTokenProvider; + BasicTokenProvider = basicTokenProvider; + HttpSignatureTokenProvider = httpSignatureTokenProvider; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateUser(User user); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateUser(User user) + { + if (user == null) + throw new ArgumentNullException(nameof(user)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateUserDefaultImplementation(ApiResponse apiResponseLocalVar, User user) + { + bool suppressDefaultLog = false; + AfterCreateUser(ref suppressDefaultLog, apiResponseLocalVar, user); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateUser(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, User user); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateUserDefaultImplementation(Exception exception, string pathFormat, string path, User user) + { + bool suppressDefaultLog = false; + OnErrorCreateUser(ref suppressDefaultLog, exception, pathFormat, path, user); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateUser(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, User user); + + /// + /// Create user This can only be done by the logged in user. + /// + /// Created user object + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> CreateUserOrDefaultAsync(User user, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateUserAsync(user, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> CreateUserAsync(User user, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateUser(user); + + FormatCreateUser(user); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/user"; + + httpRequestMessageLocalVar.Content = (user as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/user", requestedAtLocalVar, _jsonSerializerOptions); + + AfterCreateUserDefaultImplementation(apiResponseLocalVar, user); + + Events.ExecuteOnCreateUser(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateUserDefaultImplementation(e, "/user", uriBuilderLocalVar.Path, user); + Events.ExecuteOnErrorCreateUser(e); + throw; + } + } + + partial void FormatCreateUsersWithArrayInput(List user); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateUsersWithArrayInput(List user) + { + if (user == null) + throw new ArgumentNullException(nameof(user)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateUsersWithArrayInputDefaultImplementation(ApiResponse apiResponseLocalVar, List user) + { + bool suppressDefaultLog = false; + AfterCreateUsersWithArrayInput(ref suppressDefaultLog, apiResponseLocalVar, user); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateUsersWithArrayInput(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, List user); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateUsersWithArrayInputDefaultImplementation(Exception exception, string pathFormat, string path, List user) + { + bool suppressDefaultLog = false; + OnErrorCreateUsersWithArrayInput(ref suppressDefaultLog, exception, pathFormat, path, user); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateUsersWithArrayInput(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, List user); + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> CreateUsersWithArrayInputOrDefaultAsync(List user, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateUsersWithArrayInputAsync(user, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> CreateUsersWithArrayInputAsync(List user, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateUsersWithArrayInput(user); + + FormatCreateUsersWithArrayInput(user); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/user/createWithArray"; + + httpRequestMessageLocalVar.Content = (user as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/user/createWithArray", requestedAtLocalVar, _jsonSerializerOptions); + + AfterCreateUsersWithArrayInputDefaultImplementation(apiResponseLocalVar, user); + + Events.ExecuteOnCreateUsersWithArrayInput(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateUsersWithArrayInputDefaultImplementation(e, "/user/createWithArray", uriBuilderLocalVar.Path, user); + Events.ExecuteOnErrorCreateUsersWithArrayInput(e); + throw; + } + } + + partial void FormatCreateUsersWithListInput(List user); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateUsersWithListInput(List user) + { + if (user == null) + throw new ArgumentNullException(nameof(user)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateUsersWithListInputDefaultImplementation(ApiResponse apiResponseLocalVar, List user) + { + bool suppressDefaultLog = false; + AfterCreateUsersWithListInput(ref suppressDefaultLog, apiResponseLocalVar, user); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateUsersWithListInput(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, List user); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateUsersWithListInputDefaultImplementation(Exception exception, string pathFormat, string path, List user) + { + bool suppressDefaultLog = false; + OnErrorCreateUsersWithListInput(ref suppressDefaultLog, exception, pathFormat, path, user); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateUsersWithListInput(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, List user); + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> CreateUsersWithListInputOrDefaultAsync(List user, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateUsersWithListInputAsync(user, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> CreateUsersWithListInputAsync(List user, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateUsersWithListInput(user); + + FormatCreateUsersWithListInput(user); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/user/createWithList"; + + httpRequestMessageLocalVar.Content = (user as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/user/createWithList", requestedAtLocalVar, _jsonSerializerOptions); + + AfterCreateUsersWithListInputDefaultImplementation(apiResponseLocalVar, user); + + Events.ExecuteOnCreateUsersWithListInput(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateUsersWithListInputDefaultImplementation(e, "/user/createWithList", uriBuilderLocalVar.Path, user); + Events.ExecuteOnErrorCreateUsersWithListInput(e); + throw; + } + } + + partial void FormatDeleteUser(ref string username); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteUser(string username) + { + if (username == null) + throw new ArgumentNullException(nameof(username)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteUserDefaultImplementation(ApiResponse apiResponseLocalVar, string username) + { + bool suppressDefaultLog = false; + AfterDeleteUser(ref suppressDefaultLog, apiResponseLocalVar, username); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteUser(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, string username); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteUserDefaultImplementation(Exception exception, string pathFormat, string path, string username) + { + bool suppressDefaultLog = false; + OnErrorDeleteUser(ref suppressDefaultLog, exception, pathFormat, path, username); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteUser(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, string username); + + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> DeleteUserOrDefaultAsync(string username, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteUserAsync(username, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> DeleteUserAsync(string username, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteUser(username); + + FormatDeleteUser(ref username); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/user/{username}", requestedAtLocalVar, _jsonSerializerOptions); + + AfterDeleteUserDefaultImplementation(apiResponseLocalVar, username); + + Events.ExecuteOnDeleteUser(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteUserDefaultImplementation(e, "/user/{username}", uriBuilderLocalVar.Path, username); + Events.ExecuteOnErrorDeleteUser(e); + throw; + } + } + + partial void FormatGetUserByName(ref string username); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetUserByName(string username) + { + if (username == null) + throw new ArgumentNullException(nameof(username)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetUserByNameDefaultImplementation(ApiResponse apiResponseLocalVar, string username) + { + bool suppressDefaultLog = false; + AfterGetUserByName(ref suppressDefaultLog, apiResponseLocalVar, username); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetUserByName(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, string username); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetUserByNameDefaultImplementation(Exception exception, string pathFormat, string path, string username) + { + bool suppressDefaultLog = false; + OnErrorGetUserByName(ref suppressDefaultLog, exception, pathFormat, path, username); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetUserByName(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, string username); + + /// + /// Get user by user name + /// + /// The name that needs to be fetched. Use user1 for testing. + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> GetUserByNameOrDefaultAsync(string username, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetUserByNameAsync(username, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> GetUserByNameAsync(string username, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetUserByName(username); + + FormatGetUserByName(ref username); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/xml", + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/user/{username}", requestedAtLocalVar, _userDeserializationContext.User); + + AfterGetUserByNameDefaultImplementation(apiResponseLocalVar, username); + + Events.ExecuteOnGetUserByName(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetUserByNameDefaultImplementation(e, "/user/{username}", uriBuilderLocalVar.Path, username); + Events.ExecuteOnErrorGetUserByName(e); + throw; + } + } + + partial void FormatLoginUser(ref string username, ref string password); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateLoginUser(string username, string password) + { + if (username == null) + throw new ArgumentNullException(nameof(username)); + + if (password == null) + throw new ArgumentNullException(nameof(password)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterLoginUserDefaultImplementation(ApiResponse apiResponseLocalVar, string username, string password) + { + bool suppressDefaultLog = false; + AfterLoginUser(ref suppressDefaultLog, apiResponseLocalVar, username, password); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterLoginUser(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, string username, string password); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorLoginUserDefaultImplementation(Exception exception, string pathFormat, string path, string username, string password) + { + bool suppressDefaultLog = false; + OnErrorLoginUser(ref suppressDefaultLog, exception, pathFormat, path, username, password); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorLoginUser(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, string username, string password); + + /// + /// Logs user into the system + /// + /// The user name for login + /// The password for login in clear text + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> LoginUserOrDefaultAsync(string username, string password, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await LoginUserAsync(username, password, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> LoginUserAsync(string username, string password, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateLoginUser(username, password); + + FormatLoginUser(ref username, ref password); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/user/login"; + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryStringLocalVar["username"] = username.ToString(); + parseQueryStringLocalVar["password"] = password.ToString(); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/xml", + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/user/login", requestedAtLocalVar, _jsonSerializerOptions); + + AfterLoginUserDefaultImplementation(apiResponseLocalVar, username, password); + + Events.ExecuteOnLoginUser(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorLoginUserDefaultImplementation(e, "/user/login", uriBuilderLocalVar.Path, username, password); + Events.ExecuteOnErrorLoginUser(e); + throw; + } + } + + /// + /// Processes the server response + /// + /// + private void AfterLogoutUserDefaultImplementation(ApiResponse apiResponseLocalVar) + { + bool suppressDefaultLog = false; + AfterLogoutUser(ref suppressDefaultLog, apiResponseLocalVar); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + partial void AfterLogoutUser(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + private void OnErrorLogoutUserDefaultImplementation(Exception exception, string pathFormat, string path) + { + bool suppressDefaultLog = false; + OnErrorLogoutUser(ref suppressDefaultLog, exception, pathFormat, path); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + partial void OnErrorLogoutUser(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path); + + /// + /// Logs out current logged in user session + /// + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> LogoutUserOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await LogoutUserAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> LogoutUserAsync(System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/user/logout"; + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/user/logout", requestedAtLocalVar, _jsonSerializerOptions); + + AfterLogoutUserDefaultImplementation(apiResponseLocalVar); + + Events.ExecuteOnLogoutUser(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorLogoutUserDefaultImplementation(e, "/user/logout", uriBuilderLocalVar.Path); + Events.ExecuteOnErrorLogoutUser(e); + throw; + } + } + + partial void FormatUpdateUser(User user, ref string username); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdateUser(User user, string username) + { + if (user == null) + throw new ArgumentNullException(nameof(user)); + + if (username == null) + throw new ArgumentNullException(nameof(username)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterUpdateUserDefaultImplementation(ApiResponse apiResponseLocalVar, User user, string username) + { + bool suppressDefaultLog = false; + AfterUpdateUser(ref suppressDefaultLog, apiResponseLocalVar, user, username); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterUpdateUser(ref bool suppressDefaultLog, ApiResponse apiResponseLocalVar, User user, string username); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorUpdateUserDefaultImplementation(Exception exception, string pathFormat, string path, User user, string username) + { + bool suppressDefaultLog = false; + OnErrorUpdateUser(ref suppressDefaultLog, exception, pathFormat, path, user, username); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdateUser(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, User user, string username); + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Updated user object + /// name that need to be deleted + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task?> UpdateUserOrDefaultAsync(User user, string username, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdateUserAsync(user, username, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Updated user object + /// name that need to be deleted + /// Cancellation Token to cancel the request. + /// <> where T : + public async Task> UpdateUserAsync(User user, string username, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdateUser(user, username); + + FormatUpdateUser(user, ref username); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/user/{username}"; + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Busername%7D", Uri.EscapeDataString(username.ToString())); + + httpRequestMessageLocalVar.Content = (user as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(user, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ApiResponse apiResponseLocalVar = new ApiResponse(httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/user/{username}", requestedAtLocalVar, _jsonSerializerOptions); + + AfterUpdateUserDefaultImplementation(apiResponseLocalVar, user, username); + + Events.ExecuteOnUpdateUser(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdateUserDefaultImplementation(e, "/user/{username}", uriBuilderLocalVar.Path, user, username); + Events.ExecuteOnErrorUpdateUser(e); + throw; + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiException.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiException.cs new file mode 100644 index 00000000000..a74619ac03f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiException.cs @@ -0,0 +1,52 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; + +namespace UseSourceGeneration.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// The reason the api request failed + /// + public string? ReasonPhrase { get; } + + /// + /// The HttpStatusCode + /// + public System.Net.HttpStatusCode StatusCode { get; } + + /// + /// The raw data returned by the api + /// + public string RawContent { get; } + + /// + /// Construct the ApiException from parts of the response + /// + /// + /// + /// + public ApiException(string? reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent) : base(reasonPhrase ?? rawContent) + { + ReasonPhrase = reasonPhrase; + + StatusCode = statusCode; + + RawContent = rawContent; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiFactory.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiFactory.cs new file mode 100644 index 00000000000..220be1d09d4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiFactory.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Api; + +namespace UseSourceGeneration.Client +{ + /// + /// An IApiFactory interface + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi; + } + + /// + /// An ApiFactory + /// + public class ApiFactory : IApiFactory + { + /// + /// The service provider + /// + public IServiceProvider Services { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ApiFactory(IServiceProvider services) + { + Services = services; + } + + /// + /// A method to create an IApi of type IResult + /// + /// + /// + public IResult Create() where IResult : IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiKeyToken.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiKeyToken.cs new file mode 100644 index 00000000000..532b5eaa2d4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiKeyToken.cs @@ -0,0 +1,49 @@ +// + +#nullable enable + +using System; + +namespace UseSourceGeneration.Client +{ + /// + /// A token constructed from an apiKey. + /// + public class ApiKeyToken : TokenBase + { + private string _raw; + + /// + /// Constructs an ApiKeyToken object. + /// + /// + /// + /// + public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) + { + _raw = $"{ prefix }{ value }"; + } + + /// + /// Places the token in the header. + /// + /// + /// + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + { + request.Headers.Add(headerName, _raw); + } + + /// + /// Places the token in the query. + /// + /// + /// + /// + /// + public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString, string parameterName) + { + parseQueryString[parameterName] = Uri.EscapeDataString(_raw).ToString()!; + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiResponseEventArgs.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiResponseEventArgs.cs new file mode 100644 index 00000000000..a2428008e18 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiResponseEventArgs.cs @@ -0,0 +1,24 @@ +using System; + +namespace UseSourceGeneration.Client +{ + /// + /// Useful for tracking server health + /// + public class ApiResponseEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public ApiResponse ApiResponse { get; } + + /// + /// The ApiResponseEventArgs + /// + /// + public ApiResponseEventArgs(ApiResponse apiResponse) + { + ApiResponse = apiResponse; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiResponse`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiResponse`1.cs new file mode 100644 index 00000000000..72cffa4c55c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiResponse`1.cs @@ -0,0 +1,205 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; + +namespace UseSourceGeneration.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The type that represents the server's response. + /// + Type ResponseType { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// The raw content of this response. + /// + string RawContent { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } + + /// + /// The path used when making the request. + /// + string Path { get; } + + /// + /// The Uri used when making the request. + /// + Uri? RequestUri { get; } + } + + /// + /// API Response + /// + public partial class ApiResponse : IApiResponse + { + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// The type that represents the server's response. + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The raw data + /// + public string RawContent { get; private set; } + + /// + /// The IsSuccessStatusCode from the api response + /// + public bool IsSuccessStatusCode { get; } + + /// + /// The reason phrase contained in the api response + /// + public string? ReasonPhrase { get; } + + /// + /// The headers contained in the api response + /// + public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; + + /// + /// The DateTime when the request was sent. + /// + public DateTime RequestedAt { get; } + + /// + /// The path used when making the request. + /// + public string Path { get; } + + /// + /// The Uri used when making the request. + /// + public Uri? RequestUri { get; } + + /// + /// The JsonSerialzierOptions + /// + private System.Text.Json.JsonSerializerOptions? _jsonSerializerOptions; + + /// + /// The JsonTypeInfo + /// + private readonly System.Text.Json.Serialization.Metadata.JsonTypeInfo? _typeInfo; + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + /// + /// + /// + /// + public ApiResponse(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.Serialization.Metadata.JsonTypeInfo typeInfo) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + RawContent = rawContent; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _typeInfo = typeInfo; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + /// + /// + /// + /// + public ApiResponse(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + RawContent = rawContent; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Deserializes the server's response + /// + public T? AsModel() + { + // This logic may be modified with the AsModel.mustache template + if (!IsSuccessStatusCode) + return default(T); + + return _typeInfo == null + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : System.Text.Json.JsonSerializer.Deserialize(RawContent, _typeInfo); + } + + /// + /// Returns true when the model can be deserialized + /// + public bool TryToModel([NotNullWhen(true)] out T? model) + { + try + { + model = AsModel(); + return model != null; + } + catch + { + model = default(T); + return false; + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/BasicToken.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/BasicToken.cs new file mode 100644 index 00000000000..9adf13b4662 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/BasicToken.cs @@ -0,0 +1,44 @@ +// + +#nullable enable + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace UseSourceGeneration.Client +{ + /// + /// A token constructed from a username and password. + /// + public class BasicToken : TokenBase + { + private string _username; + + private string _password; + + /// + /// Constructs a BasicToken object. + /// + /// + /// + /// + public BasicToken(string username, string password, TimeSpan? timeout = null) : base(timeout) + { + _username = username; + + _password = password; + } + + /// + /// Places the token in the header. + /// + /// + /// + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + { + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", UseSourceGeneration.Client.ClientUtils.Base64Encode(_username + ":" + _password)); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/BearerToken.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/BearerToken.cs new file mode 100644 index 00000000000..c82eee7de32 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/BearerToken.cs @@ -0,0 +1,39 @@ +// + +#nullable enable + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace UseSourceGeneration.Client +{ + /// + /// A token constructed from a token from a bearer token. + /// + public class BearerToken : TokenBase + { + private string _raw; + + /// + /// Constructs a BearerToken object. + /// + /// + /// + public BearerToken(string value, TimeSpan? timeout = null) : base(timeout) + { + _raw = value; + } + + /// + /// Places the token in the header. + /// + /// + /// + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + { + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _raw); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ClientUtils.cs new file mode 100644 index 00000000000..a4f8e6df40d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ClientUtils.cs @@ -0,0 +1,332 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using KellermanSoftware.CompareNetObjects; +using UseSourceGeneration.Model; +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("UseSourceGeneration.Test")] + +namespace UseSourceGeneration.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static constructor to initialise compareLogic. + /// + static ClientUtils() + { + compareLogic = new CompareLogic(); + } + + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is bool boolean) + return boolean + ? "true" + : "false"; + if (obj is ChildCat.PetTypeEnum childCatPetTypeEnum) + return ChildCat.PetTypeEnumToJsonValue(childCatPetTypeEnum); + if (obj is EnumArrays.ArrayEnumEnum enumArraysArrayEnumEnum) + return EnumArrays.ArrayEnumEnumToJsonValue(enumArraysArrayEnumEnum); + if (obj is EnumArrays.JustSymbolEnum enumArraysJustSymbolEnum) + return EnumArrays.JustSymbolEnumToJsonValue(enumArraysJustSymbolEnum); + if (obj is EnumClass enumClass) + return EnumClassValueConverter.ToJsonValue(enumClass); + if (obj is EnumTest.EnumIntegerEnum enumTestEnumIntegerEnum) + return EnumTest.EnumIntegerEnumToJsonValue(enumTestEnumIntegerEnum).ToString(); + if (obj is EnumTest.EnumIntegerOnlyEnum enumTestEnumIntegerOnlyEnum) + return EnumTest.EnumIntegerOnlyEnumToJsonValue(enumTestEnumIntegerOnlyEnum).ToString(); + if (obj is EnumTest.EnumNumberEnum enumTestEnumNumberEnum) + return EnumTest.EnumNumberEnumToJsonValue(enumTestEnumNumberEnum).ToString(); + if (obj is EnumTest.EnumStringEnum enumTestEnumStringEnum) + return EnumTest.EnumStringEnumToJsonValue(enumTestEnumStringEnum); + if (obj is EnumTest.EnumStringRequiredEnum enumTestEnumStringRequiredEnum) + return EnumTest.EnumStringRequiredEnumToJsonValue(enumTestEnumStringRequiredEnum); + if (obj is MapTest.InnerEnum mapTestInnerEnum) + return MapTest.InnerEnumToJsonValue(mapTestInnerEnum); + if (obj is Order.StatusEnum orderStatusEnum) + return Order.StatusEnumToJsonValue(orderStatusEnum); + if (obj is OuterEnum outerEnum) + return OuterEnumValueConverter.ToJsonValue(outerEnum); + if (obj is OuterEnumDefaultValue outerEnumDefaultValue) + return OuterEnumDefaultValueValueConverter.ToJsonValue(outerEnumDefaultValue); + if (obj is OuterEnumInteger outerEnumInteger) + return OuterEnumIntegerValueConverter.ToJsonValue(outerEnumInteger).ToString(); + if (obj is OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) + return OuterEnumIntegerDefaultValueValueConverter.ToJsonValue(outerEnumIntegerDefaultValue).ToString(); + if (obj is OuterEnumTest outerEnumTest) + return OuterEnumTestValueConverter.ToJsonValue(outerEnumTest); + if (obj is Pet.StatusEnum petStatusEnum) + return Pet.StatusEnumToJsonValue(petStatusEnum); + if (obj is Zebra.TypeEnum zebraTypeEnum) + return Zebra.TypeEnumToJsonValue(zebraTypeEnum); + if (obj is ZeroBasedEnum zeroBasedEnum) + return ZeroBasedEnumValueConverter.ToJsonValue(zeroBasedEnum); + if (obj is ZeroBasedEnumClass.ZeroBasedEnumEnum zeroBasedEnumClassZeroBasedEnumEnum) + return ZeroBasedEnumClass.ZeroBasedEnumEnumToJsonValue(zeroBasedEnumClassZeroBasedEnumEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// The base path of the API + /// + public const string BASE_ADDRESS = "http://petstore.swagger.io:80/v2"; + + /// + /// The scheme of the API + /// + public const string SCHEME = "http"; + + /// + /// The context path of the API + /// + public const string CONTEXT_PATH = "/v2"; + + /// + /// The host of the API + /// + public const string HOST = "petstore.swagger.io"; + + /// + /// The format to use for DateTime serialization + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/CookieContainer.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/CookieContainer.cs new file mode 100644 index 00000000000..b676a76a894 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/CookieContainer.cs @@ -0,0 +1,20 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace UseSourceGeneration.Client +{ + /// + /// A class containing a CookieContainer + /// + public sealed class CookieContainer + { + /// + /// The collection of tokens + /// + public System.Net.CookieContainer Value { get; } = new System.Net.CookieContainer(); + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeJsonConverter.cs new file mode 100644 index 00000000000..4c66712a3e3 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeJsonConverter.cs @@ -0,0 +1,76 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace UseSourceGeneration.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyy'-'MM'-'dd", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + "yyyyMMdd" + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateTimeValue.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeNullableJsonConverter.cs new file mode 100644 index 00000000000..e341a77d5cd --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeNullableJsonConverter.cs @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace UseSourceGeneration.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyy'-'MM'-'dd", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + "yyyyMMdd" + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + return null; + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime? dateTimeValue, JsonSerializerOptions options) + { + if (dateTimeValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateTimeValue.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ExceptionEventArgs.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ExceptionEventArgs.cs new file mode 100644 index 00000000000..43d7997d7c0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ExceptionEventArgs.cs @@ -0,0 +1,24 @@ +using System; + +namespace UseSourceGeneration.Client +{ + /// + /// Useful for tracking server health + /// + public class ExceptionEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public Exception Exception { get; } + + /// + /// The ExcepetionEventArgs + /// + /// + public ExceptionEventArgs(Exception exception) + { + Exception = exception; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HostConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HostConfiguration.cs new file mode 100644 index 00000000000..d49c84acdea --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HostConfiguration.cs @@ -0,0 +1,422 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Api; +using UseSourceGeneration.Model; + +namespace UseSourceGeneration.Client +{ + /// + /// Provides hosting configuration for UseSourceGeneration + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + + internal bool HttpClientsAdded { get; private set; } + + /// + /// Instantiates the class + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new ActivityJsonConverter()); + _jsonOptions.Converters.Add(new ActivityOutputElementRepresentationJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalPropertiesClassJsonConverter()); + _jsonOptions.Converters.Add(new AnimalJsonConverter()); + _jsonOptions.Converters.Add(new ApiResponseJsonConverter()); + _jsonOptions.Converters.Add(new AppleJsonConverter()); + _jsonOptions.Converters.Add(new AppleReqJsonConverter()); + _jsonOptions.Converters.Add(new ArrayOfArrayOfNumberOnlyJsonConverter()); + _jsonOptions.Converters.Add(new ArrayOfNumberOnlyJsonConverter()); + _jsonOptions.Converters.Add(new ArrayTestJsonConverter()); + _jsonOptions.Converters.Add(new BananaJsonConverter()); + _jsonOptions.Converters.Add(new BananaReqJsonConverter()); + _jsonOptions.Converters.Add(new BasquePigJsonConverter()); + _jsonOptions.Converters.Add(new CapitalizationJsonConverter()); + _jsonOptions.Converters.Add(new CatJsonConverter()); + _jsonOptions.Converters.Add(new CategoryJsonConverter()); + _jsonOptions.Converters.Add(new ChildCatJsonConverter()); + _jsonOptions.Converters.Add(new ClassModelJsonConverter()); + _jsonOptions.Converters.Add(new ComplexQuadrilateralJsonConverter()); + _jsonOptions.Converters.Add(new DanishPigJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyClassJsonConverter()); + _jsonOptions.Converters.Add(new DeprecatedObjectJsonConverter()); + _jsonOptions.Converters.Add(new DogJsonConverter()); + _jsonOptions.Converters.Add(new DrawingJsonConverter()); + _jsonOptions.Converters.Add(new EnumArraysJsonConverter()); + _jsonOptions.Converters.Add(new EnumClassJsonConverter()); + _jsonOptions.Converters.Add(new EnumClassNullableJsonConverter()); + _jsonOptions.Converters.Add(new EnumTestJsonConverter()); + _jsonOptions.Converters.Add(new EquilateralTriangleJsonConverter()); + _jsonOptions.Converters.Add(new FileJsonConverter()); + _jsonOptions.Converters.Add(new FileSchemaTestClassJsonConverter()); + _jsonOptions.Converters.Add(new FooJsonConverter()); + _jsonOptions.Converters.Add(new FooGetDefaultResponseJsonConverter()); + _jsonOptions.Converters.Add(new FormatTestJsonConverter()); + _jsonOptions.Converters.Add(new FruitJsonConverter()); + _jsonOptions.Converters.Add(new FruitReqJsonConverter()); + _jsonOptions.Converters.Add(new GmFruitJsonConverter()); + _jsonOptions.Converters.Add(new GrandparentAnimalJsonConverter()); + _jsonOptions.Converters.Add(new HasOnlyReadOnlyJsonConverter()); + _jsonOptions.Converters.Add(new HealthCheckResultJsonConverter()); + _jsonOptions.Converters.Add(new IsoscelesTriangleJsonConverter()); + _jsonOptions.Converters.Add(new ListJsonConverter()); + _jsonOptions.Converters.Add(new LiteralStringClassJsonConverter()); + _jsonOptions.Converters.Add(new MammalJsonConverter()); + _jsonOptions.Converters.Add(new MapTestJsonConverter()); + _jsonOptions.Converters.Add(new MixedPropertiesAndAdditionalPropertiesClassJsonConverter()); + _jsonOptions.Converters.Add(new Model200ResponseJsonConverter()); + _jsonOptions.Converters.Add(new ModelClientJsonConverter()); + _jsonOptions.Converters.Add(new NameJsonConverter()); + _jsonOptions.Converters.Add(new NotificationtestGetElementsV1ResponseMPayloadJsonConverter()); + _jsonOptions.Converters.Add(new NullableClassJsonConverter()); + _jsonOptions.Converters.Add(new NullableGuidClassJsonConverter()); + _jsonOptions.Converters.Add(new NullableShapeJsonConverter()); + _jsonOptions.Converters.Add(new NumberOnlyJsonConverter()); + _jsonOptions.Converters.Add(new ObjectWithDeprecatedFieldsJsonConverter()); + _jsonOptions.Converters.Add(new OneOfStringJsonConverter()); + _jsonOptions.Converters.Add(new OrderJsonConverter()); + _jsonOptions.Converters.Add(new OuterCompositeJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumNullableJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumDefaultValueJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumDefaultValueNullableJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerNullableJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerDefaultValueJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumIntegerDefaultValueNullableJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumTestJsonConverter()); + _jsonOptions.Converters.Add(new OuterEnumTestNullableJsonConverter()); + _jsonOptions.Converters.Add(new ParentPetJsonConverter()); + _jsonOptions.Converters.Add(new PetJsonConverter()); + _jsonOptions.Converters.Add(new PigJsonConverter()); + _jsonOptions.Converters.Add(new PolymorphicPropertyJsonConverter()); + _jsonOptions.Converters.Add(new QuadrilateralJsonConverter()); + _jsonOptions.Converters.Add(new QuadrilateralInterfaceJsonConverter()); + _jsonOptions.Converters.Add(new ReadOnlyFirstJsonConverter()); + _jsonOptions.Converters.Add(new ReturnJsonConverter()); + _jsonOptions.Converters.Add(new RolesReportsHashJsonConverter()); + _jsonOptions.Converters.Add(new RolesReportsHashRoleJsonConverter()); + _jsonOptions.Converters.Add(new ScaleneTriangleJsonConverter()); + _jsonOptions.Converters.Add(new ShapeJsonConverter()); + _jsonOptions.Converters.Add(new ShapeInterfaceJsonConverter()); + _jsonOptions.Converters.Add(new ShapeOrNullJsonConverter()); + _jsonOptions.Converters.Add(new SimpleQuadrilateralJsonConverter()); + _jsonOptions.Converters.Add(new SpecialModelNameJsonConverter()); + _jsonOptions.Converters.Add(new TagJsonConverter()); + _jsonOptions.Converters.Add(new TestCollectionEndingWithWordListJsonConverter()); + _jsonOptions.Converters.Add(new TestCollectionEndingWithWordListObjectJsonConverter()); + _jsonOptions.Converters.Add(new TriangleJsonConverter()); + _jsonOptions.Converters.Add(new TriangleInterfaceJsonConverter()); + _jsonOptions.Converters.Add(new UserJsonConverter()); + _jsonOptions.Converters.Add(new WhaleJsonConverter()); + _jsonOptions.Converters.Add(new ZebraJsonConverter()); + _jsonOptions.Converters.Add(new ZeroBasedEnumJsonConverter()); + _jsonOptions.Converters.Add(new ZeroBasedEnumNullableJsonConverter()); + _jsonOptions.Converters.Add(new ZeroBasedEnumClassJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddTransient(); + _services.AddSingleton(); + _services.AddTransient(); + _services.AddSingleton(); + _services.AddTransient(); + _services.AddSingleton(); + _services.AddTransient(); + _services.AddSingleton(); + _services.AddTransient(); + _services.AddSingleton(); + _services.AddTransient(); + _services.AddSingleton(); + _services.AddTransient(); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration AddApiHttpClients + ( + Action? client = null, Action? builder = null) + { + if (client == null) + client = c => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); + + List builders = new List(); + + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + + if (builder != null) + foreach (IHttpClientBuilder instance in builders) + builder(instance); + + HttpClientsAdded = true; + + return this; + } + + /// + /// Configures the JsonSerializerSettings + /// + /// + /// + public HostConfiguration ConfigureJsonOptions(Action options) + { + options(_jsonOptions); + + return this; + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + { + return AddTokens(new TTokenBase[]{ token }); + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + { + TokenContainer container = new TokenContainer(tokens); + _services.AddSingleton(services => container); + + return this; + } + + /// + /// Adds a token provider to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration UseProvider() + where TTokenProvider : TokenProvider + where TTokenBase : TokenBase + { + _services.AddSingleton(); + _services.AddSingleton>(services => services.GetRequiredService()); + + return this; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HttpSigningConfiguration.cs new file mode 100644 index 00000000000..d0350fcea0d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HttpSigningConfiguration.cs @@ -0,0 +1,679 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Cryptography; +using System.Text; +using System.Web; + +namespace UseSourceGeneration.Client +{ + /// + /// Class for HttpSigning auth related parameter and methods + /// + public class HttpSigningConfiguration + { + /// + /// Create an instance + /// + public HttpSigningConfiguration(string keyId, string keyFilePath, SecureString? keyPassPhrase, List httpSigningHeader, HashAlgorithmName hashAlgorithm, string signingAlgorithm, int signatureValidityPeriod) + { + KeyId = keyId; + KeyFilePath = keyFilePath; + KeyPassPhrase = keyPassPhrase; + HttpSigningHeader = httpSigningHeader; + HashAlgorithm = hashAlgorithm; + SigningAlgorithm = signingAlgorithm; + SignatureValidityPeriod = signatureValidityPeriod; + } + + /// + ///Gets the Api keyId + /// + public string KeyId { get; set; } + + /// + /// Gets the Key file path + /// + public string KeyFilePath { get; set; } + + /// + /// Gets the key pass phrase for password protected key + /// + public SecureString? KeyPassPhrase { get; set; } + + /// + /// Gets the HTTP signing header + /// + public List HttpSigningHeader { get; set; } + + /// + /// Gets the hash algorithm sha256 or sha512 + /// + public HashAlgorithmName HashAlgorithm { get; set; } = HashAlgorithmName.SHA256; + + /// + /// Gets the signing algorithm + /// + public string SigningAlgorithm { get; set; } + + /// + /// Gets the Signature validaty period in seconds + /// + public int SignatureValidityPeriod { get; set; } + + private enum PrivateKeyType + { + None = 0, + RSA = 1, + ECDSA = 2, + } + + /// + /// Gets the Headers for HttpSigning + /// + /// + /// + /// + internal Dictionary GetHttpSignedHeader(System.Net.Http.HttpRequestMessage request, string requestBody, System.Threading.CancellationToken cancellationToken = default) + { + if (request.RequestUri == null) + throw new NullReferenceException("The request URI was null"); + + const string HEADER_REQUEST_TARGET = "(request-target)"; + + // The time when the HTTP signature expires. The API server should reject HTTP requests that have expired. + const string HEADER_EXPIRES = "(expires)"; + + //The 'Date' header. + const string HEADER_DATE = "Date"; + + //The 'Host' header. + const string HEADER_HOST = "Host"; + + //The time when the HTTP signature was generated. + const string HEADER_CREATED = "(created)"; + + //When the 'Digest' header is included in the HTTP signature, the client automatically + //computes the digest of the HTTP request body, per RFC 3230. + const string HEADER_DIGEST = "Digest"; + + //The 'Authorization' header is automatically generated by the client. It includes + //the list of signed headers and a base64-encoded signature. + const string HEADER_AUTHORIZATION = "Authorization"; + + //Hash table to store singed headers + var HttpSignedRequestHeader = new Dictionary(); + + var httpSignatureHeader = new Dictionary(); + + if (HttpSigningHeader.Count == 0) + HttpSigningHeader.Add("(created)"); + + var dateTime = DateTime.Now; + string digest = String.Empty; + + if (HashAlgorithm == HashAlgorithmName.SHA256) + { + var bodyDigest = GetStringHash(HashAlgorithm, requestBody); + digest = string.Format("SHA-256={0}", Convert.ToBase64String(bodyDigest)); + } + else if (HashAlgorithm == HashAlgorithmName.SHA512) + { + var bodyDigest = GetStringHash(HashAlgorithm, requestBody); + digest = string.Format("SHA-512={0}", Convert.ToBase64String(bodyDigest)); + } + else + throw new Exception(string.Format("{0} not supported", HashAlgorithm)); + + foreach (var header in HttpSigningHeader) + if (header.Equals(HEADER_REQUEST_TARGET)) + httpSignatureHeader.Add(header.ToLower(), request.RequestUri.ToString()); + else if (header.Equals(HEADER_EXPIRES)) + { + var expireDateTime = dateTime.AddSeconds(SignatureValidityPeriod); + httpSignatureHeader.Add(header.ToLower(), GetUnixTime(expireDateTime).ToString()); + } + else if (header.Equals(HEADER_DATE)) + { + var utcDateTime = dateTime.ToString("r").ToString(); + httpSignatureHeader.Add(header.ToLower(), utcDateTime); + HttpSignedRequestHeader.Add(HEADER_DATE, utcDateTime); + } + else if (header.Equals(HEADER_HOST)) + { + httpSignatureHeader.Add(header.ToLower(), request.RequestUri.ToString()); + HttpSignedRequestHeader.Add(HEADER_HOST, request.RequestUri.ToString()); + } + else if (header.Equals(HEADER_CREATED)) + httpSignatureHeader.Add(header.ToLower(), GetUnixTime(dateTime).ToString()); + else if (header.Equals(HEADER_DIGEST)) + { + HttpSignedRequestHeader.Add(HEADER_DIGEST, digest); + httpSignatureHeader.Add(header.ToLower(), digest); + } + else + { + bool isHeaderFound = false; + foreach (var item in request.Headers) + { + if (string.Equals(item.Key, header, StringComparison.OrdinalIgnoreCase)) + { + httpSignatureHeader.Add(header.ToLower(), item.Value.ToString()); + isHeaderFound = true; + break; + } + } + + if (!isHeaderFound) + throw new Exception(string.Format("Cannot sign HTTP request.Request does not contain the {0} header.",header)); + } + + var headersKeysString = String.Join(" ", httpSignatureHeader.Keys); + var headerValuesList = new List(); + + foreach (var keyVal in httpSignatureHeader) + headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); + + //Concatenate headers value separated by new line + var headerValuesString = string.Join("\n", headerValuesList); + var signatureStringHash = GetStringHash(HashAlgorithm, headerValuesString); + string? headerSignatureStr = null; + var keyType = GetKeyType(KeyFilePath); + + if (keyType == PrivateKeyType.RSA) + headerSignatureStr = GetRSASignature(signatureStringHash); + + else if (keyType == PrivateKeyType.ECDSA) + headerSignatureStr = GetECDSASignature(signatureStringHash); + + var cryptographicScheme = "hs2019"; + var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", + KeyId, cryptographicScheme); + + if (httpSignatureHeader.ContainsKey(HEADER_CREATED)) + authorizationHeaderValue += string.Format(",created={0}", httpSignatureHeader[HEADER_CREATED]); + + if (httpSignatureHeader.ContainsKey(HEADER_EXPIRES)) + authorizationHeaderValue += string.Format(",expires={0}", httpSignatureHeader[HEADER_EXPIRES]); + + authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", headersKeysString, headerSignatureStr); + + HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); + + return HttpSignedRequestHeader; + } + + private byte[] GetStringHash(HashAlgorithmName hashAlgorithmName, string stringToBeHashed) + { + HashAlgorithm? hashAlgorithm = null; + + if (hashAlgorithmName == HashAlgorithmName.SHA1) + hashAlgorithm = SHA1.Create(); + + if (hashAlgorithmName == HashAlgorithmName.SHA256) + hashAlgorithm = SHA256.Create(); + + if (hashAlgorithmName == HashAlgorithmName.SHA512) + hashAlgorithm = SHA512.Create(); + + if (hashAlgorithmName == HashAlgorithmName.MD5) + hashAlgorithm = MD5.Create(); + + if (hashAlgorithm == null) + throw new NullReferenceException($"{ nameof(hashAlgorithm) } was null."); + + byte[] bytes = Encoding.UTF8.GetBytes(stringToBeHashed); + byte[] stringHash = hashAlgorithm.ComputeHash(bytes); + return stringHash; + } + + private int GetUnixTime(DateTime date2) + { + DateTime date1 = new DateTime(1970, 01, 01); + TimeSpan timeSpan = date2 - date1; + return (int)timeSpan.TotalSeconds; + } + + private string GetRSASignature(byte[] stringToSign) + { + if (KeyPassPhrase == null) + throw new NullReferenceException($"{ nameof(KeyPassPhrase) } was null."); + + RSA? rsa = GetRSAProviderFromPemFile(KeyFilePath, KeyPassPhrase); + + if (rsa == null) + return string.Empty; + else if (SigningAlgorithm == "RSASSA-PSS") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pss); + return Convert.ToBase64String(signedbytes); + } + else if (SigningAlgorithm == "PKCS1-v15") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); + return Convert.ToBase64String(signedbytes); + } + + return string.Empty; + } + + /// + /// Gets the ECDSA signature + /// + /// + /// + private string GetECDSASignature(byte[] dataToSign) + { + if (!File.Exists(KeyFilePath)) + throw new Exception("key file path does not exist."); + + var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + var keyStr = File.ReadAllText(KeyFilePath); + var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); + var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); + var ecdsa = ECDsa.Create(); + + var byteCount = 0; + if (KeyPassPhrase != null) + { + IntPtr unmanagedString = IntPtr.Zero; + try + { + // convert secure string to byte array + unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(KeyPassPhrase); + + string ptrToStringUni = Marshal.PtrToStringUni(unmanagedString) ?? throw new NullReferenceException(); + + ecdsa.ImportEncryptedPkcs8PrivateKey(Encoding.UTF8.GetBytes(ptrToStringUni), keyBytes, out byteCount); + } + finally + { + if (unmanagedString != IntPtr.Zero) + Marshal.ZeroFreeBSTR(unmanagedString); + } + } + else + ecdsa.ImportPkcs8PrivateKey(keyBytes, out byteCount); + + var signedBytes = ecdsa.SignHash(dataToSign); + var derBytes = ConvertToECDSAANS1Format(signedBytes); + var signedString = System.Convert.ToBase64String(derBytes); + + return signedString; + } + + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + { + var derBytes = new List(); + byte derLength = 68; //default length for ECDSA code signing bit 0x44 + byte rbytesLength = 32; //R length 0x20 + byte sbytesLength = 32; //S length 0x20 + var rBytes = new List(); + var sBytes = new List(); + for (int i = 0; i < 32; i++) + rBytes.Add(signedBytes[i]); + + for (int i = 32; i < 64; i++) + sBytes.Add(signedBytes[i]); + + if (rBytes[0] > 0x7F) + { + derLength++; + rbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(rBytes); + rBytes.Clear(); + rBytes.Add(0x00); + rBytes.AddRange(tempBytes); + } + + if (sBytes[0] > 0x7F) + { + derLength++; + sbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(sBytes); + sBytes.Clear(); + sBytes.Add(0x00); + sBytes.AddRange(tempBytes); + + } + + derBytes.Add(48); //start of the sequence 0x30 + derBytes.Add(derLength); //total length r length, type and r bytes + + derBytes.Add(2); //tag for integer + derBytes.Add(rbytesLength); //length of r + derBytes.AddRange(rBytes); + + derBytes.Add(2); //tag for integer + derBytes.Add(sbytesLength); //length of s + derBytes.AddRange(sBytes); + return derBytes.ToArray(); + } + + private RSACryptoServiceProvider? GetRSAProviderFromPemFile(String pemfile, SecureString? keyPassPhrase = null) + { + const String pempubheader = "-----BEGIN PUBLIC KEY-----"; + const String pempubfooter = "-----END PUBLIC KEY-----"; + bool isPrivateKeyFile = true; + byte[]? pemkey = null; + + if (!File.Exists(pemfile)) + throw new Exception("private key file does not exist."); + + string pemstr = File.ReadAllText(pemfile).Trim(); + + if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) + isPrivateKeyFile = false; + + if (isPrivateKeyFile) + { + pemkey = ConvertPrivateKeyToBytes(pemstr, keyPassPhrase); + + if (pemkey == null) + return null; + + return DecodeRSAPrivateKey(pemkey); + } + return null; + } + + private byte[]? ConvertPrivateKeyToBytes(String instr, SecureString? keyPassPhrase = null) + { + const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; + const String pemprivfooter = "-----END RSA PRIVATE KEY-----"; + String pemstr = instr.Trim(); + byte[] binkey; + + if (!pemstr.StartsWith(pemprivheader) || !pemstr.EndsWith(pemprivfooter)) + return null; + + StringBuilder sb = new StringBuilder(pemstr); + sb.Replace(pemprivheader, ""); + sb.Replace(pemprivfooter, ""); + String pvkstr = sb.ToString().Trim(); + + try + { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key + binkey = Convert.FromBase64String(pvkstr); + return binkey; + } + catch (System.FormatException) + { + StringReader str = new StringReader(pvkstr); + + //-------- read PEM encryption info. lines and extract salt ----- + if (!str.ReadLine()!.StartsWith("Proc-Type: 4,ENCRYPTED")) // TODO: what do we do here if ReadLine is null? + return null; + + String saltline = str.ReadLine()!; // TODO: what do we do here if ReadLine is null? + if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) + return null; + + String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + byte[] salt = new byte[saltstr.Length / 2]; + for (int i = 0; i < salt.Length; i++) + salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); + + if (!(str.ReadLine() == "")) + return null; + + //------ remaining b64 data is encrypted RSA key ---- + String encryptedstr = str.ReadToEnd(); + + try + { //should have b64 encrypted RSA key now + binkey = Convert.FromBase64String(encryptedstr); + } + catch (System.FormatException) + { //data is not in base64 format + return null; + } + + // TODO: what do we do here if keyPassPhrase is null? + byte[] deskey = GetEncryptedKey(salt, keyPassPhrase!, 1, 2); // count=1 (for OpenSSL implementation); 2 iterations to get at least 24 bytes + if (deskey == null) + return null; + + //------ Decrypt the encrypted 3des-encrypted RSA private key ------ + byte[]? rsakey = DecryptKey(binkey, deskey, salt); //OpenSSL uses salt value in PEM header also as 3DES IV + + return rsakey; + } + } + + private RSACryptoServiceProvider? DecodeRSAPrivateKey(byte[] privkey) + { + byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + + // --------- Set up stream to decode the asn.1 encoded RSA private key ------ + MemoryStream mem = new MemoryStream(privkey); + BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + int elems = 0; + try + { + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) //version number + return null; + + bt = binr.ReadByte(); + if (bt != 0x00) + return null; + + //------ all private key components are Integer sequences ---- + elems = GetIntegerSize(binr); + MODULUS = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + E = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + D = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + P = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + Q = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + IQ = binr.ReadBytes(elems); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); + RSAParameters RSAparams = new RSAParameters(); + RSAparams.Modulus = MODULUS; + RSAparams.Exponent = E; + RSAparams.D = D; + RSAparams.P = P; + RSAparams.Q = Q; + RSAparams.DP = DP; + RSAparams.DQ = DQ; + RSAparams.InverseQ = IQ; + RSA.ImportParameters(RSAparams); + return RSA; + } + catch (Exception) + { + return null; + } + finally + { + binr.Close(); + } + } + + private int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + byte lowbyte = 0x00; + byte highbyte = 0x00; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) //expect integer + return 0; + + bt = binr.ReadByte(); + + if (bt == 0x81) + count = binr.ReadByte(); // data size in next byte + else if (bt == 0x82) + { + highbyte = binr.ReadByte(); // data size in next 2 bytes + lowbyte = binr.ReadByte(); + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; + count = BitConverter.ToInt32(modint, 0); + } + else + count = bt; // we already have the data size + + while (binr.ReadByte() == 0x00) + //remove high order zeros in data + count -= 1; + + binr.BaseStream.Seek(-1, SeekOrigin.Current); + + //last ReadByte wasn't a removed zero, so back up a byte + return count; + } + + private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) + { + IntPtr unmanagedPswd = IntPtr.Zero; + int HASHLENGTH = 16; //MD5 bytes + byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results + + byte[] psbytes = new byte[secpswd.Length]; + unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd); + Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length); + Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd); + + // --- concatenate salt and pswd bytes into fixed data array --- + byte[] data00 = new byte[psbytes.Length + salt.Length]; + Array.Copy(psbytes, data00, psbytes.Length); //copy the pswd bytes + Array.Copy(salt, 0, data00, psbytes.Length, salt.Length); //concatenate the salt bytes + + // ---- do multi-hashing and concatenate results D1, D2 ... into keymaterial bytes ---- + MD5 md5 = MD5.Create(); + byte[]? result = null; + byte[] hashtarget = new byte[HASHLENGTH + data00.Length]; //fixed length initial hashtarget + + for (int j = 0; j < miter; j++) + { + // ---- Now hash consecutively for count times ------ + if (j == 0) + result = data00; //initialize + else + { + Array.Copy(result!, hashtarget, result!.Length); // TODO: what do we do if result is null here? + Array.Copy(data00, 0, hashtarget, result.Length, data00.Length); + result = hashtarget; + } + + for (int i = 0; i < count; i++) + result = md5.ComputeHash(result); + + Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial + } + byte[] deskey = new byte[24]; + Array.Copy(keymaterial, deskey, deskey.Length); + + Array.Clear(psbytes, 0, psbytes.Length); + Array.Clear(data00, 0, data00.Length); + Array.Clear(result!, 0, result!.Length); // TODO: what do we do if result is null here? + Array.Clear(hashtarget, 0, hashtarget.Length); + Array.Clear(keymaterial, 0, keymaterial.Length); + return deskey; + } + + private byte[]? DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV) + { + MemoryStream memst = new MemoryStream(); + TripleDES alg = TripleDES.Create(); + alg.Key = desKey; + alg.IV = IV; + try + { + CryptoStream cs = new CryptoStream(memst, alg.CreateDecryptor(), CryptoStreamMode.Write); + cs.Write(cipherData, 0, cipherData.Length); + cs.Close(); + } + catch (Exception) + { + return null; + } + byte[] decryptedData = memst.ToArray(); + return decryptedData; + } + + /// + /// Detect the key type from the pem file. + /// + /// key file path in pem format + /// + private PrivateKeyType GetKeyType(string keyFilePath) + { + if (!File.Exists(keyFilePath)) + throw new Exception("Key file path does not exist."); + + var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + var ecPrivateKeyFooter = "END EC PRIVATE KEY"; + var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + var rsaPrivateFooter = "END RSA PRIVATE KEY"; + //var pkcs8Header = "BEGIN PRIVATE KEY"; + //var pkcs8Footer = "END PRIVATE KEY"; + var keyType = PrivateKeyType.None; + var key = File.ReadAllLines(keyFilePath); + + if (key[0].ToString().Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) + keyType = PrivateKeyType.RSA; + else if (key[0].ToString().Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + keyType = PrivateKeyType.ECDSA; + + else if (key[0].ToString().Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + { + /* this type of key can hold many type different types of private key, but here due lack of pem header + Considering this as EC key + */ + //TODO :- update the key based on oid + keyType = PrivateKeyType.ECDSA; + } + else + throw new Exception("Either the key is invalid or key is not supported"); + + return keyType; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HttpSigningToken.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HttpSigningToken.cs new file mode 100644 index 00000000000..2f2dd4c57ae --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HttpSigningToken.cs @@ -0,0 +1,43 @@ +// + +#nullable enable + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace UseSourceGeneration.Client +{ + /// + /// A token constructed from an HttpSigningConfiguration + /// + public class HttpSignatureToken : TokenBase + { + private HttpSigningConfiguration _configuration; + + /// + /// Constructs an HttpSignatureToken object. + /// + /// + /// + public HttpSignatureToken(HttpSigningConfiguration configuration, TimeSpan? timeout = null) : base(timeout) + { + _configuration = configuration; + } + + /// + /// Places the token in the header. + /// + /// + /// + /// + public void UseInHeader(System.Net.Http.HttpRequestMessage request, string requestBody, CancellationToken cancellationToken = default) + { + var signedHeaders = _configuration.GetHttpSignedHeader(request, requestBody, cancellationToken); + + foreach (var signedHeader in signedHeaders) + request.Headers.Add(signedHeader.Key, signedHeader.Value); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/JsonSerializerOptionsProvider.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 00000000000..05c6ef20a72 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace UseSourceGeneration.Client +{ + /// + /// Provides the JsonSerializerOptions + /// + public class JsonSerializerOptionsProvider + { + /// + /// the JsonSerializerOptions + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/OAuthToken.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/OAuthToken.cs new file mode 100644 index 00000000000..15621227d96 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/OAuthToken.cs @@ -0,0 +1,39 @@ +// + +#nullable enable + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace UseSourceGeneration.Client +{ + /// + /// A token constructed with OAuth. + /// + public class OAuthToken : TokenBase + { + private string _raw; + + /// + /// Consturcts an OAuthToken object. + /// + /// + /// + public OAuthToken(string value, TimeSpan? timeout = null) : base(timeout) + { + _raw = value; + } + + /// + /// Places the token in the header. + /// + /// + /// + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + { + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _raw); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/Option.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/Option.cs new file mode 100644 index 00000000000..93f54baec74 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/Option.cs @@ -0,0 +1,41 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + + +namespace UseSourceGeneration.Client +{ + /// + /// A wrapper for operation parameters which are not required + /// + public struct Option + { + /// + /// The value to send to the server + /// + public TType Value { get; } + + /// + /// When true the value will be sent to the server + /// + internal bool IsSet { get; } + + /// + /// A wrapper for operation parameters which are not required + /// + /// + public Option(TType value) + { + IsSet = true; + Value = value; + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/RateLimitProvider`1.cs new file mode 100644 index 00000000000..0ad3cc6e6eb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/RateLimitProvider`1.cs @@ -0,0 +1,48 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Threading.Channels; + +namespace UseSourceGeneration.Client +{ + /// + /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. + /// + /// + public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase + { + internal Channel AvailableTokens { get; } + + /// + /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. + /// + /// + public RateLimitProvider(TokenContainer container) : base(container.Tokens) + { + foreach(TTokenBase token in _tokens) + token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); + + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite + }; + + AvailableTokens = Channel.CreateBounded(options); + + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); + } + internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default) + => await AvailableTokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenBase.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenBase.cs new file mode 100644 index 00000000000..3d54794f39f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenBase.cs @@ -0,0 +1,71 @@ +// + +#nullable enable + +using System; + +namespace UseSourceGeneration.Client +{ + /// + /// The base for all tokens. + /// + public abstract class TokenBase + { + private DateTime _nextAvailable = DateTime.UtcNow; + private object _nextAvailableLock = new object(); + private readonly System.Timers.Timer _timer = new System.Timers.Timer(); + + + internal TimeSpan? Timeout { get; set; } + internal delegate void TokenBecameAvailableEventHandler(object sender); + internal event TokenBecameAvailableEventHandler? TokenBecameAvailable; + + + /// + /// Initialize a TokenBase object. + /// + /// + internal TokenBase(TimeSpan? timeout = null) + { + Timeout = timeout; + + if (Timeout != null) + StartTimer(Timeout.Value); + } + + + /// + /// Starts the token's timer + /// + /// + internal void StartTimer(TimeSpan timeout) + { + Timeout = timeout; + _timer.Interval = Timeout.Value.TotalMilliseconds; + _timer.Elapsed += OnTimer; + _timer.AutoReset = true; + _timer.Start(); + } + + /// + /// Returns true while the token is rate limited. + /// + public bool IsRateLimited => _nextAvailable > DateTime.UtcNow; + + /// + /// Triggered when the server returns status code TooManyRequests + /// Once triggered the local timeout will be extended an arbitrary length of time. + /// + public void BeginRateLimit() + { + lock(_nextAvailableLock) + _nextAvailable = DateTime.UtcNow.AddSeconds(5); + } + + private void OnTimer(object? sender, System.Timers.ElapsedEventArgs e) + { + if (TokenBecameAvailable != null && !IsRateLimited) + TokenBecameAvailable.Invoke(this); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenContainer`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenContainer`1.cs new file mode 100644 index 00000000000..20dcc6dbc66 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenContainer`1.cs @@ -0,0 +1,37 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace UseSourceGeneration.Client +{ + /// + /// A container for a collection of tokens. + /// + /// + public sealed class TokenContainer where TTokenBase : TokenBase + { + /// + /// The collection of tokens + /// + public List Tokens { get; } = new List(); + + /// + /// Instantiates a TokenContainer + /// + public TokenContainer() + { + } + + /// + /// Instantiates a TokenContainer + /// + /// + public TokenContainer(System.Collections.Generic.IEnumerable tokens) + { + Tokens = tokens.ToList(); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenProvider`1.cs new file mode 100644 index 00000000000..1044bc055fa --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenProvider`1.cs @@ -0,0 +1,44 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using System.Collections.Generic; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration +{ + /// + /// A class which will provide tokens. + /// + public abstract class TokenProvider where TTokenBase : TokenBase + { + /// + /// The array of tokens. + /// + protected TTokenBase[] _tokens; + + internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default); + + /// + /// Instantiates a TokenProvider. + /// + /// + public TokenProvider(IEnumerable tokens) + { + _tokens = tokens.ToArray(); + + if (_tokens.Length == 0) + throw new ArgumentException("You did not provide any tokens."); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Extensions/IHostBuilderExtensions.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Extensions/IHostBuilderExtensions.cs new file mode 100644 index 00000000000..9a1a3d0a935 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Extensions/IHostBuilderExtensions.cs @@ -0,0 +1,43 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Extensions +{ + /// + /// Extension methods for IHostBuilder + /// + public static class IHostBuilderExtensions + { + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action options) + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Extensions/IHttpClientBuilderExtensions.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Extensions/IHttpClientBuilderExtensions.cs new file mode 100644 index 00000000000..22e17999e66 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Extensions/IHttpClientBuilderExtensions.cs @@ -0,0 +1,79 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly; + +namespace UseSourceGeneration.Extensions +{ + /// + /// Extension methods for IHttpClientBuilder + /// + public static class IHttpClientBuilderExtensions + { + /// + /// Adds a Polly retry policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries) + { + client.AddPolicyHandler(RetryPolicy(retries)); + + return client; + } + + /// + /// Adds a Polly timeout policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout) + { + client.AddPolicyHandler(TimeoutPolicy(timeout)); + + return client; + } + + /// + /// Adds a Polly circuit breaker to your clients. + /// + /// + /// + /// + /// + public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder client, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + { + client.AddTransientHttpErrorPolicy(builder => CircuitBreakerPolicy(builder, handledEventsAllowedBeforeBreaking, durationOfBreak)); + + return client; + } + + private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int retries) + => HttpPolicyExtensions + .HandleTransientHttpError() + .Or() + .RetryAsync(retries); + + private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout) + => Policy.TimeoutAsync(timeout); + + private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy( + PolicyBuilder builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Extensions/IServiceCollectionExtensions.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 00000000000..b232b7be8a7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,63 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Extensions +{ + /// + /// Extension methods for IServiceCollection + /// + public static class IServiceCollectionExtensions + { + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action options) + { + HostConfiguration config = new(services); + options(config); + AddApi(services, config); + } + + internal static void AddApi(IServiceCollection services, HostConfiguration host) + { + if (!host.HttpClientsAdded) + host.AddApiHttpClients(); + + services.AddSingleton(); + + // ensure that a token provider was provided for this token type + // if not, default to RateLimitProvider + var containerServices = services.Where(s => s.ServiceType.IsGenericType && + s.ServiceType.GetGenericTypeDefinition().IsAssignableFrom(typeof(TokenContainer<>))).ToArray(); + + foreach(var containerService in containerServices) + { + var tokenType = containerService.ServiceType.GenericTypeArguments[0]; + + var provider = services.FirstOrDefault(s => s.ServiceType.IsAssignableFrom(typeof(TokenProvider<>).MakeGenericType(tokenType))); + + if (provider == null) + { + services.AddSingleton(typeof(RateLimitProvider<>).MakeGenericType(tokenType)); + services.AddSingleton(typeof(TokenProvider<>).MakeGenericType(tokenType), + s => s.GetRequiredService(typeof(RateLimitProvider<>).MakeGenericType(tokenType))); + } + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Activity.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Activity.cs new file mode 100644 index 00000000000..5753aac9635 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Activity.cs @@ -0,0 +1,200 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// test map of maps + /// + public partial class Activity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// activityOutputs + [JsonConstructor] + public Activity(Dictionary> activityOutputs) + { + ActivityOutputs = activityOutputs; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ActivityOutputs + /// + [JsonPropertyName("activity_outputs")] + public Dictionary> ActivityOutputs { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Activity {\n"); + sb.Append(" ActivityOutputs: ").Append(ActivityOutputs).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ActivityJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Dictionary>? activityOutputs = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "activity_outputs": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + activityOutputs = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (activityOutputs == null) + throw new ArgumentNullException(nameof(activityOutputs), "Property is required for class Activity."); + + return new Activity(activityOutputs); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Activity activity, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, activity, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Activity activity, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("activity_outputs"); + JsonSerializer.Serialize(writer, activity.ActivityOutputs, jsonSerializerOptions); + } + } + + /// + /// The ActivitySerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Activity))] + public partial class ActivitySerializationContext : JsonSerializerContext + { + /// + /// The ActivitySerializationContext + /// + /// + public ActivitySerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ActivityDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Activity))] + public partial class ActivityDeserializationContext : JsonSerializerContext + { + /// + /// ActivityDeserializationContext + /// + /// + public ActivityDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ActivityOutputElementRepresentation.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ActivityOutputElementRepresentation.cs new file mode 100644 index 00000000000..f663e566b3f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ActivityOutputElementRepresentation.cs @@ -0,0 +1,217 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ActivityOutputElementRepresentation + /// + public partial class ActivityOutputElementRepresentation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// prop1 + /// prop2 + [JsonConstructor] + public ActivityOutputElementRepresentation(string prop1, Object prop2) + { + Prop1 = prop1; + Prop2 = prop2; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Prop1 + /// + [JsonPropertyName("prop1")] + public string Prop1 { get; set; } + + /// + /// Gets or Sets Prop2 + /// + [JsonPropertyName("prop2")] + public Object Prop2 { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ActivityOutputElementRepresentation {\n"); + sb.Append(" Prop1: ").Append(Prop1).Append("\n"); + sb.Append(" Prop2: ").Append(Prop2).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ActivityOutputElementRepresentationJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? prop1 = default; + Object? prop2 = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "prop1": + prop1 = utf8JsonReader.GetString(); + break; + case "prop2": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + prop2 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (prop1 == null) + throw new ArgumentNullException(nameof(prop1), "Property is required for class ActivityOutputElementRepresentation."); + + if (prop2 == null) + throw new ArgumentNullException(nameof(prop2), "Property is required for class ActivityOutputElementRepresentation."); + + return new ActivityOutputElementRepresentation(prop1, prop2); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ActivityOutputElementRepresentation activityOutputElementRepresentation, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, activityOutputElementRepresentation, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ActivityOutputElementRepresentation activityOutputElementRepresentation, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); + writer.WritePropertyName("prop2"); + JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, jsonSerializerOptions); + } + } + + /// + /// The ActivityOutputElementRepresentationSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ActivityOutputElementRepresentation))] + public partial class ActivityOutputElementRepresentationSerializationContext : JsonSerializerContext + { + /// + /// The ActivityOutputElementRepresentationSerializationContext + /// + /// + public ActivityOutputElementRepresentationSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ActivityOutputElementRepresentationDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ActivityOutputElementRepresentation))] + public partial class ActivityOutputElementRepresentationDeserializationContext : JsonSerializerContext + { + /// + /// ActivityOutputElementRepresentationDeserializationContext + /// + /// + public ActivityOutputElementRepresentationDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AdditionalPropertiesClass.cs new file mode 100644 index 00000000000..8248ed1274d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AdditionalPropertiesClass.cs @@ -0,0 +1,331 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// AdditionalPropertiesClass + /// + public partial class AdditionalPropertiesClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// an object with no declared properties and no undeclared properties, hence it's an empty map. + /// mapOfMapProperty + /// mapProperty + /// mapWithUndeclaredPropertiesAnytype1 + /// mapWithUndeclaredPropertiesAnytype2 + /// mapWithUndeclaredPropertiesAnytype3 + /// mapWithUndeclaredPropertiesString + /// anytype1 + [JsonConstructor] + public AdditionalPropertiesClass(Object emptyMap, Dictionary> mapOfMapProperty, Dictionary mapProperty, Object mapWithUndeclaredPropertiesAnytype1, Object mapWithUndeclaredPropertiesAnytype2, Dictionary mapWithUndeclaredPropertiesAnytype3, Dictionary mapWithUndeclaredPropertiesString, Object? anytype1 = default) + { + EmptyMap = emptyMap; + MapOfMapProperty = mapOfMapProperty; + MapProperty = mapProperty; + MapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; + MapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; + MapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; + MapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; + Anytype1 = anytype1; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// an object with no declared properties and no undeclared properties, hence it's an empty map. + /// + /// an object with no declared properties and no undeclared properties, hence it's an empty map. + [JsonPropertyName("empty_map")] + public Object EmptyMap { get; set; } + + /// + /// Gets or Sets MapOfMapProperty + /// + [JsonPropertyName("map_of_map_property")] + public Dictionary> MapOfMapProperty { get; set; } + + /// + /// Gets or Sets MapProperty + /// + [JsonPropertyName("map_property")] + public Dictionary MapProperty { get; set; } + + /// + /// Gets or Sets MapWithUndeclaredPropertiesAnytype1 + /// + [JsonPropertyName("map_with_undeclared_properties_anytype_1")] + public Object MapWithUndeclaredPropertiesAnytype1 { get; set; } + + /// + /// Gets or Sets MapWithUndeclaredPropertiesAnytype2 + /// + [JsonPropertyName("map_with_undeclared_properties_anytype_2")] + public Object MapWithUndeclaredPropertiesAnytype2 { get; set; } + + /// + /// Gets or Sets MapWithUndeclaredPropertiesAnytype3 + /// + [JsonPropertyName("map_with_undeclared_properties_anytype_3")] + public Dictionary MapWithUndeclaredPropertiesAnytype3 { get; set; } + + /// + /// Gets or Sets MapWithUndeclaredPropertiesString + /// + [JsonPropertyName("map_with_undeclared_properties_string")] + public Dictionary MapWithUndeclaredPropertiesString { get; set; } + + /// + /// Gets or Sets Anytype1 + /// + [JsonPropertyName("anytype_1")] + public Object? Anytype1 { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalPropertiesClass {\n"); + sb.Append(" EmptyMap: ").Append(EmptyMap).Append("\n"); + sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); + sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesAnytype1: ").Append(MapWithUndeclaredPropertiesAnytype1).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesAnytype2: ").Append(MapWithUndeclaredPropertiesAnytype2).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesAnytype3: ").Append(MapWithUndeclaredPropertiesAnytype3).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesString: ").Append(MapWithUndeclaredPropertiesString).Append("\n"); + sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalPropertiesClassJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Object? emptyMap = default; + Dictionary>? mapOfMapProperty = default; + Dictionary? mapProperty = default; + Object? mapWithUndeclaredPropertiesAnytype1 = default; + Object? mapWithUndeclaredPropertiesAnytype2 = default; + Dictionary? mapWithUndeclaredPropertiesAnytype3 = default; + Dictionary? mapWithUndeclaredPropertiesString = default; + Object? anytype1 = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "empty_map": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + emptyMap = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "map_of_map_property": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + mapOfMapProperty = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "map_property": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + mapProperty = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "map_with_undeclared_properties_anytype_1": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + mapWithUndeclaredPropertiesAnytype1 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "map_with_undeclared_properties_anytype_2": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + mapWithUndeclaredPropertiesAnytype2 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "map_with_undeclared_properties_anytype_3": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + mapWithUndeclaredPropertiesAnytype3 = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "map_with_undeclared_properties_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + mapWithUndeclaredPropertiesString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "anytype_1": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anytype1 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (emptyMap == null) + throw new ArgumentNullException(nameof(emptyMap), "Property is required for class AdditionalPropertiesClass."); + + if (mapOfMapProperty == null) + throw new ArgumentNullException(nameof(mapOfMapProperty), "Property is required for class AdditionalPropertiesClass."); + + if (mapProperty == null) + throw new ArgumentNullException(nameof(mapProperty), "Property is required for class AdditionalPropertiesClass."); + + if (mapWithUndeclaredPropertiesAnytype1 == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype1), "Property is required for class AdditionalPropertiesClass."); + + if (mapWithUndeclaredPropertiesAnytype2 == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype2), "Property is required for class AdditionalPropertiesClass."); + + if (mapWithUndeclaredPropertiesAnytype3 == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype3), "Property is required for class AdditionalPropertiesClass."); + + if (mapWithUndeclaredPropertiesString == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesString), "Property is required for class AdditionalPropertiesClass."); + + return new AdditionalPropertiesClass(emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString, anytype1); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalPropertiesClass additionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, additionalPropertiesClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, AdditionalPropertiesClass additionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("empty_map"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, jsonSerializerOptions); + writer.WritePropertyName("map_of_map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, jsonSerializerOptions); + writer.WritePropertyName("map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, jsonSerializerOptions); + writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, jsonSerializerOptions); + writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, jsonSerializerOptions); + writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, jsonSerializerOptions); + writer.WritePropertyName("map_with_undeclared_properties_string"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, jsonSerializerOptions); + writer.WritePropertyName("anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, jsonSerializerOptions); + } + } + + /// + /// The AdditionalPropertiesClassSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(AdditionalPropertiesClass))] + public partial class AdditionalPropertiesClassSerializationContext : JsonSerializerContext + { + /// + /// The AdditionalPropertiesClassSerializationContext + /// + /// + public AdditionalPropertiesClassSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// AdditionalPropertiesClassDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(AdditionalPropertiesClass))] + public partial class AdditionalPropertiesClassDeserializationContext : JsonSerializerContext + { + /// + /// AdditionalPropertiesClassDeserializationContext + /// + /// + public AdditionalPropertiesClassDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Animal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Animal.cs new file mode 100644 index 00000000000..ad4d3be5866 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Animal.cs @@ -0,0 +1,225 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Animal + /// + public partial class Animal : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// className + /// color (default to "red") + [JsonConstructor] + public Animal(string className, string color = @"red") + { + ClassName = className; + Color = color; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ClassName + /// + [JsonPropertyName("className")] + public string ClassName { get; set; } + + /// + /// Gets or Sets Color + /// + [JsonPropertyName("color")] + public string Color { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Animal {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AnimalJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? className = default; + string? color = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "className": + className = utf8JsonReader.GetString(); + break; + case "color": + color = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (className == null) + throw new ArgumentNullException(nameof(className), "Property is required for class Animal."); + + if (color == null) + throw new ArgumentNullException(nameof(color), "Property is required for class Animal."); + + return new Animal(className, color); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Animal animal, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, animal, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Animal animal, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("className", animal.ClassName); + writer.WriteString("color", animal.Color); + } + } + + /// + /// The AnimalSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Animal))] + public partial class AnimalSerializationContext : JsonSerializerContext + { + /// + /// The AnimalSerializationContext + /// + /// + public AnimalSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// AnimalDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Animal))] + public partial class AnimalDeserializationContext : JsonSerializerContext + { + /// + /// AnimalDeserializationContext + /// + /// + public AnimalDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ApiResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ApiResponse.cs new file mode 100644 index 00000000000..3593d36382e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ApiResponse.cs @@ -0,0 +1,233 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ApiResponse + /// + public partial class ApiResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// code + /// message + /// type + [JsonConstructor] + public ApiResponse(int code, string message, string type) + { + Code = code; + Message = message; + Type = type; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Code + /// + [JsonPropertyName("code")] + public int Code { get; set; } + + /// + /// Gets or Sets Message + /// + [JsonPropertyName("message")] + public string Message { get; set; } + + /// + /// Gets or Sets Type + /// + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApiResponse {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApiResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + int? code = default; + string? message = default; + string? type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "code": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + code = utf8JsonReader.GetInt32(); + break; + case "message": + message = utf8JsonReader.GetString(); + break; + case "type": + type = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (code == null) + throw new ArgumentNullException(nameof(code), "Property is required for class ApiResponse."); + + if (message == null) + throw new ArgumentNullException(nameof(message), "Property is required for class ApiResponse."); + + if (type == null) + throw new ArgumentNullException(nameof(type), "Property is required for class ApiResponse."); + + return new ApiResponse(code.Value, message, type); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApiResponse apiResponse, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, apiResponse, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ApiResponse apiResponse, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("code", apiResponse.Code); + writer.WriteString("message", apiResponse.Message); + writer.WriteString("type", apiResponse.Type); + } + } + + /// + /// The ApiResponseSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ApiResponse))] + public partial class ApiResponseSerializationContext : JsonSerializerContext + { + /// + /// The ApiResponseSerializationContext + /// + /// + public ApiResponseSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ApiResponseDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ApiResponse))] + public partial class ApiResponseDeserializationContext : JsonSerializerContext + { + /// + /// ApiResponseDeserializationContext + /// + /// + public ApiResponseDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Apple.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Apple.cs new file mode 100644 index 00000000000..10f265c70b5 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Apple.cs @@ -0,0 +1,259 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Apple + /// + public partial class Apple : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// colorCode + /// cultivar + /// origin + [JsonConstructor] + public Apple(string colorCode, string cultivar, string origin) + { + ColorCode = colorCode; + Cultivar = cultivar; + Origin = origin; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ColorCode + /// + [JsonPropertyName("color_code")] + public string ColorCode { get; set; } + + /// + /// Gets or Sets Cultivar + /// + [JsonPropertyName("cultivar")] + public string Cultivar { get; set; } + + /// + /// Gets or Sets Origin + /// + [JsonPropertyName("origin")] + public string Origin { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Apple {\n"); + sb.Append(" ColorCode: ").Append(ColorCode).Append("\n"); + sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); + sb.Append(" Origin: ").Append(Origin).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + if (this.ColorCode != null) { + // ColorCode (string) pattern + Regex regexColorCode = new Regex(@"^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$", RegexOptions.CultureInvariant); + if (!regexColorCode.Match(this.ColorCode).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ColorCode, must match a pattern of " + regexColorCode, new [] { "ColorCode" }); + } + } + + if (this.Cultivar != null) { + // Cultivar (string) pattern + Regex regexCultivar = new Regex(@"^[a-zA-Z\s]*$", RegexOptions.CultureInvariant); + if (!regexCultivar.Match(this.Cultivar).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cultivar, must match a pattern of " + regexCultivar, new [] { "Cultivar" }); + } + } + + if (this.Origin != null) { + // Origin (string) pattern + Regex regexOrigin = new Regex(@"^[A-Z\s]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (!regexOrigin.Match(this.Origin).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Origin, must match a pattern of " + regexOrigin, new [] { "Origin" }); + } + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AppleJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? colorCode = default; + string? cultivar = default; + string? origin = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "color_code": + colorCode = utf8JsonReader.GetString(); + break; + case "cultivar": + cultivar = utf8JsonReader.GetString(); + break; + case "origin": + origin = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (colorCode == null) + throw new ArgumentNullException(nameof(colorCode), "Property is required for class Apple."); + + if (cultivar == null) + throw new ArgumentNullException(nameof(cultivar), "Property is required for class Apple."); + + if (origin == null) + throw new ArgumentNullException(nameof(origin), "Property is required for class Apple."); + + return new Apple(colorCode, cultivar, origin); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, apple, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Apple apple, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("color_code", apple.ColorCode); + writer.WriteString("cultivar", apple.Cultivar); + writer.WriteString("origin", apple.Origin); + } + } + + /// + /// The AppleSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Apple))] + public partial class AppleSerializationContext : JsonSerializerContext + { + /// + /// The AppleSerializationContext + /// + /// + public AppleSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// AppleDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Apple))] + public partial class AppleDeserializationContext : JsonSerializerContext + { + /// + /// AppleDeserializationContext + /// + /// + public AppleDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AppleReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AppleReq.cs new file mode 100644 index 00000000000..73317b812bb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AppleReq.cs @@ -0,0 +1,209 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// AppleReq + /// + public partial class AppleReq : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// cultivar + /// mealy + [JsonConstructor] + public AppleReq(string cultivar, bool mealy) + { + Cultivar = cultivar; + Mealy = mealy; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Cultivar + /// + [JsonPropertyName("cultivar")] + public string Cultivar { get; set; } + + /// + /// Gets or Sets Mealy + /// + [JsonPropertyName("mealy")] + public bool Mealy { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AppleReq {\n"); + sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); + sb.Append(" Mealy: ").Append(Mealy).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AppleReqJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? cultivar = default; + bool? mealy = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "cultivar": + cultivar = utf8JsonReader.GetString(); + break; + case "mealy": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + mealy = utf8JsonReader.GetBoolean(); + break; + default: + break; + } + } + } + + if (cultivar == null) + throw new ArgumentNullException(nameof(cultivar), "Property is required for class AppleReq."); + + if (mealy == null) + throw new ArgumentNullException(nameof(mealy), "Property is required for class AppleReq."); + + return new AppleReq(cultivar, mealy.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AppleReq appleReq, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, appleReq, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, AppleReq appleReq, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("cultivar", appleReq.Cultivar); + writer.WriteBoolean("mealy", appleReq.Mealy); + } + } + + /// + /// The AppleReqSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(AppleReq))] + public partial class AppleReqSerializationContext : JsonSerializerContext + { + /// + /// The AppleReqSerializationContext + /// + /// + public AppleReqSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// AppleReqDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(AppleReq))] + public partial class AppleReqDeserializationContext : JsonSerializerContext + { + /// + /// AppleReqDeserializationContext + /// + /// + public AppleReqDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfArrayOfNumberOnly.cs new file mode 100644 index 00000000000..3436dbbc9e7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfArrayOfNumberOnly.cs @@ -0,0 +1,200 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ArrayOfArrayOfNumberOnly + /// + public partial class ArrayOfArrayOfNumberOnly : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayArrayNumber + [JsonConstructor] + public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber) + { + ArrayArrayNumber = arrayArrayNumber; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ArrayArrayNumber + /// + [JsonPropertyName("ArrayArrayNumber")] + public List> ArrayArrayNumber { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ArrayOfArrayOfNumberOnly {\n"); + sb.Append(" ArrayArrayNumber: ").Append(ArrayArrayNumber).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ArrayOfArrayOfNumberOnlyJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + List>? arrayArrayNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "ArrayArrayNumber": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + arrayArrayNumber = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (arrayArrayNumber == null) + throw new ArgumentNullException(nameof(arrayArrayNumber), "Property is required for class ArrayOfArrayOfNumberOnly."); + + return new ArrayOfArrayOfNumberOnly(arrayArrayNumber); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, arrayOfArrayOfNumberOnly, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("ArrayArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, jsonSerializerOptions); + } + } + + /// + /// The ArrayOfArrayOfNumberOnlySerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ArrayOfArrayOfNumberOnly))] + public partial class ArrayOfArrayOfNumberOnlySerializationContext : JsonSerializerContext + { + /// + /// The ArrayOfArrayOfNumberOnlySerializationContext + /// + /// + public ArrayOfArrayOfNumberOnlySerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ArrayOfArrayOfNumberOnlyDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ArrayOfArrayOfNumberOnly))] + public partial class ArrayOfArrayOfNumberOnlyDeserializationContext : JsonSerializerContext + { + /// + /// ArrayOfArrayOfNumberOnlyDeserializationContext + /// + /// + public ArrayOfArrayOfNumberOnlyDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfNumberOnly.cs new file mode 100644 index 00000000000..58fd354388e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfNumberOnly.cs @@ -0,0 +1,200 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ArrayOfNumberOnly + /// + public partial class ArrayOfNumberOnly : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayNumber + [JsonConstructor] + public ArrayOfNumberOnly(List arrayNumber) + { + ArrayNumber = arrayNumber; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ArrayNumber + /// + [JsonPropertyName("ArrayNumber")] + public List ArrayNumber { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ArrayOfNumberOnly {\n"); + sb.Append(" ArrayNumber: ").Append(ArrayNumber).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ArrayOfNumberOnlyJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + List? arrayNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "ArrayNumber": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + arrayNumber = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (arrayNumber == null) + throw new ArgumentNullException(nameof(arrayNumber), "Property is required for class ArrayOfNumberOnly."); + + return new ArrayOfNumberOnly(arrayNumber); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, arrayOfNumberOnly, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("ArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, jsonSerializerOptions); + } + } + + /// + /// The ArrayOfNumberOnlySerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ArrayOfNumberOnly))] + public partial class ArrayOfNumberOnlySerializationContext : JsonSerializerContext + { + /// + /// The ArrayOfNumberOnlySerializationContext + /// + /// + public ArrayOfNumberOnlySerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ArrayOfNumberOnlyDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ArrayOfNumberOnly))] + public partial class ArrayOfNumberOnlyDeserializationContext : JsonSerializerContext + { + /// + /// ArrayOfNumberOnlyDeserializationContext + /// + /// + public ArrayOfNumberOnlyDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayTest.cs new file mode 100644 index 00000000000..933fda6ab8f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayTest.cs @@ -0,0 +1,238 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ArrayTest + /// + public partial class ArrayTest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayArrayOfInteger + /// arrayArrayOfModel + /// arrayOfString + [JsonConstructor] + public ArrayTest(List> arrayArrayOfInteger, List> arrayArrayOfModel, List arrayOfString) + { + ArrayArrayOfInteger = arrayArrayOfInteger; + ArrayArrayOfModel = arrayArrayOfModel; + ArrayOfString = arrayOfString; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ArrayArrayOfInteger + /// + [JsonPropertyName("array_array_of_integer")] + public List> ArrayArrayOfInteger { get; set; } + + /// + /// Gets or Sets ArrayArrayOfModel + /// + [JsonPropertyName("array_array_of_model")] + public List> ArrayArrayOfModel { get; set; } + + /// + /// Gets or Sets ArrayOfString + /// + [JsonPropertyName("array_of_string")] + public List ArrayOfString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ArrayTest {\n"); + sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); + sb.Append(" ArrayArrayOfModel: ").Append(ArrayArrayOfModel).Append("\n"); + sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ArrayTestJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + List>? arrayArrayOfInteger = default; + List>? arrayArrayOfModel = default; + List? arrayOfString = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "array_array_of_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + arrayArrayOfInteger = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "array_array_of_model": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + arrayArrayOfModel = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + arrayOfString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (arrayArrayOfInteger == null) + throw new ArgumentNullException(nameof(arrayArrayOfInteger), "Property is required for class ArrayTest."); + + if (arrayArrayOfModel == null) + throw new ArgumentNullException(nameof(arrayArrayOfModel), "Property is required for class ArrayTest."); + + if (arrayOfString == null) + throw new ArgumentNullException(nameof(arrayOfString), "Property is required for class ArrayTest."); + + return new ArrayTest(arrayArrayOfInteger, arrayArrayOfModel, arrayOfString); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ArrayTest arrayTest, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, arrayTest, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ArrayTest arrayTest, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("array_array_of_integer"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, jsonSerializerOptions); + writer.WritePropertyName("array_array_of_model"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, jsonSerializerOptions); + writer.WritePropertyName("array_of_string"); + JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, jsonSerializerOptions); + } + } + + /// + /// The ArrayTestSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ArrayTest))] + public partial class ArrayTestSerializationContext : JsonSerializerContext + { + /// + /// The ArrayTestSerializationContext + /// + /// + public ArrayTestSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ArrayTestDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ArrayTest))] + public partial class ArrayTestDeserializationContext : JsonSerializerContext + { + /// + /// ArrayTestDeserializationContext + /// + /// + public ArrayTestDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Banana.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Banana.cs new file mode 100644 index 00000000000..96ebf1eb703 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Banana.cs @@ -0,0 +1,199 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Banana + /// + public partial class Banana : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// lengthCm + [JsonConstructor] + public Banana(decimal lengthCm) + { + LengthCm = lengthCm; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets LengthCm + /// + [JsonPropertyName("lengthCm")] + public decimal LengthCm { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Banana {\n"); + sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BananaJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + decimal? lengthCm = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "lengthCm": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + lengthCm = utf8JsonReader.GetDecimal(); + break; + default: + break; + } + } + } + + if (lengthCm == null) + throw new ArgumentNullException(nameof(lengthCm), "Property is required for class Banana."); + + return new Banana(lengthCm.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, banana, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Banana banana, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("lengthCm", banana.LengthCm); + } + } + + /// + /// The BananaSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Banana))] + public partial class BananaSerializationContext : JsonSerializerContext + { + /// + /// The BananaSerializationContext + /// + /// + public BananaSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// BananaDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Banana))] + public partial class BananaDeserializationContext : JsonSerializerContext + { + /// + /// BananaDeserializationContext + /// + /// + public BananaDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BananaReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BananaReq.cs new file mode 100644 index 00000000000..e39fb405511 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BananaReq.cs @@ -0,0 +1,210 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// BananaReq + /// + public partial class BananaReq : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// lengthCm + /// sweet + [JsonConstructor] + public BananaReq(decimal lengthCm, bool sweet) + { + LengthCm = lengthCm; + Sweet = sweet; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets LengthCm + /// + [JsonPropertyName("lengthCm")] + public decimal LengthCm { get; set; } + + /// + /// Gets or Sets Sweet + /// + [JsonPropertyName("sweet")] + public bool Sweet { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BananaReq {\n"); + sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); + sb.Append(" Sweet: ").Append(Sweet).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BananaReqJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + decimal? lengthCm = default; + bool? sweet = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "lengthCm": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + lengthCm = utf8JsonReader.GetDecimal(); + break; + case "sweet": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + sweet = utf8JsonReader.GetBoolean(); + break; + default: + break; + } + } + } + + if (lengthCm == null) + throw new ArgumentNullException(nameof(lengthCm), "Property is required for class BananaReq."); + + if (sweet == null) + throw new ArgumentNullException(nameof(sweet), "Property is required for class BananaReq."); + + return new BananaReq(lengthCm.Value, sweet.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BananaReq bananaReq, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, bananaReq, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, BananaReq bananaReq, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("lengthCm", bananaReq.LengthCm); + writer.WriteBoolean("sweet", bananaReq.Sweet); + } + } + + /// + /// The BananaReqSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(BananaReq))] + public partial class BananaReqSerializationContext : JsonSerializerContext + { + /// + /// The BananaReqSerializationContext + /// + /// + public BananaReqSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// BananaReqDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(BananaReq))] + public partial class BananaReqDeserializationContext : JsonSerializerContext + { + /// + /// BananaReqDeserializationContext + /// + /// + public BananaReqDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BasquePig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BasquePig.cs new file mode 100644 index 00000000000..cf774084149 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BasquePig.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// BasquePig + /// + public partial class BasquePig : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// className + [JsonConstructor] + public BasquePig(string className) + { + ClassName = className; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ClassName + /// + [JsonPropertyName("className")] + public string ClassName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BasquePig {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BasquePigJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? className = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "className": + className = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (className == null) + throw new ArgumentNullException(nameof(className), "Property is required for class BasquePig."); + + return new BasquePig(className); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BasquePig basquePig, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, basquePig, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, BasquePig basquePig, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("className", basquePig.ClassName); + } + } + + /// + /// The BasquePigSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(BasquePig))] + public partial class BasquePigSerializationContext : JsonSerializerContext + { + /// + /// The BasquePigSerializationContext + /// + /// + public BasquePigSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// BasquePigDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(BasquePig))] + public partial class BasquePigDeserializationContext : JsonSerializerContext + { + /// + /// BasquePigDeserializationContext + /// + /// + public BasquePigDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Capitalization.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Capitalization.cs new file mode 100644 index 00000000000..0cc55ad39e6 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Capitalization.cs @@ -0,0 +1,284 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Capitalization + /// + public partial class Capitalization : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Name of the pet + /// capitalCamel + /// capitalSnake + /// sCAETHFlowPoints + /// smallCamel + /// smallSnake + [JsonConstructor] + public Capitalization(string aTTNAME, string capitalCamel, string capitalSnake, string sCAETHFlowPoints, string smallCamel, string smallSnake) + { + ATT_NAME = aTTNAME; + CapitalCamel = capitalCamel; + CapitalSnake = capitalSnake; + SCAETHFlowPoints = sCAETHFlowPoints; + SmallCamel = smallCamel; + SmallSnake = smallSnake; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Name of the pet + /// + /// Name of the pet + [JsonPropertyName("ATT_NAME")] + public string ATT_NAME { get; set; } + + /// + /// Gets or Sets CapitalCamel + /// + [JsonPropertyName("CapitalCamel")] + public string CapitalCamel { get; set; } + + /// + /// Gets or Sets CapitalSnake + /// + [JsonPropertyName("Capital_Snake")] + public string CapitalSnake { get; set; } + + /// + /// Gets or Sets SCAETHFlowPoints + /// + [JsonPropertyName("SCA_ETH_Flow_Points")] + public string SCAETHFlowPoints { get; set; } + + /// + /// Gets or Sets SmallCamel + /// + [JsonPropertyName("smallCamel")] + public string SmallCamel { get; set; } + + /// + /// Gets or Sets SmallSnake + /// + [JsonPropertyName("small_Snake")] + public string SmallSnake { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Capitalization {\n"); + sb.Append(" ATT_NAME: ").Append(ATT_NAME).Append("\n"); + sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); + sb.Append(" CapitalSnake: ").Append(CapitalSnake).Append("\n"); + sb.Append(" SCAETHFlowPoints: ").Append(SCAETHFlowPoints).Append("\n"); + sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); + sb.Append(" SmallSnake: ").Append(SmallSnake).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapitalizationJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? aTTNAME = default; + string? capitalCamel = default; + string? capitalSnake = default; + string? sCAETHFlowPoints = default; + string? smallCamel = default; + string? smallSnake = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "ATT_NAME": + aTTNAME = utf8JsonReader.GetString(); + break; + case "CapitalCamel": + capitalCamel = utf8JsonReader.GetString(); + break; + case "Capital_Snake": + capitalSnake = utf8JsonReader.GetString(); + break; + case "SCA_ETH_Flow_Points": + sCAETHFlowPoints = utf8JsonReader.GetString(); + break; + case "smallCamel": + smallCamel = utf8JsonReader.GetString(); + break; + case "small_Snake": + smallSnake = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (aTTNAME == null) + throw new ArgumentNullException(nameof(aTTNAME), "Property is required for class Capitalization."); + + if (capitalCamel == null) + throw new ArgumentNullException(nameof(capitalCamel), "Property is required for class Capitalization."); + + if (capitalSnake == null) + throw new ArgumentNullException(nameof(capitalSnake), "Property is required for class Capitalization."); + + if (sCAETHFlowPoints == null) + throw new ArgumentNullException(nameof(sCAETHFlowPoints), "Property is required for class Capitalization."); + + if (smallCamel == null) + throw new ArgumentNullException(nameof(smallCamel), "Property is required for class Capitalization."); + + if (smallSnake == null) + throw new ArgumentNullException(nameof(smallSnake), "Property is required for class Capitalization."); + + return new Capitalization(aTTNAME, capitalCamel, capitalSnake, sCAETHFlowPoints, smallCamel, smallSnake); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Capitalization capitalization, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, capitalization, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Capitalization capitalization, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("ATT_NAME", capitalization.ATT_NAME); + writer.WriteString("CapitalCamel", capitalization.CapitalCamel); + writer.WriteString("Capital_Snake", capitalization.CapitalSnake); + writer.WriteString("SCA_ETH_Flow_Points", capitalization.SCAETHFlowPoints); + writer.WriteString("smallCamel", capitalization.SmallCamel); + writer.WriteString("small_Snake", capitalization.SmallSnake); + } + } + + /// + /// The CapitalizationSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Capitalization))] + public partial class CapitalizationSerializationContext : JsonSerializerContext + { + /// + /// The CapitalizationSerializationContext + /// + /// + public CapitalizationSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// CapitalizationDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Capitalization))] + public partial class CapitalizationDeserializationContext : JsonSerializerContext + { + /// + /// CapitalizationDeserializationContext + /// + /// + public CapitalizationDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Cat.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Cat.cs new file mode 100644 index 00000000000..4d14aac0664 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Cat.cs @@ -0,0 +1,201 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Cat + /// + public partial class Cat : Animal, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// className + /// declawed + /// color (default to "red") + [JsonConstructor] + public Cat(string className, bool declawed, string color = @"red") : base(className, color) + { + Declawed = declawed; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Declawed + /// + [JsonPropertyName("declawed")] + public bool Declawed { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Cat {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" Declawed: ").Append(Declawed).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class CatJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? className = default; + bool? declawed = default; + string? color = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "className": + className = utf8JsonReader.GetString(); + break; + case "declawed": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + declawed = utf8JsonReader.GetBoolean(); + break; + case "color": + color = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (className == null) + throw new ArgumentNullException(nameof(className), "Property is required for class Cat."); + + if (declawed == null) + throw new ArgumentNullException(nameof(declawed), "Property is required for class Cat."); + + if (color == null) + throw new ArgumentNullException(nameof(color), "Property is required for class Cat."); + + return new Cat(className, declawed.Value, color); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, cat, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Cat cat, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("className", cat.ClassName); + writer.WriteBoolean("declawed", cat.Declawed); + writer.WriteString("color", cat.Color); + } + } + + /// + /// The CatSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Cat))] + public partial class CatSerializationContext : JsonSerializerContext + { + /// + /// The CatSerializationContext + /// + /// + public CatSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// CatDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Cat))] + public partial class CatDeserializationContext : JsonSerializerContext + { + /// + /// CatDeserializationContext + /// + /// + public CatDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Category.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Category.cs new file mode 100644 index 00000000000..a01ca0206bd --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Category.cs @@ -0,0 +1,216 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Category + /// + public partial class Category : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id + /// name (default to "default-name") + [JsonConstructor] + public Category(long id, string name = @"default-name") + { + Id = id; + Name = name; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Category {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CategoryJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + long? id = default; + string? name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + id = utf8JsonReader.GetInt64(); + break; + case "name": + name = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (id == null) + throw new ArgumentNullException(nameof(id), "Property is required for class Category."); + + if (name == null) + throw new ArgumentNullException(nameof(name), "Property is required for class Category."); + + return new Category(id.Value, name); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Category category, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, category, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Category category, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("id", category.Id); + writer.WriteString("name", category.Name); + } + } + + /// + /// The CategorySerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Category))] + public partial class CategorySerializationContext : JsonSerializerContext + { + /// + /// The CategorySerializationContext + /// + /// + public CategorySerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// CategoryDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Category))] + public partial class CategoryDeserializationContext : JsonSerializerContext + { + /// + /// CategoryDeserializationContext + /// + /// + public CategoryDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ChildCat.cs new file mode 100644 index 00000000000..c2d70d4488a --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ChildCat.cs @@ -0,0 +1,259 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ChildCat + /// + public partial class ChildCat : ParentPet, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + /// petType (default to PetTypeEnum.ChildCat) + [JsonConstructor] + public ChildCat(string name, PetTypeEnum petType = PetTypeEnum.ChildCat) : base(ChildCat.PetTypeEnumToJsonValue(petType)) + { + Name = name; + PetType = petType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Defines PetType + /// + public enum PetTypeEnum + { + /// + /// Enum ChildCat for value: ChildCat + /// + ChildCat = 1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static PetTypeEnum PetTypeEnumFromString(string value) + { + if (value.Equals("ChildCat")) + return PetTypeEnum.ChildCat; + + throw new NotImplementedException($"Could not convert value to type PetTypeEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static PetTypeEnum? PetTypeEnumFromStringOrDefault(string value) + { + if (value.Equals("ChildCat")) + return PetTypeEnum.ChildCat; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string PetTypeEnumToJsonValue(PetTypeEnum value) + { + if (value == PetTypeEnum.ChildCat) + return "ChildCat"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets PetType + /// + [JsonPropertyName("pet_type")] + public new PetTypeEnum PetType { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ChildCat {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PetType: ").Append(PetType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class ChildCatJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? name = default; + ChildCat.PetTypeEnum? petType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + name = utf8JsonReader.GetString(); + break; + case "pet_type": + string? petTypeRawValue = utf8JsonReader.GetString(); + petType = petTypeRawValue == null + ? null + : ChildCat.PetTypeEnumFromStringOrDefault(petTypeRawValue); + break; + default: + break; + } + } + } + + if (name == null) + throw new ArgumentNullException(nameof(name), "Property is required for class ChildCat."); + + if (petType == null) + throw new ArgumentNullException(nameof(petType), "Property is required for class ChildCat."); + + return new ChildCat(name, petType.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, childCat, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("name", childCat.Name); + + var petTypeRawValue = ChildCat.PetTypeEnumToJsonValue(childCat.PetType); + if (petTypeRawValue != null) + writer.WriteString("pet_type", petTypeRawValue); + else + writer.WriteNull("pet_type"); + } + } + + /// + /// The ChildCatSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ChildCat))] + public partial class ChildCatSerializationContext : JsonSerializerContext + { + /// + /// The ChildCatSerializationContext + /// + /// + public ChildCatSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ChildCatDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ChildCat))] + public partial class ChildCatDeserializationContext : JsonSerializerContext + { + /// + /// ChildCatDeserializationContext + /// + /// + public ChildCatDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ClassModel.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ClassModel.cs new file mode 100644 index 00000000000..8accbfa81d6 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ClassModel.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Model for testing model with \"_class\" property + /// + public partial class ClassModel : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// varClass + [JsonConstructor] + public ClassModel(string varClass) + { + VarClass = varClass; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets VarClass + /// + [JsonPropertyName("_class")] + public string VarClass { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ClassModel {\n"); + sb.Append(" VarClass: ").Append(VarClass).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ClassModelJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? varClass = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "_class": + varClass = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (varClass == null) + throw new ArgumentNullException(nameof(varClass), "Property is required for class ClassModel."); + + return new ClassModel(varClass); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ClassModel classModel, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, classModel, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ClassModel classModel, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("_class", classModel.VarClass); + } + } + + /// + /// The ClassModelSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ClassModel))] + public partial class ClassModelSerializationContext : JsonSerializerContext + { + /// + /// The ClassModelSerializationContext + /// + /// + public ClassModelSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ClassModelDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ClassModel))] + public partial class ClassModelDeserializationContext : JsonSerializerContext + { + /// + /// ClassModelDeserializationContext + /// + /// + public ClassModelDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ComplexQuadrilateral.cs new file mode 100644 index 00000000000..e831cef5762 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ComplexQuadrilateral.cs @@ -0,0 +1,215 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ComplexQuadrilateral + /// + public partial class ComplexQuadrilateral : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// quadrilateralType + /// shapeType + [JsonConstructor] + public ComplexQuadrilateral(string quadrilateralType, string shapeType) + { + QuadrilateralType = quadrilateralType; + ShapeType = shapeType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets QuadrilateralType + /// + [JsonPropertyName("quadrilateralType")] + public string QuadrilateralType { get; set; } + + /// + /// Gets or Sets ShapeType + /// + [JsonPropertyName("shapeType")] + public string ShapeType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ComplexQuadrilateral {\n"); + sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ComplexQuadrilateralJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? quadrilateralType = default; + string? shapeType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "quadrilateralType": + quadrilateralType = utf8JsonReader.GetString(); + break; + case "shapeType": + shapeType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (quadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class ComplexQuadrilateral."); + + if (shapeType == null) + throw new ArgumentNullException(nameof(shapeType), "Property is required for class ComplexQuadrilateral."); + + return new ComplexQuadrilateral(quadrilateralType, shapeType); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, complexQuadrilateral, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("quadrilateralType", complexQuadrilateral.QuadrilateralType); + writer.WriteString("shapeType", complexQuadrilateral.ShapeType); + } + } + + /// + /// The ComplexQuadrilateralSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ComplexQuadrilateral))] + public partial class ComplexQuadrilateralSerializationContext : JsonSerializerContext + { + /// + /// The ComplexQuadrilateralSerializationContext + /// + /// + public ComplexQuadrilateralSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ComplexQuadrilateralDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ComplexQuadrilateral))] + public partial class ComplexQuadrilateralDeserializationContext : JsonSerializerContext + { + /// + /// ComplexQuadrilateralDeserializationContext + /// + /// + public ComplexQuadrilateralDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DanishPig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DanishPig.cs new file mode 100644 index 00000000000..e67e90ff44b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DanishPig.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// DanishPig + /// + public partial class DanishPig : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// className + [JsonConstructor] + public DanishPig(string className) + { + ClassName = className; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ClassName + /// + [JsonPropertyName("className")] + public string ClassName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DanishPig {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DanishPigJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? className = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "className": + className = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (className == null) + throw new ArgumentNullException(nameof(className), "Property is required for class DanishPig."); + + return new DanishPig(className); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DanishPig danishPig, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, danishPig, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, DanishPig danishPig, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("className", danishPig.ClassName); + } + } + + /// + /// The DanishPigSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(DanishPig))] + public partial class DanishPigSerializationContext : JsonSerializerContext + { + /// + /// The DanishPigSerializationContext + /// + /// + public DanishPigSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// DanishPigDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(DanishPig))] + public partial class DanishPigDeserializationContext : JsonSerializerContext + { + /// + /// DanishPigDeserializationContext + /// + /// + public DanishPigDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DateOnlyClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DateOnlyClass.cs new file mode 100644 index 00000000000..645d84b7a14 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DateOnlyClass.cs @@ -0,0 +1,205 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// DateOnlyClass + /// + public partial class DateOnlyClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// dateOnlyProperty + [JsonConstructor] + public DateOnlyClass(DateTime dateOnlyProperty) + { + DateOnlyProperty = dateOnlyProperty; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets DateOnlyProperty + /// + /// Fri Jul 21 00:00:00 UTC 2017 + [JsonPropertyName("dateOnlyProperty")] + public DateTime DateOnlyProperty { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DateOnlyClass {\n"); + sb.Append(" DateOnlyProperty: ").Append(DateOnlyProperty).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DateOnlyClassJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOnlyProperty + /// + public static string DateOnlyPropertyFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + DateTime? dateOnlyProperty = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "dateOnlyProperty": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + dateOnlyProperty = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (dateOnlyProperty == null) + throw new ArgumentNullException(nameof(dateOnlyProperty), "Property is required for class DateOnlyClass."); + + return new DateOnlyClass(dateOnlyProperty.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnlyClass dateOnlyClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, dateOnlyClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, DateOnlyClass dateOnlyClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("dateOnlyProperty", dateOnlyClass.DateOnlyProperty.ToString(DateOnlyPropertyFormat)); + } + } + + /// + /// The DateOnlyClassSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(DateOnlyClass))] + public partial class DateOnlyClassSerializationContext : JsonSerializerContext + { + /// + /// The DateOnlyClassSerializationContext + /// + /// + public DateOnlyClassSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// DateOnlyClassDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(DateOnlyClass))] + public partial class DateOnlyClassDeserializationContext : JsonSerializerContext + { + /// + /// DateOnlyClassDeserializationContext + /// + /// + public DateOnlyClassDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DeprecatedObject.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DeprecatedObject.cs new file mode 100644 index 00000000000..d1f20b4cf53 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DeprecatedObject.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// DeprecatedObject + /// + public partial class DeprecatedObject : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + [JsonConstructor] + public DeprecatedObject(string name) + { + Name = name; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeprecatedObject {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeprecatedObjectJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + name = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (name == null) + throw new ArgumentNullException(nameof(name), "Property is required for class DeprecatedObject."); + + return new DeprecatedObject(name); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeprecatedObject deprecatedObject, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, deprecatedObject, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, DeprecatedObject deprecatedObject, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("name", deprecatedObject.Name); + } + } + + /// + /// The DeprecatedObjectSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(DeprecatedObject))] + public partial class DeprecatedObjectSerializationContext : JsonSerializerContext + { + /// + /// The DeprecatedObjectSerializationContext + /// + /// + public DeprecatedObjectSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// DeprecatedObjectDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(DeprecatedObject))] + public partial class DeprecatedObjectDeserializationContext : JsonSerializerContext + { + /// + /// DeprecatedObjectDeserializationContext + /// + /// + public DeprecatedObjectDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Dog.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Dog.cs new file mode 100644 index 00000000000..bb77154d9b4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Dog.cs @@ -0,0 +1,200 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Dog + /// + public partial class Dog : Animal, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// breed + /// className + /// color (default to "red") + [JsonConstructor] + public Dog(string breed, string className, string color = @"red") : base(className, color) + { + Breed = breed; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Breed + /// + [JsonPropertyName("breed")] + public string Breed { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Dog {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" Breed: ").Append(Breed).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class DogJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? breed = default; + string? className = default; + string? color = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "breed": + breed = utf8JsonReader.GetString(); + break; + case "className": + className = utf8JsonReader.GetString(); + break; + case "color": + color = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (breed == null) + throw new ArgumentNullException(nameof(breed), "Property is required for class Dog."); + + if (className == null) + throw new ArgumentNullException(nameof(className), "Property is required for class Dog."); + + if (color == null) + throw new ArgumentNullException(nameof(color), "Property is required for class Dog."); + + return new Dog(breed, className, color); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, dog, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Dog dog, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("breed", dog.Breed); + writer.WriteString("className", dog.ClassName); + writer.WriteString("color", dog.Color); + } + } + + /// + /// The DogSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Dog))] + public partial class DogSerializationContext : JsonSerializerContext + { + /// + /// The DogSerializationContext + /// + /// + public DogSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// DogDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Dog))] + public partial class DogDeserializationContext : JsonSerializerContext + { + /// + /// DogDeserializationContext + /// + /// + public DogDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Drawing.cs new file mode 100644 index 00000000000..eee5adff943 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Drawing.cs @@ -0,0 +1,262 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Drawing + /// + public partial class Drawing : Dictionary, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// mainShape + /// shapes + /// nullableShape + /// shapeOrNull + [JsonConstructor] + public Drawing(Shape mainShape, List shapes, NullableShape? nullableShape = default, ShapeOrNull? shapeOrNull = default) : base() + { + MainShape = mainShape; + Shapes = shapes; + NullableShape = nullableShape; + ShapeOrNull = shapeOrNull; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets MainShape + /// + [JsonPropertyName("mainShape")] + public Shape MainShape { get; set; } + + /// + /// Gets or Sets Shapes + /// + [JsonPropertyName("shapes")] + public List Shapes { get; set; } + + /// + /// Gets or Sets NullableShape + /// + [JsonPropertyName("nullableShape")] + public NullableShape? NullableShape { get; set; } + + /// + /// Gets or Sets ShapeOrNull + /// + [JsonPropertyName("shapeOrNull")] + public ShapeOrNull? ShapeOrNull { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Drawing {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" MainShape: ").Append(MainShape).Append("\n"); + sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); + sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DrawingJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Shape? mainShape = default; + List? shapes = default; + NullableShape? nullableShape = default; + ShapeOrNull? shapeOrNull = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "mainShape": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + mainShape = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "shapes": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + shapes = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "nullableShape": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + nullableShape = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "shapeOrNull": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + shapeOrNull = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (mainShape == null) + throw new ArgumentNullException(nameof(mainShape), "Property is required for class Drawing."); + + if (shapes == null) + throw new ArgumentNullException(nameof(shapes), "Property is required for class Drawing."); + + return new Drawing(mainShape, shapes, nullableShape, shapeOrNull); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Drawing drawing, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, drawing, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Drawing drawing, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("mainShape"); + JsonSerializer.Serialize(writer, drawing.MainShape, jsonSerializerOptions); + writer.WritePropertyName("shapes"); + JsonSerializer.Serialize(writer, drawing.Shapes, jsonSerializerOptions); + writer.WritePropertyName("nullableShape"); + JsonSerializer.Serialize(writer, drawing.NullableShape, jsonSerializerOptions); + writer.WritePropertyName("shapeOrNull"); + JsonSerializer.Serialize(writer, drawing.ShapeOrNull, jsonSerializerOptions); + } + } + + /// + /// The DrawingSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Drawing))] + public partial class DrawingSerializationContext : JsonSerializerContext + { + /// + /// The DrawingSerializationContext + /// + /// + public DrawingSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// DrawingDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Drawing))] + public partial class DrawingDeserializationContext : JsonSerializerContext + { + /// + /// DrawingDeserializationContext + /// + /// + public DrawingDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumArrays.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumArrays.cs new file mode 100644 index 00000000000..2456ab09872 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumArrays.cs @@ -0,0 +1,357 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// EnumArrays + /// + public partial class EnumArrays : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayEnum + /// justSymbol + [JsonConstructor] + public EnumArrays(List arrayEnum, JustSymbolEnum justSymbol) + { + ArrayEnum = arrayEnum; + JustSymbol = justSymbol; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Defines ArrayEnum + /// + public enum ArrayEnumEnum + { + /// + /// Enum Fish for value: fish + /// + Fish = 1, + + /// + /// Enum Crab for value: crab + /// + Crab = 2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static ArrayEnumEnum ArrayEnumEnumFromString(string value) + { + if (value.Equals("fish")) + return ArrayEnumEnum.Fish; + + if (value.Equals("crab")) + return ArrayEnumEnum.Crab; + + throw new NotImplementedException($"Could not convert value to type ArrayEnumEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static ArrayEnumEnum? ArrayEnumEnumFromStringOrDefault(string value) + { + if (value.Equals("fish")) + return ArrayEnumEnum.Fish; + + if (value.Equals("crab")) + return ArrayEnumEnum.Crab; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ArrayEnumEnumToJsonValue(ArrayEnumEnum value) + { + if (value == ArrayEnumEnum.Fish) + return "fish"; + + if (value == ArrayEnumEnum.Crab) + return "crab"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Defines JustSymbol + /// + public enum JustSymbolEnum + { + /// + /// Enum GreaterThanOrEqualTo for value: >= + /// + GreaterThanOrEqualTo = 1, + + /// + /// Enum Dollar for value: $ + /// + Dollar = 2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static JustSymbolEnum JustSymbolEnumFromString(string value) + { + if (value.Equals(">=")) + return JustSymbolEnum.GreaterThanOrEqualTo; + + if (value.Equals("$")) + return JustSymbolEnum.Dollar; + + throw new NotImplementedException($"Could not convert value to type JustSymbolEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static JustSymbolEnum? JustSymbolEnumFromStringOrDefault(string value) + { + if (value.Equals(">=")) + return JustSymbolEnum.GreaterThanOrEqualTo; + + if (value.Equals("$")) + return JustSymbolEnum.Dollar; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string JustSymbolEnumToJsonValue(JustSymbolEnum value) + { + if (value == JustSymbolEnum.GreaterThanOrEqualTo) + return ">="; + + if (value == JustSymbolEnum.Dollar) + return "$"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets JustSymbol + /// + [JsonPropertyName("just_symbol")] + public JustSymbolEnum JustSymbol { get; set; } + + /// + /// Gets or Sets ArrayEnum + /// + [JsonPropertyName("array_enum")] + public List ArrayEnum { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EnumArrays {\n"); + sb.Append(" ArrayEnum: ").Append(ArrayEnum).Append("\n"); + sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EnumArraysJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + List? arrayEnum = default; + EnumArrays.JustSymbolEnum? justSymbol = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "array_enum": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + arrayEnum = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "just_symbol": + string? justSymbolRawValue = utf8JsonReader.GetString(); + justSymbol = justSymbolRawValue == null + ? null + : EnumArrays.JustSymbolEnumFromStringOrDefault(justSymbolRawValue); + break; + default: + break; + } + } + } + + if (arrayEnum == null) + throw new ArgumentNullException(nameof(arrayEnum), "Property is required for class EnumArrays."); + + if (justSymbol == null) + throw new ArgumentNullException(nameof(justSymbol), "Property is required for class EnumArrays."); + + return new EnumArrays(arrayEnum, justSymbol.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnumArrays enumArrays, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, enumArrays, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, EnumArrays enumArrays, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("array_enum"); + JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, jsonSerializerOptions); + + var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbol); + if (justSymbolRawValue != null) + writer.WriteString("just_symbol", justSymbolRawValue); + else + writer.WriteNull("just_symbol"); + } + } + + /// + /// The EnumArraysSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(EnumArrays))] + public partial class EnumArraysSerializationContext : JsonSerializerContext + { + /// + /// The EnumArraysSerializationContext + /// + /// + public EnumArraysSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// EnumArraysDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(EnumArrays))] + public partial class EnumArraysDeserializationContext : JsonSerializerContext + { + /// + /// EnumArraysDeserializationContext + /// + /// + public EnumArraysDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumClass.cs new file mode 100644 index 00000000000..2d23eb5113d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumClass.cs @@ -0,0 +1,224 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Defines EnumClass + /// + public enum EnumClass + { + /// + /// Enum Abc for value: _abc + /// + Abc = 1, + + /// + /// Enum Efg for value: -efg + /// + Efg = 2, + + /// + /// Enum Xyz for value: (xyz) + /// + Xyz = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class EnumClassValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static EnumClass FromString(string value) + { + if (value.Equals("_abc")) + return EnumClass.Abc; + + if (value.Equals("-efg")) + return EnumClass.Efg; + + if (value.Equals("(xyz)")) + return EnumClass.Xyz; + + throw new NotImplementedException($"Could not convert value to type EnumClass: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static EnumClass? FromStringOrDefault(string value) + { + if (value.Equals("_abc")) + return EnumClass.Abc; + + if (value.Equals("-efg")) + return EnumClass.Efg; + + if (value.Equals("(xyz)")) + return EnumClass.Xyz; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(EnumClass value) + { + if (value == EnumClass.Abc) + return "_abc"; + + if (value == EnumClass.Efg) + return "-efg"; + + if (value == EnumClass.Xyz) + return "(xyz)"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class EnumClassJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override EnumClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + EnumClass? result = rawValue == null + ? null + : EnumClassValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the EnumClass to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnumClass enumClass, JsonSerializerOptions options) + { + writer.WriteStringValue(enumClass.ToString()); + } + } + + /// + /// A Json converter for type + /// + public class EnumClassNullableJsonConverter : JsonConverter + { + /// + /// Returns a EnumClass from the Json object + /// + /// + /// + /// + /// + public override EnumClass? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + EnumClass? result = rawValue == null + ? null + : EnumClassValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnumClass? enumClass, JsonSerializerOptions options) + { + writer.WriteStringValue(enumClass?.ToString() ?? "null"); + } + } + + + /// + /// The EnumClassSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(EnumClass))] + public partial class EnumClassSerializationContext : JsonSerializerContext + { + /// + /// The EnumClassSerializationContext + /// + /// + public EnumClassSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// EnumClassDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(EnumClass))] + public partial class EnumClassDeserializationContext : JsonSerializerContext + { + /// + /// EnumClassDeserializationContext + /// + /// + public EnumClassDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumTest.cs new file mode 100644 index 00000000000..ccf47d85d81 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumTest.cs @@ -0,0 +1,865 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// EnumTest + /// + public partial class EnumTest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// enumInteger + /// enumIntegerOnly + /// enumNumber + /// enumString + /// enumStringRequired + /// outerEnumDefaultValue + /// outerEnumInteger + /// outerEnumIntegerDefaultValue + /// outerEnum + [JsonConstructor] + public EnumTest(EnumIntegerEnum enumInteger, EnumIntegerOnlyEnum enumIntegerOnly, EnumNumberEnum enumNumber, EnumStringEnum enumString, EnumStringRequiredEnum enumStringRequired, OuterEnumDefaultValue outerEnumDefaultValue, OuterEnumInteger outerEnumInteger, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue, OuterEnum? outerEnum = default) + { + EnumInteger = enumInteger; + EnumIntegerOnly = enumIntegerOnly; + EnumNumber = enumNumber; + EnumString = enumString; + EnumStringRequired = enumStringRequired; + OuterEnumDefaultValue = outerEnumDefaultValue; + OuterEnumInteger = outerEnumInteger; + OuterEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + OuterEnum = outerEnum; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Defines EnumInteger + /// + public enum EnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static EnumIntegerEnum EnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return EnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return EnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type EnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static EnumIntegerEnum? EnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return EnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return EnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int EnumIntegerEnumToJsonValue(EnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets EnumInteger + /// + [JsonPropertyName("enum_integer")] + public EnumIntegerEnum EnumInteger { get; set; } + + /// + /// Defines EnumIntegerOnly + /// + public enum EnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static EnumIntegerOnlyEnum EnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return EnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return EnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type EnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static EnumIntegerOnlyEnum? EnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return EnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return EnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int EnumIntegerOnlyEnumToJsonValue(EnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets EnumIntegerOnly + /// + [JsonPropertyName("enum_integer_only")] + public EnumIntegerOnlyEnum EnumIntegerOnly { get; set; } + + /// + /// Defines EnumNumber + /// + public enum EnumNumberEnum + { + /// + /// Enum NUMBER_1_DOT_1 for value: 1.1 + /// + NUMBER_1_DOT_1 = 1, + + /// + /// Enum NUMBER_MINUS_1_DOT_2 for value: -1.2 + /// + NUMBER_MINUS_1_DOT_2 = 2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static EnumNumberEnum EnumNumberEnumFromString(string value) + { + if (value.Equals("1.1")) + return EnumNumberEnum.NUMBER_1_DOT_1; + + if (value.Equals("-1.2")) + return EnumNumberEnum.NUMBER_MINUS_1_DOT_2; + + throw new NotImplementedException($"Could not convert value to type EnumNumberEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static EnumNumberEnum? EnumNumberEnumFromStringOrDefault(string value) + { + if (value.Equals("1.1")) + return EnumNumberEnum.NUMBER_1_DOT_1; + + if (value.Equals("-1.2")) + return EnumNumberEnum.NUMBER_MINUS_1_DOT_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static double EnumNumberEnumToJsonValue(EnumNumberEnum value) + { + if (value == EnumNumberEnum.NUMBER_1_DOT_1) + return 1.1; + + if (value == EnumNumberEnum.NUMBER_MINUS_1_DOT_2) + return -1.2; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets EnumNumber + /// + [JsonPropertyName("enum_number")] + public EnumNumberEnum EnumNumber { get; set; } + + /// + /// Defines EnumString + /// + public enum EnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static EnumStringEnum EnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return EnumStringEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringEnum.Lower; + + if (value.Equals("")) + return EnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type EnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static EnumStringEnum? EnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return EnumStringEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringEnum.Lower; + + if (value.Equals("")) + return EnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string EnumStringEnumToJsonValue(EnumStringEnum value) + { + if (value == EnumStringEnum.UPPER) + return "UPPER"; + + if (value == EnumStringEnum.Lower) + return "lower"; + + if (value == EnumStringEnum.Empty) + return ""; + + if (value == EnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == EnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == EnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == EnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == EnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets EnumString + /// + [JsonPropertyName("enum_string")] + public EnumStringEnum EnumString { get; set; } + + /// + /// Defines EnumStringRequired + /// + public enum EnumStringRequiredEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) + { + if (value.Equals("UPPER")) + return EnumStringRequiredEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringRequiredEnum.Lower; + + if (value.Equals("")) + return EnumStringRequiredEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringRequiredEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringRequiredEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringRequiredEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static EnumStringRequiredEnum? EnumStringRequiredEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return EnumStringRequiredEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringRequiredEnum.Lower; + + if (value.Equals("")) + return EnumStringRequiredEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringRequiredEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringRequiredEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringRequiredEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string EnumStringRequiredEnumToJsonValue(EnumStringRequiredEnum value) + { + if (value == EnumStringRequiredEnum.UPPER) + return "UPPER"; + + if (value == EnumStringRequiredEnum.Lower) + return "lower"; + + if (value == EnumStringRequiredEnum.Empty) + return ""; + + if (value == EnumStringRequiredEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == EnumStringRequiredEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == EnumStringRequiredEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == EnumStringRequiredEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == EnumStringRequiredEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets EnumStringRequired + /// + [JsonPropertyName("enum_string_required")] + public EnumStringRequiredEnum EnumStringRequired { get; set; } + + /// + /// Gets or Sets OuterEnumDefaultValue + /// + [JsonPropertyName("outerEnumDefaultValue")] + public OuterEnumDefaultValue OuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets OuterEnumInteger + /// + [JsonPropertyName("outerEnumInteger")] + public OuterEnumInteger OuterEnumInteger { get; set; } + + /// + /// Gets or Sets OuterEnumIntegerDefaultValue + /// + [JsonPropertyName("outerEnumIntegerDefaultValue")] + public OuterEnumIntegerDefaultValue OuterEnumIntegerDefaultValue { get; set; } + + /// + /// Gets or Sets OuterEnum + /// + [JsonPropertyName("outerEnum")] + public OuterEnum? OuterEnum { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EnumTest {\n"); + sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); + sb.Append(" EnumIntegerOnly: ").Append(EnumIntegerOnly).Append("\n"); + sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); + sb.Append(" EnumString: ").Append(EnumString).Append("\n"); + sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); + sb.Append(" OuterEnumDefaultValue: ").Append(OuterEnumDefaultValue).Append("\n"); + sb.Append(" OuterEnumInteger: ").Append(OuterEnumInteger).Append("\n"); + sb.Append(" OuterEnumIntegerDefaultValue: ").Append(OuterEnumIntegerDefaultValue).Append("\n"); + sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EnumTestJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + EnumTest.EnumIntegerEnum? enumInteger = default; + EnumTest.EnumIntegerOnlyEnum? enumIntegerOnly = default; + EnumTest.EnumNumberEnum? enumNumber = default; + EnumTest.EnumStringEnum? enumString = default; + EnumTest.EnumStringRequiredEnum? enumStringRequired = default; + OuterEnumDefaultValue? outerEnumDefaultValue = default; + OuterEnumInteger? outerEnumInteger = default; + OuterEnumIntegerDefaultValue? outerEnumIntegerDefaultValue = default; + OuterEnum? outerEnum = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + enumInteger = (EnumTest.EnumIntegerEnum)utf8JsonReader.GetInt32(); + break; + case "enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + enumIntegerOnly = (EnumTest.EnumIntegerOnlyEnum)utf8JsonReader.GetInt32(); + break; + case "enum_number": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + enumNumber = (EnumTest.EnumNumberEnum)utf8JsonReader.GetInt32(); + break; + case "enum_string": + string? enumStringRawValue = utf8JsonReader.GetString(); + enumString = enumStringRawValue == null + ? null + : EnumTest.EnumStringEnumFromStringOrDefault(enumStringRawValue); + break; + case "enum_string_required": + string? enumStringRequiredRawValue = utf8JsonReader.GetString(); + enumStringRequired = enumStringRequiredRawValue == null + ? null + : EnumTest.EnumStringRequiredEnumFromStringOrDefault(enumStringRequiredRawValue); + break; + case "outerEnumDefaultValue": + string? outerEnumDefaultValueRawValue = utf8JsonReader.GetString(); + outerEnumDefaultValue = outerEnumDefaultValueRawValue == null + ? null + : OuterEnumDefaultValueValueConverter.FromStringOrDefault(outerEnumDefaultValueRawValue); + break; + case "outerEnumInteger": + string? outerEnumIntegerRawValue = utf8JsonReader.GetString(); + outerEnumInteger = outerEnumIntegerRawValue == null + ? null + : OuterEnumIntegerValueConverter.FromStringOrDefault(outerEnumIntegerRawValue); + break; + case "outerEnumIntegerDefaultValue": + string? outerEnumIntegerDefaultValueRawValue = utf8JsonReader.GetString(); + outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValueRawValue == null + ? null + : OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(outerEnumIntegerDefaultValueRawValue); + break; + case "outerEnum": + string? outerEnumRawValue = utf8JsonReader.GetString(); + outerEnum = outerEnumRawValue == null + ? null + : OuterEnumValueConverter.FromStringOrDefault(outerEnumRawValue); + break; + default: + break; + } + } + } + + if (enumInteger == null) + throw new ArgumentNullException(nameof(enumInteger), "Property is required for class EnumTest."); + + if (enumIntegerOnly == null) + throw new ArgumentNullException(nameof(enumIntegerOnly), "Property is required for class EnumTest."); + + if (enumNumber == null) + throw new ArgumentNullException(nameof(enumNumber), "Property is required for class EnumTest."); + + if (enumString == null) + throw new ArgumentNullException(nameof(enumString), "Property is required for class EnumTest."); + + if (enumStringRequired == null) + throw new ArgumentNullException(nameof(enumStringRequired), "Property is required for class EnumTest."); + + if (outerEnumDefaultValue == null) + throw new ArgumentNullException(nameof(outerEnumDefaultValue), "Property is required for class EnumTest."); + + if (outerEnumInteger == null) + throw new ArgumentNullException(nameof(outerEnumInteger), "Property is required for class EnumTest."); + + if (outerEnumIntegerDefaultValue == null) + throw new ArgumentNullException(nameof(outerEnumIntegerDefaultValue), "Property is required for class EnumTest."); + + return new EnumTest(enumInteger.Value, enumIntegerOnly.Value, enumNumber.Value, enumString.Value, enumStringRequired.Value, outerEnumDefaultValue.Value, outerEnumInteger.Value, outerEnumIntegerDefaultValue.Value, outerEnum); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnumTest enumTest, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, enumTest, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, EnumTest enumTest, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("enum_integer", EnumTest.EnumIntegerEnumToJsonValue(enumTest.EnumInteger)); + writer.WriteNumber("enum_integer_only", EnumTest.EnumIntegerOnlyEnumToJsonValue(enumTest.EnumIntegerOnly)); + writer.WriteNumber("enum_number", EnumTest.EnumNumberEnumToJsonValue(enumTest.EnumNumber)); + + var enumStringRawValue = EnumTest.EnumStringEnumToJsonValue(enumTest.EnumString); + if (enumStringRawValue != null) + writer.WriteString("enum_string", enumStringRawValue); + else + writer.WriteNull("enum_string"); + + var enumStringRequiredRawValue = EnumTest.EnumStringRequiredEnumToJsonValue(enumTest.EnumStringRequired); + if (enumStringRequiredRawValue != null) + writer.WriteString("enum_string_required", enumStringRequiredRawValue); + else + writer.WriteNull("enum_string_required"); + + var outerEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue); + + if (outerEnumDefaultValueRawValue != null) + writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); + else + writer.WriteNull("outerEnumDefaultValue"); + + var outerEnumIntegerRawValue = OuterEnumIntegerValueConverter.ToJsonValue(enumTest.OuterEnumInteger); + writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); + var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue); + writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); + + if (enumTest.OuterEnum == null) + writer.WriteNull("outerEnum"); + else + { + var outerEnumRawValue = OuterEnumValueConverter.ToJsonValue(enumTest.OuterEnum.Value); + if (outerEnumRawValue != null) + writer.WriteString("outerEnum", outerEnumRawValue); + else + writer.WriteNull("outerEnum"); + } + } + } + + /// + /// The EnumTestSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(EnumTest))] + public partial class EnumTestSerializationContext : JsonSerializerContext + { + /// + /// The EnumTestSerializationContext + /// + /// + public EnumTestSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// EnumTestDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(EnumTest))] + public partial class EnumTestDeserializationContext : JsonSerializerContext + { + /// + /// EnumTestDeserializationContext + /// + /// + public EnumTestDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EquilateralTriangle.cs new file mode 100644 index 00000000000..21835e24e30 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EquilateralTriangle.cs @@ -0,0 +1,215 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// EquilateralTriangle + /// + public partial class EquilateralTriangle : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// shapeType + /// triangleType + [JsonConstructor] + public EquilateralTriangle(string shapeType, string triangleType) + { + ShapeType = shapeType; + TriangleType = triangleType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ShapeType + /// + [JsonPropertyName("shapeType")] + public string ShapeType { get; set; } + + /// + /// Gets or Sets TriangleType + /// + [JsonPropertyName("triangleType")] + public string TriangleType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EquilateralTriangle {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EquilateralTriangleJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? shapeType = default; + string? triangleType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "shapeType": + shapeType = utf8JsonReader.GetString(); + break; + case "triangleType": + triangleType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (shapeType == null) + throw new ArgumentNullException(nameof(shapeType), "Property is required for class EquilateralTriangle."); + + if (triangleType == null) + throw new ArgumentNullException(nameof(triangleType), "Property is required for class EquilateralTriangle."); + + return new EquilateralTriangle(shapeType, triangleType); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, equilateralTriangle, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("shapeType", equilateralTriangle.ShapeType); + writer.WriteString("triangleType", equilateralTriangle.TriangleType); + } + } + + /// + /// The EquilateralTriangleSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(EquilateralTriangle))] + public partial class EquilateralTriangleSerializationContext : JsonSerializerContext + { + /// + /// The EquilateralTriangleSerializationContext + /// + /// + public EquilateralTriangleSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// EquilateralTriangleDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(EquilateralTriangle))] + public partial class EquilateralTriangleDeserializationContext : JsonSerializerContext + { + /// + /// EquilateralTriangleDeserializationContext + /// + /// + public EquilateralTriangleDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/File.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/File.cs new file mode 100644 index 00000000000..0af05bc9a53 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/File.cs @@ -0,0 +1,199 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Must be named `File` for test. + /// + public partial class File : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Test capitalization + [JsonConstructor] + public File(string sourceURI) + { + SourceURI = sourceURI; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Test capitalization + /// + /// Test capitalization + [JsonPropertyName("sourceURI")] + public string SourceURI { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class File {\n"); + sb.Append(" SourceURI: ").Append(SourceURI).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FileJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? sourceURI = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "sourceURI": + sourceURI = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (sourceURI == null) + throw new ArgumentNullException(nameof(sourceURI), "Property is required for class File."); + + return new File(sourceURI); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, File file, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, file, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, File file, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("sourceURI", file.SourceURI); + } + } + + /// + /// The FileSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(File))] + public partial class FileSerializationContext : JsonSerializerContext + { + /// + /// The FileSerializationContext + /// + /// + public FileSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// FileDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(File))] + public partial class FileDeserializationContext : JsonSerializerContext + { + /// + /// FileDeserializationContext + /// + /// + public FileDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FileSchemaTestClass.cs new file mode 100644 index 00000000000..40925985a15 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FileSchemaTestClass.cs @@ -0,0 +1,219 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// FileSchemaTestClass + /// + public partial class FileSchemaTestClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// file + /// files + [JsonConstructor] + public FileSchemaTestClass(File file, List files) + { + File = file; + Files = files; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets File + /// + [JsonPropertyName("file")] + public File File { get; set; } + + /// + /// Gets or Sets Files + /// + [JsonPropertyName("files")] + public List Files { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FileSchemaTestClass {\n"); + sb.Append(" File: ").Append(File).Append("\n"); + sb.Append(" Files: ").Append(Files).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FileSchemaTestClassJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + File? file = default; + List? files = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "file": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + file = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "files": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + files = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (file == null) + throw new ArgumentNullException(nameof(file), "Property is required for class FileSchemaTestClass."); + + if (files == null) + throw new ArgumentNullException(nameof(files), "Property is required for class FileSchemaTestClass."); + + return new FileSchemaTestClass(file, files); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FileSchemaTestClass fileSchemaTestClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, fileSchemaTestClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, FileSchemaTestClass fileSchemaTestClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("file"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.File, jsonSerializerOptions); + writer.WritePropertyName("files"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, jsonSerializerOptions); + } + } + + /// + /// The FileSchemaTestClassSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(FileSchemaTestClass))] + public partial class FileSchemaTestClassSerializationContext : JsonSerializerContext + { + /// + /// The FileSchemaTestClassSerializationContext + /// + /// + public FileSchemaTestClassSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// FileSchemaTestClassDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(FileSchemaTestClass))] + public partial class FileSchemaTestClassDeserializationContext : JsonSerializerContext + { + /// + /// FileSchemaTestClassDeserializationContext + /// + /// + public FileSchemaTestClassDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Foo.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Foo.cs new file mode 100644 index 00000000000..e03bcf0b739 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Foo.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Foo + /// + public partial class Foo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// bar (default to "bar") + [JsonConstructor] + public Foo(string bar = @"bar") + { + Bar = bar; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Bar + /// + [JsonPropertyName("bar")] + public string Bar { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Foo {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FooJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? bar = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "bar": + bar = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (bar == null) + throw new ArgumentNullException(nameof(bar), "Property is required for class Foo."); + + return new Foo(bar); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Foo foo, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, foo, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Foo foo, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("bar", foo.Bar); + } + } + + /// + /// The FooSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Foo))] + public partial class FooSerializationContext : JsonSerializerContext + { + /// + /// The FooSerializationContext + /// + /// + public FooSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// FooDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Foo))] + public partial class FooDeserializationContext : JsonSerializerContext + { + /// + /// FooDeserializationContext + /// + /// + public FooDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FooGetDefaultResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FooGetDefaultResponse.cs new file mode 100644 index 00000000000..7230cd7bd89 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FooGetDefaultResponse.cs @@ -0,0 +1,200 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// FooGetDefaultResponse + /// + public partial class FooGetDefaultResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// varString + [JsonConstructor] + public FooGetDefaultResponse(Foo varString) + { + VarString = varString; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets VarString + /// + [JsonPropertyName("string")] + public Foo VarString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FooGetDefaultResponse {\n"); + sb.Append(" VarString: ").Append(VarString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FooGetDefaultResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Foo? varString = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + varString = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (varString == null) + throw new ArgumentNullException(nameof(varString), "Property is required for class FooGetDefaultResponse."); + + return new FooGetDefaultResponse(varString); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FooGetDefaultResponse fooGetDefaultResponse, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, fooGetDefaultResponse, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, FooGetDefaultResponse fooGetDefaultResponse, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("string"); + JsonSerializer.Serialize(writer, fooGetDefaultResponse.VarString, jsonSerializerOptions); + } + } + + /// + /// The FooGetDefaultResponseSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(FooGetDefaultResponse))] + public partial class FooGetDefaultResponseSerializationContext : JsonSerializerContext + { + /// + /// The FooGetDefaultResponseSerializationContext + /// + /// + public FooGetDefaultResponseSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// FooGetDefaultResponseDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(FooGetDefaultResponse))] + public partial class FooGetDefaultResponseDeserializationContext : JsonSerializerContext + { + /// + /// FooGetDefaultResponseDeserializationContext + /// + /// + public FooGetDefaultResponseDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FormatTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FormatTest.cs new file mode 100644 index 00000000000..770808322b9 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FormatTest.cs @@ -0,0 +1,657 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// FormatTest + /// + public partial class FormatTest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// binary + /// varByte + /// date + /// dateTime + /// varDecimal + /// varDouble + /// varFloat + /// int32 + /// int64 + /// integer + /// number + /// password + /// None + /// A string that is a 10 digit number. Can have leading zeros. + /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + /// varString + /// unsignedInteger + /// unsignedLong + /// uuid + [JsonConstructor] + public FormatTest(System.IO.Stream binary, byte[] varByte, DateTime date, DateTime dateTime, decimal varDecimal, double varDouble, float varFloat, int int32, long int64, int integer, decimal number, string password, string patternWithBackslash, string patternWithDigits, string patternWithDigitsAndDelimiter, string varString, uint unsignedInteger, ulong unsignedLong, Guid uuid) + { + Binary = binary; + VarByte = varByte; + Date = date; + DateTime = dateTime; + VarDecimal = varDecimal; + VarDouble = varDouble; + VarFloat = varFloat; + Int32 = int32; + Int64 = int64; + Integer = integer; + Number = number; + Password = password; + PatternWithBackslash = patternWithBackslash; + PatternWithDigits = patternWithDigits; + PatternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + VarString = varString; + UnsignedInteger = unsignedInteger; + UnsignedLong = unsignedLong; + Uuid = uuid; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Binary + /// + [JsonPropertyName("binary")] + public System.IO.Stream Binary { get; set; } + + /// + /// Gets or Sets VarByte + /// + [JsonPropertyName("byte")] + public byte[] VarByte { get; set; } + + /// + /// Gets or Sets Date + /// + /// Sun Feb 02 00:00:00 UTC 2020 + [JsonPropertyName("date")] + public DateTime Date { get; set; } + + /// + /// Gets or Sets DateTime + /// + /// 2007-12-03T10:15:30+01:00 + [JsonPropertyName("dateTime")] + public DateTime DateTime { get; set; } + + /// + /// Gets or Sets VarDecimal + /// + [JsonPropertyName("decimal")] + public decimal VarDecimal { get; set; } + + /// + /// Gets or Sets VarDouble + /// + [JsonPropertyName("double")] + public double VarDouble { get; set; } + + /// + /// Gets or Sets VarFloat + /// + [JsonPropertyName("float")] + public float VarFloat { get; set; } + + /// + /// Gets or Sets Int32 + /// + [JsonPropertyName("int32")] + public int Int32 { get; set; } + + /// + /// Gets or Sets Int64 + /// + [JsonPropertyName("int64")] + public long Int64 { get; set; } + + /// + /// Gets or Sets Integer + /// + [JsonPropertyName("integer")] + public int Integer { get; set; } + + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public decimal Number { get; set; } + + /// + /// Gets or Sets Password + /// + [JsonPropertyName("password")] + public string Password { get; set; } + + /// + /// None + /// + /// None + [JsonPropertyName("pattern_with_backslash")] + public string PatternWithBackslash { get; set; } + + /// + /// A string that is a 10 digit number. Can have leading zeros. + /// + /// A string that is a 10 digit number. Can have leading zeros. + [JsonPropertyName("pattern_with_digits")] + public string PatternWithDigits { get; set; } + + /// + /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + /// + /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + [JsonPropertyName("pattern_with_digits_and_delimiter")] + public string PatternWithDigitsAndDelimiter { get; set; } + + /// + /// Gets or Sets VarString + /// + [JsonPropertyName("string")] + public string VarString { get; set; } + + /// + /// Gets or Sets UnsignedInteger + /// + [JsonPropertyName("unsigned_integer")] + public uint UnsignedInteger { get; set; } + + /// + /// Gets or Sets UnsignedLong + /// + [JsonPropertyName("unsigned_long")] + public ulong UnsignedLong { get; set; } + + /// + /// Gets or Sets Uuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("uuid")] + public Guid Uuid { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FormatTest {\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); + sb.Append(" VarByte: ").Append(VarByte).Append("\n"); + sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" VarDecimal: ").Append(VarDecimal).Append("\n"); + sb.Append(" VarDouble: ").Append(VarDouble).Append("\n"); + sb.Append(" VarFloat: ").Append(VarFloat).Append("\n"); + sb.Append(" Int32: ").Append(Int32).Append("\n"); + sb.Append(" Int64: ").Append(Int64).Append("\n"); + sb.Append(" Integer: ").Append(Integer).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" PatternWithBackslash: ").Append(PatternWithBackslash).Append("\n"); + sb.Append(" PatternWithDigits: ").Append(PatternWithDigits).Append("\n"); + sb.Append(" PatternWithDigitsAndDelimiter: ").Append(PatternWithDigitsAndDelimiter).Append("\n"); + sb.Append(" VarString: ").Append(VarString).Append("\n"); + sb.Append(" UnsignedInteger: ").Append(UnsignedInteger).Append("\n"); + sb.Append(" UnsignedLong: ").Append(UnsignedLong).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // VarDouble (double) maximum + if (this.VarDouble > (double)123.4) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarDouble, must be a value less than or equal to 123.4.", new [] { "VarDouble" }); + } + + // VarDouble (double) minimum + if (this.VarDouble < (double)67.8) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarDouble, must be a value greater than or equal to 67.8.", new [] { "VarDouble" }); + } + + // VarFloat (float) maximum + if (this.VarFloat > (float)987.6) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarFloat, must be a value less than or equal to 987.6.", new [] { "VarFloat" }); + } + + // VarFloat (float) minimum + if (this.VarFloat < (float)54.3) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarFloat, must be a value greater than or equal to 54.3.", new [] { "VarFloat" }); + } + + // Int32 (int) maximum + if (this.Int32 > (int)200) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); + } + + // Int32 (int) minimum + if (this.Int32 < (int)20) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); + } + + // Integer (int) maximum + if (this.Integer > (int)100) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); + } + + // Integer (int) minimum + if (this.Integer < (int)10) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); + } + + // Number (decimal) maximum + if (this.Number > (decimal)543.2) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); + } + + // Number (decimal) minimum + if (this.Number < (decimal)32.1) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); + } + + // Password (string) maxLength + if (this.Password != null && this.Password.Length > 64) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); + } + + // Password (string) minLength + if (this.Password != null && this.Password.Length < 10) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); + } + + if (this.PatternWithBackslash != null) { + // PatternWithBackslash (string) pattern + Regex regexPatternWithBackslash = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$", RegexOptions.CultureInvariant); + if (!regexPatternWithBackslash.Match(this.PatternWithBackslash).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithBackslash, must match a pattern of " + regexPatternWithBackslash, new [] { "PatternWithBackslash" }); + } + } + + if (this.PatternWithDigits != null) { + // PatternWithDigits (string) pattern + Regex regexPatternWithDigits = new Regex(@"^\d{10}$", RegexOptions.CultureInvariant); + if (!regexPatternWithDigits.Match(this.PatternWithDigits).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigits, must match a pattern of " + regexPatternWithDigits, new [] { "PatternWithDigits" }); + } + } + + if (this.PatternWithDigitsAndDelimiter != null) { + // PatternWithDigitsAndDelimiter (string) pattern + Regex regexPatternWithDigitsAndDelimiter = new Regex(@"^image_\d{1,3}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (!regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiter).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigitsAndDelimiter, must match a pattern of " + regexPatternWithDigitsAndDelimiter, new [] { "PatternWithDigitsAndDelimiter" }); + } + } + + if (this.VarString != null) { + // VarString (string) pattern + Regex regexVarString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (!regexVarString.Match(this.VarString).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarString, must match a pattern of " + regexVarString, new [] { "VarString" }); + } + } + + // UnsignedInteger (uint) maximum + if (this.UnsignedInteger > (uint)200) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UnsignedInteger, must be a value less than or equal to 200.", new [] { "UnsignedInteger" }); + } + + // UnsignedInteger (uint) minimum + if (this.UnsignedInteger < (uint)20) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UnsignedInteger, must be a value greater than or equal to 20.", new [] { "UnsignedInteger" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FormatTestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Date + /// + public static string DateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize DateTime + /// + public static string DateTimeFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + System.IO.Stream? binary = default; + byte[]? varByte = default; + DateTime? date = default; + DateTime? dateTime = default; + decimal? varDecimal = default; + double? varDouble = default; + float? varFloat = default; + int? int32 = default; + long? int64 = default; + int? integer = default; + decimal? number = default; + string? password = default; + string? patternWithBackslash = default; + string? patternWithDigits = default; + string? patternWithDigitsAndDelimiter = default; + string? varString = default; + uint? unsignedInteger = default; + ulong? unsignedLong = default; + Guid? uuid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "binary": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + binary = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "byte": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + varByte = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "date": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + date = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "dateTime": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + dateTime = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "decimal": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + varDecimal = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "double": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + varDouble = utf8JsonReader.GetDouble(); + break; + case "float": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + varFloat = (float)utf8JsonReader.GetDouble(); + break; + case "int32": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + int32 = utf8JsonReader.GetInt32(); + break; + case "int64": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + int64 = utf8JsonReader.GetInt64(); + break; + case "integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + integer = utf8JsonReader.GetInt32(); + break; + case "number": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + number = utf8JsonReader.GetDecimal(); + break; + case "password": + password = utf8JsonReader.GetString(); + break; + case "pattern_with_backslash": + patternWithBackslash = utf8JsonReader.GetString(); + break; + case "pattern_with_digits": + patternWithDigits = utf8JsonReader.GetString(); + break; + case "pattern_with_digits_and_delimiter": + patternWithDigitsAndDelimiter = utf8JsonReader.GetString(); + break; + case "string": + varString = utf8JsonReader.GetString(); + break; + case "unsigned_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + unsignedInteger = utf8JsonReader.GetUInt32(); + break; + case "unsigned_long": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + unsignedLong = utf8JsonReader.GetUInt64(); + break; + case "uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + uuid = utf8JsonReader.GetGuid(); + break; + default: + break; + } + } + } + + if (binary == null) + throw new ArgumentNullException(nameof(binary), "Property is required for class FormatTest."); + + if (varByte == null) + throw new ArgumentNullException(nameof(varByte), "Property is required for class FormatTest."); + + if (date == null) + throw new ArgumentNullException(nameof(date), "Property is required for class FormatTest."); + + if (dateTime == null) + throw new ArgumentNullException(nameof(dateTime), "Property is required for class FormatTest."); + + if (varDecimal == null) + throw new ArgumentNullException(nameof(varDecimal), "Property is required for class FormatTest."); + + if (varDouble == null) + throw new ArgumentNullException(nameof(varDouble), "Property is required for class FormatTest."); + + if (varFloat == null) + throw new ArgumentNullException(nameof(varFloat), "Property is required for class FormatTest."); + + if (int32 == null) + throw new ArgumentNullException(nameof(int32), "Property is required for class FormatTest."); + + if (int64 == null) + throw new ArgumentNullException(nameof(int64), "Property is required for class FormatTest."); + + if (integer == null) + throw new ArgumentNullException(nameof(integer), "Property is required for class FormatTest."); + + if (number == null) + throw new ArgumentNullException(nameof(number), "Property is required for class FormatTest."); + + if (password == null) + throw new ArgumentNullException(nameof(password), "Property is required for class FormatTest."); + + if (patternWithBackslash == null) + throw new ArgumentNullException(nameof(patternWithBackslash), "Property is required for class FormatTest."); + + if (patternWithDigits == null) + throw new ArgumentNullException(nameof(patternWithDigits), "Property is required for class FormatTest."); + + if (patternWithDigitsAndDelimiter == null) + throw new ArgumentNullException(nameof(patternWithDigitsAndDelimiter), "Property is required for class FormatTest."); + + if (varString == null) + throw new ArgumentNullException(nameof(varString), "Property is required for class FormatTest."); + + if (unsignedInteger == null) + throw new ArgumentNullException(nameof(unsignedInteger), "Property is required for class FormatTest."); + + if (unsignedLong == null) + throw new ArgumentNullException(nameof(unsignedLong), "Property is required for class FormatTest."); + + if (uuid == null) + throw new ArgumentNullException(nameof(uuid), "Property is required for class FormatTest."); + + return new FormatTest(binary, varByte, date.Value, dateTime.Value, varDecimal.Value, varDouble.Value, varFloat.Value, int32.Value, int64.Value, integer.Value, number.Value, password, patternWithBackslash, patternWithDigits, patternWithDigitsAndDelimiter, varString, unsignedInteger.Value, unsignedLong.Value, uuid.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FormatTest formatTest, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, formatTest, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, FormatTest formatTest, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("binary"); + JsonSerializer.Serialize(writer, formatTest.Binary, jsonSerializerOptions); + writer.WritePropertyName("byte"); + JsonSerializer.Serialize(writer, formatTest.VarByte, jsonSerializerOptions); + writer.WriteString("date", formatTest.Date.ToString(DateFormat)); + writer.WriteString("dateTime", formatTest.DateTime.ToString(DateTimeFormat)); + writer.WritePropertyName("decimal"); + JsonSerializer.Serialize(writer, formatTest.VarDecimal, jsonSerializerOptions); + writer.WriteNumber("double", formatTest.VarDouble); + writer.WriteNumber("float", formatTest.VarFloat); + writer.WriteNumber("int32", formatTest.Int32); + writer.WriteNumber("int64", formatTest.Int64); + writer.WriteNumber("integer", formatTest.Integer); + writer.WriteNumber("number", formatTest.Number); + writer.WriteString("password", formatTest.Password); + writer.WriteString("pattern_with_backslash", formatTest.PatternWithBackslash); + writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); + writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); + writer.WriteString("string", formatTest.VarString); + writer.WriteNumber("unsigned_integer", formatTest.UnsignedInteger); + writer.WriteNumber("unsigned_long", formatTest.UnsignedLong); + writer.WriteString("uuid", formatTest.Uuid); + } + } + + /// + /// The FormatTestSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(FormatTest))] + public partial class FormatTestSerializationContext : JsonSerializerContext + { + /// + /// The FormatTestSerializationContext + /// + /// + public FormatTestSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// FormatTestDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(FormatTest))] + public partial class FormatTestDeserializationContext : JsonSerializerContext + { + /// + /// FormatTestDeserializationContext + /// + /// + public FormatTestDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Fruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Fruit.cs new file mode 100644 index 00000000000..a810386beaf --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Fruit.cs @@ -0,0 +1,242 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Fruit + /// + public partial class Fruit : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// color + public Fruit(Apple apple, string color) + { + Apple = apple; + Color = color; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// color + public Fruit(Banana banana, string color) + { + Banana = banana; + Color = color; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Apple + /// + public Apple? Apple { get; set; } + + /// + /// Gets or Sets Banana + /// + public Banana? Banana { get; set; } + + /// + /// Gets or Sets Color + /// + [JsonPropertyName("color")] + public string Color { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Fruit {\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FruitJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? color = default; + + Apple? apple = default; + Banana? banana = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderApple = utf8JsonReader; + OpenAPIClientUtils.TryDeserialize(ref utf8JsonReaderApple, jsonSerializerOptions, out apple); + + Utf8JsonReader utf8JsonReaderBanana = utf8JsonReader; + OpenAPIClientUtils.TryDeserialize(ref utf8JsonReaderBanana, jsonSerializerOptions, out banana); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "color": + color = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (color == null) + throw new ArgumentNullException(nameof(color), "Property is required for class Fruit."); + + if (apple != null) + return new Fruit(apple, color); + + if (banana != null) + return new Fruit(banana, color); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, fruit, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("color", fruit.Color); + } + } + + /// + /// The FruitSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Fruit))] + public partial class FruitSerializationContext : JsonSerializerContext + { + /// + /// The FruitSerializationContext + /// + /// + public FruitSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// FruitDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Fruit))] + public partial class FruitDeserializationContext : JsonSerializerContext + { + /// + /// FruitDeserializationContext + /// + /// + public FruitDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FruitReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FruitReq.cs new file mode 100644 index 00000000000..0023f401421 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FruitReq.cs @@ -0,0 +1,223 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// FruitReq + /// + public partial class FruitReq : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public FruitReq(AppleReq appleReq) + { + AppleReq = appleReq; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public FruitReq(BananaReq bananaReq) + { + BananaReq = bananaReq; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets AppleReq + /// + public AppleReq? AppleReq { get; set; } + + /// + /// Gets or Sets BananaReq + /// + public BananaReq? BananaReq { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FruitReq {\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FruitReqJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override FruitReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + AppleReq? appleReq = default; + BananaReq? bananaReq = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderAppleReq = utf8JsonReader; + OpenAPIClientUtils.TryDeserialize(ref utf8JsonReaderAppleReq, jsonSerializerOptions, out appleReq); + + Utf8JsonReader utf8JsonReaderBananaReq = utf8JsonReader; + OpenAPIClientUtils.TryDeserialize(ref utf8JsonReaderBananaReq, jsonSerializerOptions, out bananaReq); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + default: + break; + } + } + } + + if (appleReq != null) + return new FruitReq(appleReq); + + if (bananaReq != null) + return new FruitReq(bananaReq); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FruitReq fruitReq, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, fruitReq, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, FruitReq fruitReq, JsonSerializerOptions jsonSerializerOptions) + { + + } + } + + /// + /// The FruitReqSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(FruitReq))] + public partial class FruitReqSerializationContext : JsonSerializerContext + { + /// + /// The FruitReqSerializationContext + /// + /// + public FruitReqSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// FruitReqDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(FruitReq))] + public partial class FruitReqDeserializationContext : JsonSerializerContext + { + /// + /// FruitReqDeserializationContext + /// + /// + public FruitReqDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GmFruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GmFruit.cs new file mode 100644 index 00000000000..39c587c1fb7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GmFruit.cs @@ -0,0 +1,238 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// GmFruit + /// + public partial class GmFruit : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// color + public GmFruit(Apple? apple, Banana? banana, string color) + { + Apple = apple; + Banana = banana; + Color = color; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Apple + /// + public Apple? Apple { get; set; } + + /// + /// Gets or Sets Banana + /// + public Banana? Banana { get; set; } + + /// + /// Gets or Sets Color + /// + [JsonPropertyName("color")] + public string Color { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GmFruit {\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GmFruitJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? color = default; + + Apple? apple = default; + Banana? banana = default; + + Utf8JsonReader utf8JsonReaderAnyOf = utf8JsonReader; + while (utf8JsonReaderAnyOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderAnyOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderAnyOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderAnyOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderAnyOf.CurrentDepth) + break; + + if (utf8JsonReaderAnyOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderAnyOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderApple = utf8JsonReader; + OpenAPIClientUtils.TryDeserialize(ref utf8JsonReaderApple, jsonSerializerOptions, out apple); + + Utf8JsonReader utf8JsonReaderBanana = utf8JsonReader; + OpenAPIClientUtils.TryDeserialize(ref utf8JsonReaderBanana, jsonSerializerOptions, out banana); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "color": + color = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (color == null) + throw new ArgumentNullException(nameof(color), "Property is required for class GmFruit."); + + return new GmFruit(apple, banana, color); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (gmFruit.Apple != null) + { + AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.Apple.GetType())); + AppleJsonConverter.WriteProperties(ref writer, gmFruit.Apple, jsonSerializerOptions); + } + + if (gmFruit.Banana != null) + { + BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.Banana.GetType())); + BananaJsonConverter.WriteProperties(ref writer, gmFruit.Banana, jsonSerializerOptions); + } + + WriteProperties(ref writer, gmFruit, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("color", gmFruit.Color); + } + } + + /// + /// The GmFruitSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(GmFruit))] + public partial class GmFruitSerializationContext : JsonSerializerContext + { + /// + /// The GmFruitSerializationContext + /// + /// + public GmFruitSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// GmFruitDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(GmFruit))] + public partial class GmFruitDeserializationContext : JsonSerializerContext + { + /// + /// GmFruitDeserializationContext + /// + /// + public GmFruitDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GrandparentAnimal.cs new file mode 100644 index 00000000000..b780f97321e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GrandparentAnimal.cs @@ -0,0 +1,208 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// GrandparentAnimal + /// + public partial class GrandparentAnimal : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// petType + [JsonConstructor] + public GrandparentAnimal(string petType) + { + PetType = petType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets PetType + /// + [JsonPropertyName("pet_type")] + public string PetType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GrandparentAnimal {\n"); + sb.Append(" PetType: ").Append(PetType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GrandparentAnimalJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? petType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "pet_type": + petType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (petType == null) + throw new ArgumentNullException(nameof(petType), "Property is required for class GrandparentAnimal."); + + return new GrandparentAnimal(petType); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GrandparentAnimal grandparentAnimal, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, grandparentAnimal, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, GrandparentAnimal grandparentAnimal, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("pet_type", grandparentAnimal.PetType); + } + } + + /// + /// The GrandparentAnimalSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(GrandparentAnimal))] + public partial class GrandparentAnimalSerializationContext : JsonSerializerContext + { + /// + /// The GrandparentAnimalSerializationContext + /// + /// + public GrandparentAnimalSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// GrandparentAnimalDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(GrandparentAnimal))] + public partial class GrandparentAnimalDeserializationContext : JsonSerializerContext + { + /// + /// GrandparentAnimalDeserializationContext + /// + /// + public GrandparentAnimalDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HasOnlyReadOnly.cs new file mode 100644 index 00000000000..2ab0e394c23 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HasOnlyReadOnly.cs @@ -0,0 +1,252 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// HasOnlyReadOnly + /// + public partial class HasOnlyReadOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// bar + /// foo + [JsonConstructor] + internal HasOnlyReadOnly(string bar, string foo) + { + Bar = bar; + Foo = foo; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Bar + /// + [JsonPropertyName("bar")] + public string Bar { get; } + + /// + /// Gets or Sets Foo + /// + [JsonPropertyName("foo")] + public string Foo { get; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HasOnlyReadOnly {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" Foo: ").Append(Foo).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object? input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as HasOnlyReadOnly).AreEqual; + } + + /// + /// Returns true if HasOnlyReadOnly instances are equal + /// + /// Instance of HasOnlyReadOnly to be compared + /// Boolean + public bool Equals(HasOnlyReadOnly? input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + Foo.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HasOnlyReadOnlyJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? bar = default; + string? foo = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "bar": + bar = utf8JsonReader.GetString(); + break; + case "foo": + foo = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (bar == null) + throw new ArgumentNullException(nameof(bar), "Property is required for class HasOnlyReadOnly."); + + if (foo == null) + throw new ArgumentNullException(nameof(foo), "Property is required for class HasOnlyReadOnly."); + + return new HasOnlyReadOnly(bar, foo); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnly, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, hasOnlyReadOnly, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnly, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("bar", hasOnlyReadOnly.Bar); + writer.WriteString("foo", hasOnlyReadOnly.Foo); + } + } + + /// + /// The HasOnlyReadOnlySerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(HasOnlyReadOnly))] + public partial class HasOnlyReadOnlySerializationContext : JsonSerializerContext + { + /// + /// The HasOnlyReadOnlySerializationContext + /// + /// + public HasOnlyReadOnlySerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// HasOnlyReadOnlyDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(HasOnlyReadOnly))] + public partial class HasOnlyReadOnlyDeserializationContext : JsonSerializerContext + { + /// + /// HasOnlyReadOnlyDeserializationContext + /// + /// + public HasOnlyReadOnlyDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HealthCheckResult.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HealthCheckResult.cs new file mode 100644 index 00000000000..7650da555ce --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HealthCheckResult.cs @@ -0,0 +1,195 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + /// + public partial class HealthCheckResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// nullableMessage + [JsonConstructor] + public HealthCheckResult(string? nullableMessage = default) + { + NullableMessage = nullableMessage; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets NullableMessage + /// + [JsonPropertyName("NullableMessage")] + public string? NullableMessage { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HealthCheckResult {\n"); + sb.Append(" NullableMessage: ").Append(NullableMessage).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HealthCheckResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override HealthCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? nullableMessage = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "NullableMessage": + nullableMessage = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + return new HealthCheckResult(nullableMessage); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HealthCheckResult healthCheckResult, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, healthCheckResult, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, HealthCheckResult healthCheckResult, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + } + } + + /// + /// The HealthCheckResultSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(HealthCheckResult))] + public partial class HealthCheckResultSerializationContext : JsonSerializerContext + { + /// + /// The HealthCheckResultSerializationContext + /// + /// + public HealthCheckResultSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// HealthCheckResultDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(HealthCheckResult))] + public partial class HealthCheckResultDeserializationContext : JsonSerializerContext + { + /// + /// HealthCheckResultDeserializationContext + /// + /// + public HealthCheckResultDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/IsoscelesTriangle.cs new file mode 100644 index 00000000000..7580d210523 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/IsoscelesTriangle.cs @@ -0,0 +1,208 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// IsoscelesTriangle + /// + public partial class IsoscelesTriangle : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// shapeType + /// triangleType + [JsonConstructor] + public IsoscelesTriangle(string shapeType, string triangleType) + { + ShapeType = shapeType; + TriangleType = triangleType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ShapeType + /// + [JsonPropertyName("shapeType")] + public string ShapeType { get; set; } + + /// + /// Gets or Sets TriangleType + /// + [JsonPropertyName("triangleType")] + public string TriangleType { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IsoscelesTriangle {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IsoscelesTriangleJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? shapeType = default; + string? triangleType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "shapeType": + shapeType = utf8JsonReader.GetString(); + break; + case "triangleType": + triangleType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (shapeType == null) + throw new ArgumentNullException(nameof(shapeType), "Property is required for class IsoscelesTriangle."); + + if (triangleType == null) + throw new ArgumentNullException(nameof(triangleType), "Property is required for class IsoscelesTriangle."); + + return new IsoscelesTriangle(shapeType, triangleType); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, isoscelesTriangle, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("shapeType", isoscelesTriangle.ShapeType); + writer.WriteString("triangleType", isoscelesTriangle.TriangleType); + } + } + + /// + /// The IsoscelesTriangleSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(IsoscelesTriangle))] + public partial class IsoscelesTriangleSerializationContext : JsonSerializerContext + { + /// + /// The IsoscelesTriangleSerializationContext + /// + /// + public IsoscelesTriangleSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// IsoscelesTriangleDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(IsoscelesTriangle))] + public partial class IsoscelesTriangleDeserializationContext : JsonSerializerContext + { + /// + /// IsoscelesTriangleDeserializationContext + /// + /// + public IsoscelesTriangleDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/List.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/List.cs new file mode 100644 index 00000000000..96853a9b8fc --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/List.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// List + /// + public partial class List : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// var123List + [JsonConstructor] + public List(string var123List) + { + Var123List = var123List; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Var123List + /// + [JsonPropertyName("123-list")] + public string Var123List { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class List {\n"); + sb.Append(" Var123List: ").Append(Var123List).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? var123List = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "123-list": + var123List = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (var123List == null) + throw new ArgumentNullException(nameof(var123List), "Property is required for class List."); + + return new List(var123List); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, List list, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, list, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, List list, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("123-list", list.Var123List); + } + } + + /// + /// The ListSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(List))] + public partial class ListSerializationContext : JsonSerializerContext + { + /// + /// The ListSerializationContext + /// + /// + public ListSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ListDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(List))] + public partial class ListDeserializationContext : JsonSerializerContext + { + /// + /// ListDeserializationContext + /// + /// + public ListDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/LiteralStringClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/LiteralStringClass.cs new file mode 100644 index 00000000000..19e6efb26eb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/LiteralStringClass.cs @@ -0,0 +1,215 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// LiteralStringClass + /// + public partial class LiteralStringClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// escapedLiteralString (default to "C:\\Users\\username") + /// unescapedLiteralString (default to "C:\Users\username") + [JsonConstructor] + public LiteralStringClass(string escapedLiteralString = @"C:\\Users\\username", string unescapedLiteralString = @"C:\Users\username") + { + EscapedLiteralString = escapedLiteralString; + UnescapedLiteralString = unescapedLiteralString; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets EscapedLiteralString + /// + [JsonPropertyName("escapedLiteralString")] + public string EscapedLiteralString { get; set; } + + /// + /// Gets or Sets UnescapedLiteralString + /// + [JsonPropertyName("unescapedLiteralString")] + public string UnescapedLiteralString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LiteralStringClass {\n"); + sb.Append(" EscapedLiteralString: ").Append(EscapedLiteralString).Append("\n"); + sb.Append(" UnescapedLiteralString: ").Append(UnescapedLiteralString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LiteralStringClassJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? escapedLiteralString = default; + string? unescapedLiteralString = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "escapedLiteralString": + escapedLiteralString = utf8JsonReader.GetString(); + break; + case "unescapedLiteralString": + unescapedLiteralString = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (escapedLiteralString == null) + throw new ArgumentNullException(nameof(escapedLiteralString), "Property is required for class LiteralStringClass."); + + if (unescapedLiteralString == null) + throw new ArgumentNullException(nameof(unescapedLiteralString), "Property is required for class LiteralStringClass."); + + return new LiteralStringClass(escapedLiteralString, unescapedLiteralString); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LiteralStringClass literalStringClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, literalStringClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, LiteralStringClass literalStringClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("escapedLiteralString", literalStringClass.EscapedLiteralString); + writer.WriteString("unescapedLiteralString", literalStringClass.UnescapedLiteralString); + } + } + + /// + /// The LiteralStringClassSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(LiteralStringClass))] + public partial class LiteralStringClassSerializationContext : JsonSerializerContext + { + /// + /// The LiteralStringClassSerializationContext + /// + /// + public LiteralStringClassSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// LiteralStringClassDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(LiteralStringClass))] + public partial class LiteralStringClassDeserializationContext : JsonSerializerContext + { + /// + /// LiteralStringClassDeserializationContext + /// + /// + public LiteralStringClassDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Mammal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Mammal.cs new file mode 100644 index 00000000000..7651c351b18 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Mammal.cs @@ -0,0 +1,311 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Mammal + /// + public partial class Mammal : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// className + public Mammal(Whale whale, string className) + { + Whale = whale; + ClassName = className; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// className + public Mammal(Zebra zebra, string className) + { + Zebra = zebra; + ClassName = className; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// className + public Mammal(Pig pig, string className) + { + Pig = pig; + ClassName = className; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Whale + /// + public Whale? Whale { get; set; } + + /// + /// Gets or Sets Zebra + /// + public Zebra? Zebra { get; set; } + + /// + /// Gets or Sets Pig + /// + public Pig? Pig { get; set; } + + /// + /// Gets or Sets ClassName + /// + [JsonPropertyName("className")] + public string ClassName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Mammal {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MammalJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? className = default; + + Pig? pig = null; + Whale? whale = null; + Zebra? zebra = null; + + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName?.Equals("className") ?? false) + { + string? discriminator = utf8JsonReaderDiscriminator.GetString(); + if (discriminator?.Equals("Pig") ?? false) + { + Utf8JsonReader utf8JsonReaderPig = utf8JsonReader; + pig = JsonSerializer.Deserialize(ref utf8JsonReaderPig, jsonSerializerOptions); + } + if (discriminator?.Equals("whale") ?? false) + { + Utf8JsonReader utf8JsonReaderWhale = utf8JsonReader; + whale = JsonSerializer.Deserialize(ref utf8JsonReaderWhale, jsonSerializerOptions); + } + if (discriminator?.Equals("zebra") ?? false) + { + Utf8JsonReader utf8JsonReaderZebra = utf8JsonReader; + zebra = JsonSerializer.Deserialize(ref utf8JsonReaderZebra, jsonSerializerOptions); + } + } + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "className": + className = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (className == null) + throw new ArgumentNullException(nameof(className), "Property is required for class Mammal."); + + if (pig != null) + return new Mammal(pig, className); + + if (whale != null) + return new Mammal(whale, className); + + if (zebra != null) + return new Mammal(zebra, className); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (mammal.Pig != null) { + PigJsonConverter pigJsonConverter = (PigJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(mammal.Pig.GetType())); + pigJsonConverter.WriteProperties(ref writer, mammal.Pig, jsonSerializerOptions); + } + + if (mammal.Whale != null) { + WhaleJsonConverter whaleJsonConverter = (WhaleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(mammal.Whale.GetType())); + whaleJsonConverter.WriteProperties(ref writer, mammal.Whale, jsonSerializerOptions); + } + + if (mammal.Zebra != null) { + ZebraJsonConverter zebraJsonConverter = (ZebraJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(mammal.Zebra.GetType())); + zebraJsonConverter.WriteProperties(ref writer, mammal.Zebra, jsonSerializerOptions); + } + + WriteProperties(ref writer, mammal, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("className", mammal.ClassName); + } + } + + /// + /// The MammalSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Mammal))] + public partial class MammalSerializationContext : JsonSerializerContext + { + /// + /// The MammalSerializationContext + /// + /// + public MammalSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// MammalDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Mammal))] + public partial class MammalDeserializationContext : JsonSerializerContext + { + /// + /// MammalDeserializationContext + /// + /// + public MammalDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MapTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MapTest.cs new file mode 100644 index 00000000000..f8565b5bf5f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MapTest.cs @@ -0,0 +1,323 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// MapTest + /// + public partial class MapTest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// directMap + /// indirectMap + /// mapMapOfString + /// mapOfEnumString + [JsonConstructor] + public MapTest(Dictionary directMap, Dictionary indirectMap, Dictionary> mapMapOfString, Dictionary mapOfEnumString) + { + DirectMap = directMap; + IndirectMap = indirectMap; + MapMapOfString = mapMapOfString; + MapOfEnumString = mapOfEnumString; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Defines Inner + /// + public enum InnerEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static InnerEnum InnerEnumFromString(string value) + { + if (value.Equals("UPPER")) + return InnerEnum.UPPER; + + if (value.Equals("lower")) + return InnerEnum.Lower; + + throw new NotImplementedException($"Could not convert value to type InnerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static InnerEnum? InnerEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return InnerEnum.UPPER; + + if (value.Equals("lower")) + return InnerEnum.Lower; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string InnerEnumToJsonValue(InnerEnum value) + { + if (value == InnerEnum.UPPER) + return "UPPER"; + + if (value == InnerEnum.Lower) + return "lower"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets DirectMap + /// + [JsonPropertyName("direct_map")] + public Dictionary DirectMap { get; set; } + + /// + /// Gets or Sets IndirectMap + /// + [JsonPropertyName("indirect_map")] + public Dictionary IndirectMap { get; set; } + + /// + /// Gets or Sets MapMapOfString + /// + [JsonPropertyName("map_map_of_string")] + public Dictionary> MapMapOfString { get; set; } + + /// + /// Gets or Sets MapOfEnumString + /// + [JsonPropertyName("map_of_enum_string")] + public Dictionary MapOfEnumString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MapTest {\n"); + sb.Append(" DirectMap: ").Append(DirectMap).Append("\n"); + sb.Append(" IndirectMap: ").Append(IndirectMap).Append("\n"); + sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); + sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MapTestJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Dictionary? directMap = default; + Dictionary? indirectMap = default; + Dictionary>? mapMapOfString = default; + Dictionary? mapOfEnumString = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "direct_map": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + directMap = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "indirect_map": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + indirectMap = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "map_map_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + mapMapOfString = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "map_of_enum_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + mapOfEnumString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (directMap == null) + throw new ArgumentNullException(nameof(directMap), "Property is required for class MapTest."); + + if (indirectMap == null) + throw new ArgumentNullException(nameof(indirectMap), "Property is required for class MapTest."); + + if (mapMapOfString == null) + throw new ArgumentNullException(nameof(mapMapOfString), "Property is required for class MapTest."); + + if (mapOfEnumString == null) + throw new ArgumentNullException(nameof(mapOfEnumString), "Property is required for class MapTest."); + + return new MapTest(directMap, indirectMap, mapMapOfString, mapOfEnumString); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MapTest mapTest, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, mapTest, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, MapTest mapTest, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("direct_map"); + JsonSerializer.Serialize(writer, mapTest.DirectMap, jsonSerializerOptions); + writer.WritePropertyName("indirect_map"); + JsonSerializer.Serialize(writer, mapTest.IndirectMap, jsonSerializerOptions); + writer.WritePropertyName("map_map_of_string"); + JsonSerializer.Serialize(writer, mapTest.MapMapOfString, jsonSerializerOptions); + writer.WritePropertyName("map_of_enum_string"); + JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, jsonSerializerOptions); + } + } + + /// + /// The MapTestSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(MapTest))] + public partial class MapTestSerializationContext : JsonSerializerContext + { + /// + /// The MapTestSerializationContext + /// + /// + public MapTestSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// MapTestDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(MapTest))] + public partial class MapTestDeserializationContext : JsonSerializerContext + { + /// + /// MapTestDeserializationContext + /// + /// + public MapTestDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MixedPropertiesAndAdditionalPropertiesClass.cs new file mode 100644 index 00000000000..96d886719f4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -0,0 +1,265 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// MixedPropertiesAndAdditionalPropertiesClass + /// + public partial class MixedPropertiesAndAdditionalPropertiesClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// dateTime + /// map + /// uuid + /// uuidWithPattern + [JsonConstructor] + public MixedPropertiesAndAdditionalPropertiesClass(DateTime dateTime, Dictionary map, Guid uuid, Guid uuidWithPattern) + { + DateTime = dateTime; + Map = map; + Uuid = uuid; + UuidWithPattern = uuidWithPattern; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets DateTime + /// + [JsonPropertyName("dateTime")] + public DateTime DateTime { get; set; } + + /// + /// Gets or Sets Map + /// + [JsonPropertyName("map")] + public Dictionary Map { get; set; } + + /// + /// Gets or Sets Uuid + /// + [JsonPropertyName("uuid")] + public Guid Uuid { get; set; } + + /// + /// Gets or Sets UuidWithPattern + /// + [JsonPropertyName("uuid_with_pattern")] + public Guid UuidWithPattern { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" Map: ").Append(Map).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" UuidWithPattern: ").Append(UuidWithPattern).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // UuidWithPattern (Guid) pattern + Regex regexUuidWithPattern = new Regex(@"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", RegexOptions.CultureInvariant); + if (!regexUuidWithPattern.Match(this.UuidWithPattern.ToString()).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UuidWithPattern, must match a pattern of " + regexUuidWithPattern, new [] { "UuidWithPattern" }); + } + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MixedPropertiesAndAdditionalPropertiesClassJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateTime + /// + public static string DateTimeFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + DateTime? dateTime = default; + Dictionary? map = default; + Guid? uuid = default; + Guid? uuidWithPattern = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "dateTime": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + dateTime = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "map": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + map = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + uuid = utf8JsonReader.GetGuid(); + break; + case "uuid_with_pattern": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + uuidWithPattern = utf8JsonReader.GetGuid(); + break; + default: + break; + } + } + } + + if (dateTime == null) + throw new ArgumentNullException(nameof(dateTime), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + + if (map == null) + throw new ArgumentNullException(nameof(map), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + + if (uuid == null) + throw new ArgumentNullException(nameof(uuid), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + + if (uuidWithPattern == null) + throw new ArgumentNullException(nameof(uuidWithPattern), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + + return new MixedPropertiesAndAdditionalPropertiesClass(dateTime.Value, map, uuid.Value, uuidWithPattern.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, mixedPropertiesAndAdditionalPropertiesClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("dateTime", mixedPropertiesAndAdditionalPropertiesClass.DateTime.ToString(DateTimeFormat)); + writer.WritePropertyName("map"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, jsonSerializerOptions); + writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.Uuid); + writer.WriteString("uuid_with_pattern", mixedPropertiesAndAdditionalPropertiesClass.UuidWithPattern); + } + } + + /// + /// The MixedPropertiesAndAdditionalPropertiesClassSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(MixedPropertiesAndAdditionalPropertiesClass))] + public partial class MixedPropertiesAndAdditionalPropertiesClassSerializationContext : JsonSerializerContext + { + /// + /// The MixedPropertiesAndAdditionalPropertiesClassSerializationContext + /// + /// + public MixedPropertiesAndAdditionalPropertiesClassSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// MixedPropertiesAndAdditionalPropertiesClassDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(MixedPropertiesAndAdditionalPropertiesClass))] + public partial class MixedPropertiesAndAdditionalPropertiesClassDeserializationContext : JsonSerializerContext + { + /// + /// MixedPropertiesAndAdditionalPropertiesClassDeserializationContext + /// + /// + public MixedPropertiesAndAdditionalPropertiesClassDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Model200Response.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Model200Response.cs new file mode 100644 index 00000000000..ccda51e8dd9 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Model200Response.cs @@ -0,0 +1,216 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Model for testing model name starting with number + /// + public partial class Model200Response : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// varClass + /// name + [JsonConstructor] + public Model200Response(string varClass, int name) + { + VarClass = varClass; + Name = name; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets VarClass + /// + [JsonPropertyName("class")] + public string VarClass { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public int Name { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Model200Response {\n"); + sb.Append(" VarClass: ").Append(VarClass).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class Model200ResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? varClass = default; + int? name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "class": + varClass = utf8JsonReader.GetString(); + break; + case "name": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + name = utf8JsonReader.GetInt32(); + break; + default: + break; + } + } + } + + if (varClass == null) + throw new ArgumentNullException(nameof(varClass), "Property is required for class Model200Response."); + + if (name == null) + throw new ArgumentNullException(nameof(name), "Property is required for class Model200Response."); + + return new Model200Response(varClass, name.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Model200Response model200Response, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, model200Response, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Model200Response model200Response, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("class", model200Response.VarClass); + writer.WriteNumber("name", model200Response.Name); + } + } + + /// + /// The Model200ResponseSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Model200Response))] + public partial class Model200ResponseSerializationContext : JsonSerializerContext + { + /// + /// The Model200ResponseSerializationContext + /// + /// + public Model200ResponseSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// Model200ResponseDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Model200Response))] + public partial class Model200ResponseDeserializationContext : JsonSerializerContext + { + /// + /// Model200ResponseDeserializationContext + /// + /// + public Model200ResponseDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ModelClient.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ModelClient.cs new file mode 100644 index 00000000000..07f7e3f307f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ModelClient.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ModelClient + /// + public partial class ModelClient : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// varClient + [JsonConstructor] + public ModelClient(string varClient) + { + VarClient = varClient; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets VarClient + /// + [JsonPropertyName("client")] + public string VarClient { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ModelClient {\n"); + sb.Append(" VarClient: ").Append(VarClient).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ModelClientJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? varClient = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "client": + varClient = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (varClient == null) + throw new ArgumentNullException(nameof(varClient), "Property is required for class ModelClient."); + + return new ModelClient(varClient); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ModelClient modelClient, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, modelClient, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ModelClient modelClient, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("client", modelClient.VarClient); + } + } + + /// + /// The ModelClientSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ModelClient))] + public partial class ModelClientSerializationContext : JsonSerializerContext + { + /// + /// The ModelClientSerializationContext + /// + /// + public ModelClientSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ModelClientDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ModelClient))] + public partial class ModelClientDeserializationContext : JsonSerializerContext + { + /// + /// ModelClientDeserializationContext + /// + /// + public ModelClientDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Name.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Name.cs new file mode 100644 index 00000000000..dba77209142 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Name.cs @@ -0,0 +1,289 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Model for testing model name same as property name + /// + public partial class Name : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// varName + /// property + /// snakeCase + /// var123Number + [JsonConstructor] + public Name(int varName, string property, int snakeCase, int var123Number) + { + VarName = varName; + Property = property; + SnakeCase = snakeCase; + Var123Number = var123Number; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets VarName + /// + [JsonPropertyName("name")] + public int VarName { get; set; } + + /// + /// Gets or Sets Property + /// + [JsonPropertyName("property")] + public string Property { get; set; } + + /// + /// Gets or Sets SnakeCase + /// + [JsonPropertyName("snake_case")] + public int SnakeCase { get; } + + /// + /// Gets or Sets Var123Number + /// + [JsonPropertyName("123Number")] + public int Var123Number { get; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" VarName: ").Append(VarName).Append("\n"); + sb.Append(" Property: ").Append(Property).Append("\n"); + sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); + sb.Append(" Var123Number: ").Append(Var123Number).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object? input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Name).AreEqual; + } + + /// + /// Returns true if Name instances are equal + /// + /// Instance of Name to be compared + /// Boolean + public bool Equals(Name? input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); + hashCode = (hashCode * 59) + Var123Number.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + int? varName = default; + string? property = default; + int? snakeCase = default; + int? var123Number = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + varName = utf8JsonReader.GetInt32(); + break; + case "property": + property = utf8JsonReader.GetString(); + break; + case "snake_case": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + snakeCase = utf8JsonReader.GetInt32(); + break; + case "123Number": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + var123Number = utf8JsonReader.GetInt32(); + break; + default: + break; + } + } + } + + if (varName == null) + throw new ArgumentNullException(nameof(varName), "Property is required for class Name."); + + if (property == null) + throw new ArgumentNullException(nameof(property), "Property is required for class Name."); + + if (snakeCase == null) + throw new ArgumentNullException(nameof(snakeCase), "Property is required for class Name."); + + if (var123Number == null) + throw new ArgumentNullException(nameof(var123Number), "Property is required for class Name."); + + return new Name(varName.Value, property, snakeCase.Value, var123Number.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, name, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("name", name.VarName); + writer.WriteString("property", name.Property); + writer.WriteNumber("snake_case", name.SnakeCase); + writer.WriteNumber("123Number", name.Var123Number); + } + } + + /// + /// The NameSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Name))] + public partial class NameSerializationContext : JsonSerializerContext + { + /// + /// The NameSerializationContext + /// + /// + public NameSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// NameDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Name))] + public partial class NameDeserializationContext : JsonSerializerContext + { + /// + /// NameDeserializationContext + /// + /// + public NameDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NotificationtestGetElementsV1ResponseMPayload.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NotificationtestGetElementsV1ResponseMPayload.cs new file mode 100644 index 00000000000..5168d24402e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NotificationtestGetElementsV1ResponseMPayload.cs @@ -0,0 +1,218 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// NotificationtestGetElementsV1ResponseMPayload + /// + public partial class NotificationtestGetElementsV1ResponseMPayload : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// aObjVariableobject + /// pkiNotificationtestID + [JsonConstructor] + public NotificationtestGetElementsV1ResponseMPayload(List> aObjVariableobject, int pkiNotificationtestID) + { + AObjVariableobject = aObjVariableobject; + PkiNotificationtestID = pkiNotificationtestID; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets AObjVariableobject + /// + [JsonPropertyName("a_objVariableobject")] + public List> AObjVariableobject { get; set; } + + /// + /// Gets or Sets PkiNotificationtestID + /// + [JsonPropertyName("pkiNotificationtestID")] + public int PkiNotificationtestID { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NotificationtestGetElementsV1ResponseMPayload {\n"); + sb.Append(" AObjVariableobject: ").Append(AObjVariableobject).Append("\n"); + sb.Append(" PkiNotificationtestID: ").Append(PkiNotificationtestID).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NotificationtestGetElementsV1ResponseMPayloadJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + List>? aObjVariableobject = default; + int? pkiNotificationtestID = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "a_objVariableobject": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + aObjVariableobject = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "pkiNotificationtestID": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + pkiNotificationtestID = utf8JsonReader.GetInt32(); + break; + default: + break; + } + } + } + + if (aObjVariableobject == null) + throw new ArgumentNullException(nameof(aObjVariableobject), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + + if (pkiNotificationtestID == null) + throw new ArgumentNullException(nameof(pkiNotificationtestID), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + + return new NotificationtestGetElementsV1ResponseMPayload(aObjVariableobject, pkiNotificationtestID.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NotificationtestGetElementsV1ResponseMPayload notificationtestGetElementsV1ResponseMPayload, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, notificationtestGetElementsV1ResponseMPayload, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, NotificationtestGetElementsV1ResponseMPayload notificationtestGetElementsV1ResponseMPayload, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("a_objVariableobject"); + JsonSerializer.Serialize(writer, notificationtestGetElementsV1ResponseMPayload.AObjVariableobject, jsonSerializerOptions); + writer.WriteNumber("pkiNotificationtestID", notificationtestGetElementsV1ResponseMPayload.PkiNotificationtestID); + } + } + + /// + /// The NotificationtestGetElementsV1ResponseMPayloadSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(NotificationtestGetElementsV1ResponseMPayload))] + public partial class NotificationtestGetElementsV1ResponseMPayloadSerializationContext : JsonSerializerContext + { + /// + /// The NotificationtestGetElementsV1ResponseMPayloadSerializationContext + /// + /// + public NotificationtestGetElementsV1ResponseMPayloadSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// NotificationtestGetElementsV1ResponseMPayloadDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(NotificationtestGetElementsV1ResponseMPayload))] + public partial class NotificationtestGetElementsV1ResponseMPayloadDeserializationContext : JsonSerializerContext + { + /// + /// NotificationtestGetElementsV1ResponseMPayloadDeserializationContext + /// + /// + public NotificationtestGetElementsV1ResponseMPayloadDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableClass.cs new file mode 100644 index 00000000000..d91c6c812b1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableClass.cs @@ -0,0 +1,414 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// NullableClass + /// + public partial class NullableClass : Dictionary, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayItemsNullable + /// objectItemsNullable + /// arrayAndItemsNullableProp + /// arrayNullableProp + /// booleanProp + /// dateProp + /// datetimeProp + /// integerProp + /// numberProp + /// objectAndItemsNullableProp + /// objectNullableProp + /// stringProp + [JsonConstructor] + public NullableClass(List arrayItemsNullable, Dictionary objectItemsNullable, List? arrayAndItemsNullableProp = default, List? arrayNullableProp = default, bool? booleanProp = default, DateTime? dateProp = default, DateTime? datetimeProp = default, int? integerProp = default, decimal? numberProp = default, Dictionary? objectAndItemsNullableProp = default, Dictionary? objectNullableProp = default, string? stringProp = default) : base() + { + ArrayItemsNullable = arrayItemsNullable; + ObjectItemsNullable = objectItemsNullable; + ArrayAndItemsNullableProp = arrayAndItemsNullableProp; + ArrayNullableProp = arrayNullableProp; + BooleanProp = booleanProp; + DateProp = dateProp; + DatetimeProp = datetimeProp; + IntegerProp = integerProp; + NumberProp = numberProp; + ObjectAndItemsNullableProp = objectAndItemsNullableProp; + ObjectNullableProp = objectNullableProp; + StringProp = stringProp; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ArrayItemsNullable + /// + [JsonPropertyName("array_items_nullable")] + public List ArrayItemsNullable { get; set; } + + /// + /// Gets or Sets ObjectItemsNullable + /// + [JsonPropertyName("object_items_nullable")] + public Dictionary ObjectItemsNullable { get; set; } + + /// + /// Gets or Sets ArrayAndItemsNullableProp + /// + [JsonPropertyName("array_and_items_nullable_prop")] + public List? ArrayAndItemsNullableProp { get; set; } + + /// + /// Gets or Sets ArrayNullableProp + /// + [JsonPropertyName("array_nullable_prop")] + public List? ArrayNullableProp { get; set; } + + /// + /// Gets or Sets BooleanProp + /// + [JsonPropertyName("boolean_prop")] + public bool? BooleanProp { get; set; } + + /// + /// Gets or Sets DateProp + /// + [JsonPropertyName("date_prop")] + public DateTime? DateProp { get; set; } + + /// + /// Gets or Sets DatetimeProp + /// + [JsonPropertyName("datetime_prop")] + public DateTime? DatetimeProp { get; set; } + + /// + /// Gets or Sets IntegerProp + /// + [JsonPropertyName("integer_prop")] + public int? IntegerProp { get; set; } + + /// + /// Gets or Sets NumberProp + /// + [JsonPropertyName("number_prop")] + public decimal? NumberProp { get; set; } + + /// + /// Gets or Sets ObjectAndItemsNullableProp + /// + [JsonPropertyName("object_and_items_nullable_prop")] + public Dictionary? ObjectAndItemsNullableProp { get; set; } + + /// + /// Gets or Sets ObjectNullableProp + /// + [JsonPropertyName("object_nullable_prop")] + public Dictionary? ObjectNullableProp { get; set; } + + /// + /// Gets or Sets StringProp + /// + [JsonPropertyName("string_prop")] + public string? StringProp { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NullableClass {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); + sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" ArrayAndItemsNullableProp: ").Append(ArrayAndItemsNullableProp).Append("\n"); + sb.Append(" ArrayNullableProp: ").Append(ArrayNullableProp).Append("\n"); + sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); + sb.Append(" DateProp: ").Append(DateProp).Append("\n"); + sb.Append(" DatetimeProp: ").Append(DatetimeProp).Append("\n"); + sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); + sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); + sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); + sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); + sb.Append(" StringProp: ").Append(StringProp).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NullableClassJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateProp + /// + public static string DatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize DatetimeProp + /// + public static string DatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + List? arrayItemsNullable = default; + Dictionary? objectItemsNullable = default; + List? arrayAndItemsNullableProp = default; + List? arrayNullableProp = default; + bool? booleanProp = default; + DateTime? dateProp = default; + DateTime? datetimeProp = default; + int? integerProp = default; + decimal? numberProp = default; + Dictionary? objectAndItemsNullableProp = default; + Dictionary? objectNullableProp = default; + string? stringProp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "array_items_nullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + arrayItemsNullable = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "object_items_nullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectItemsNullable = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "array_and_items_nullable_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + arrayAndItemsNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "array_nullable_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + arrayNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + booleanProp = utf8JsonReader.GetBoolean(); + break; + case "date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + dateProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + datetimeProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "integer_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + integerProp = utf8JsonReader.GetInt32(); + break; + case "number_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + numberProp = utf8JsonReader.GetDecimal(); + break; + case "object_and_items_nullable_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectAndItemsNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "object_nullable_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "string_prop": + stringProp = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (arrayItemsNullable == null) + throw new ArgumentNullException(nameof(arrayItemsNullable), "Property is required for class NullableClass."); + + if (objectItemsNullable == null) + throw new ArgumentNullException(nameof(objectItemsNullable), "Property is required for class NullableClass."); + + return new NullableClass(arrayItemsNullable, objectItemsNullable, arrayAndItemsNullableProp, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectNullableProp, stringProp); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NullableClass nullableClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, nullableClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, NullableClass nullableClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("array_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, jsonSerializerOptions); + writer.WritePropertyName("object_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, jsonSerializerOptions); + writer.WritePropertyName("array_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, jsonSerializerOptions); + writer.WritePropertyName("array_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, jsonSerializerOptions); + + if (nullableClass.BooleanProp != null) + writer.WriteBoolean("boolean_prop", nullableClass.BooleanProp.Value); + else + writer.WriteNull("boolean_prop"); + + if (nullableClass.DateProp != null) + writer.WriteString("date_prop", nullableClass.DateProp.Value.ToString(DatePropFormat)); + else + writer.WriteNull("date_prop"); + + if (nullableClass.DatetimeProp != null) + writer.WriteString("datetime_prop", nullableClass.DatetimeProp.Value.ToString(DatetimePropFormat)); + else + writer.WriteNull("datetime_prop"); + + if (nullableClass.IntegerProp != null) + writer.WriteNumber("integer_prop", nullableClass.IntegerProp.Value); + else + writer.WriteNull("integer_prop"); + + if (nullableClass.NumberProp != null) + writer.WriteNumber("number_prop", nullableClass.NumberProp.Value); + else + writer.WriteNull("number_prop"); + + writer.WritePropertyName("object_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, jsonSerializerOptions); + writer.WritePropertyName("object_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, jsonSerializerOptions); + writer.WriteString("string_prop", nullableClass.StringProp); + } + } + + /// + /// The NullableClassSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(NullableClass))] + public partial class NullableClassSerializationContext : JsonSerializerContext + { + /// + /// The NullableClassSerializationContext + /// + /// + public NullableClassSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// NullableClassDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(NullableClass))] + public partial class NullableClassDeserializationContext : JsonSerializerContext + { + /// + /// NullableClassDeserializationContext + /// + /// + public NullableClassDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableGuidClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableGuidClass.cs new file mode 100644 index 00000000000..fd0d03663ad --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableGuidClass.cs @@ -0,0 +1,201 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// NullableGuidClass + /// + public partial class NullableGuidClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// uuid + [JsonConstructor] + public NullableGuidClass(Guid? uuid = default) + { + Uuid = uuid; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Uuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("uuid")] + public Guid? Uuid { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NullableGuidClass {\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NullableGuidClassJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override NullableGuidClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Guid? uuid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + uuid = utf8JsonReader.GetGuid(); + break; + default: + break; + } + } + } + + return new NullableGuidClass(uuid); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NullableGuidClass nullableGuidClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, nullableGuidClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, NullableGuidClass nullableGuidClass, JsonSerializerOptions jsonSerializerOptions) + { + + if (nullableGuidClass.Uuid == null) + writer.WriteNull("uuid"); + else + writer.WriteString("uuid", nullableGuidClass.Uuid.Value); + } + } + + /// + /// The NullableGuidClassSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(NullableGuidClass))] + public partial class NullableGuidClassSerializationContext : JsonSerializerContext + { + /// + /// The NullableGuidClassSerializationContext + /// + /// + public NullableGuidClassSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// NullableGuidClassDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(NullableGuidClass))] + public partial class NullableGuidClassDeserializationContext : JsonSerializerContext + { + /// + /// NullableGuidClassDeserializationContext + /// + /// + public NullableGuidClassDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableShape.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableShape.cs new file mode 100644 index 00000000000..b5fc16fb269 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableShape.cs @@ -0,0 +1,280 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// The value may be a shape or the 'null' value. The 'nullable' attribute was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema >= 3.1. + /// + public partial class NullableShape : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// shapeType + public NullableShape(Triangle triangle, string shapeType) + { + Triangle = triangle; + ShapeType = shapeType; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// shapeType + public NullableShape(Quadrilateral quadrilateral, string shapeType) + { + Quadrilateral = quadrilateral; + ShapeType = shapeType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Triangle + /// + public Triangle? Triangle { get; set; } + + /// + /// Gets or Sets Quadrilateral + /// + public Quadrilateral? Quadrilateral { get; set; } + + /// + /// Gets or Sets ShapeType + /// + [JsonPropertyName("shapeType")] + public string ShapeType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NullableShape {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NullableShapeJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? shapeType = default; + + Quadrilateral? quadrilateral = null; + Triangle? triangle = null; + + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName?.Equals("shapeType") ?? false) + { + string? discriminator = utf8JsonReaderDiscriminator.GetString(); + if (discriminator?.Equals("Quadrilateral") ?? false) + { + Utf8JsonReader utf8JsonReaderQuadrilateral = utf8JsonReader; + quadrilateral = JsonSerializer.Deserialize(ref utf8JsonReaderQuadrilateral, jsonSerializerOptions); + } + if (discriminator?.Equals("Triangle") ?? false) + { + Utf8JsonReader utf8JsonReaderTriangle = utf8JsonReader; + triangle = JsonSerializer.Deserialize(ref utf8JsonReaderTriangle, jsonSerializerOptions); + } + } + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "shapeType": + shapeType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (shapeType == null) + throw new ArgumentNullException(nameof(shapeType), "Property is required for class NullableShape."); + + if (quadrilateral != null) + return new NullableShape(quadrilateral, shapeType); + + if (triangle != null) + return new NullableShape(triangle, shapeType); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (nullableShape.Quadrilateral != null) { + QuadrilateralJsonConverter quadrilateralJsonConverter = (QuadrilateralJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(nullableShape.Quadrilateral.GetType())); + quadrilateralJsonConverter.WriteProperties(ref writer, nullableShape.Quadrilateral, jsonSerializerOptions); + } + + if (nullableShape.Triangle != null) { + TriangleJsonConverter triangleJsonConverter = (TriangleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(nullableShape.Triangle.GetType())); + triangleJsonConverter.WriteProperties(ref writer, nullableShape.Triangle, jsonSerializerOptions); + } + + WriteProperties(ref writer, nullableShape, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("shapeType", nullableShape.ShapeType); + } + } + + /// + /// The NullableShapeSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(NullableShape))] + public partial class NullableShapeSerializationContext : JsonSerializerContext + { + /// + /// The NullableShapeSerializationContext + /// + /// + public NullableShapeSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// NullableShapeDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(NullableShape))] + public partial class NullableShapeDeserializationContext : JsonSerializerContext + { + /// + /// NullableShapeDeserializationContext + /// + /// + public NullableShapeDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NumberOnly.cs new file mode 100644 index 00000000000..06be98cd53c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NumberOnly.cs @@ -0,0 +1,199 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// NumberOnly + /// + public partial class NumberOnly : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// justNumber + [JsonConstructor] + public NumberOnly(decimal justNumber) + { + JustNumber = justNumber; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets JustNumber + /// + [JsonPropertyName("JustNumber")] + public decimal JustNumber { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NumberOnly {\n"); + sb.Append(" JustNumber: ").Append(JustNumber).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NumberOnlyJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + decimal? justNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "JustNumber": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + justNumber = utf8JsonReader.GetDecimal(); + break; + default: + break; + } + } + } + + if (justNumber == null) + throw new ArgumentNullException(nameof(justNumber), "Property is required for class NumberOnly."); + + return new NumberOnly(justNumber.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NumberOnly numberOnly, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, numberOnly, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, NumberOnly numberOnly, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("JustNumber", numberOnly.JustNumber); + } + } + + /// + /// The NumberOnlySerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(NumberOnly))] + public partial class NumberOnlySerializationContext : JsonSerializerContext + { + /// + /// The NumberOnlySerializationContext + /// + /// + public NumberOnlySerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// NumberOnlyDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(NumberOnly))] + public partial class NumberOnlyDeserializationContext : JsonSerializerContext + { + /// + /// NumberOnlyDeserializationContext + /// + /// + public NumberOnlyDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ObjectWithDeprecatedFields.cs new file mode 100644 index 00000000000..d39c47a5f43 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ObjectWithDeprecatedFields.cs @@ -0,0 +1,257 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ObjectWithDeprecatedFields + /// + public partial class ObjectWithDeprecatedFields : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// bars + /// deprecatedRef + /// id + /// uuid + [JsonConstructor] + public ObjectWithDeprecatedFields(List bars, DeprecatedObject deprecatedRef, decimal id, string uuid) + { + Bars = bars; + DeprecatedRef = deprecatedRef; + Id = id; + Uuid = uuid; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Bars + /// + [JsonPropertyName("bars")] + [Obsolete] + public List Bars { get; set; } + + /// + /// Gets or Sets DeprecatedRef + /// + [JsonPropertyName("deprecatedRef")] + [Obsolete] + public DeprecatedObject DeprecatedRef { get; set; } + + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + [Obsolete] + public decimal Id { get; set; } + + /// + /// Gets or Sets Uuid + /// + [JsonPropertyName("uuid")] + public string Uuid { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ObjectWithDeprecatedFields {\n"); + sb.Append(" Bars: ").Append(Bars).Append("\n"); + sb.Append(" DeprecatedRef: ").Append(DeprecatedRef).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ObjectWithDeprecatedFieldsJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + List? bars = default; + DeprecatedObject? deprecatedRef = default; + decimal? id = default; + string? uuid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "bars": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + bars = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "deprecatedRef": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + deprecatedRef = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "id": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + id = utf8JsonReader.GetDecimal(); + break; + case "uuid": + uuid = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (bars == null) + throw new ArgumentNullException(nameof(bars), "Property is required for class ObjectWithDeprecatedFields."); + + if (deprecatedRef == null) + throw new ArgumentNullException(nameof(deprecatedRef), "Property is required for class ObjectWithDeprecatedFields."); + + if (id == null) + throw new ArgumentNullException(nameof(id), "Property is required for class ObjectWithDeprecatedFields."); + + if (uuid == null) + throw new ArgumentNullException(nameof(uuid), "Property is required for class ObjectWithDeprecatedFields."); + + return new ObjectWithDeprecatedFields(bars, deprecatedRef, id.Value, uuid); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ObjectWithDeprecatedFields objectWithDeprecatedFields, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, objectWithDeprecatedFields, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ObjectWithDeprecatedFields objectWithDeprecatedFields, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("bars"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, jsonSerializerOptions); + writer.WritePropertyName("deprecatedRef"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, jsonSerializerOptions); + writer.WriteNumber("id", objectWithDeprecatedFields.Id); + writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); + } + } + + /// + /// The ObjectWithDeprecatedFieldsSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ObjectWithDeprecatedFields))] + public partial class ObjectWithDeprecatedFieldsSerializationContext : JsonSerializerContext + { + /// + /// The ObjectWithDeprecatedFieldsSerializationContext + /// + /// + public ObjectWithDeprecatedFieldsSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ObjectWithDeprecatedFieldsDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ObjectWithDeprecatedFields))] + public partial class ObjectWithDeprecatedFieldsDeserializationContext : JsonSerializerContext + { + /// + /// ObjectWithDeprecatedFieldsDeserializationContext + /// + /// + public ObjectWithDeprecatedFieldsDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OneOfString.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OneOfString.cs new file mode 100644 index 00000000000..1c4b8334db2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OneOfString.cs @@ -0,0 +1,195 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// OneOfString + /// + public partial class OneOfString : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + internal OneOfString(string varString) + { + VarString = varString; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets VarString + /// + public string? VarString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OneOfString {\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OneOfStringJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override OneOfString Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? varString = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + default: + break; + } + } + } + + if (varString != null) + return new OneOfString(varString); + + if (varString != null) + return new OneOfString(varString); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OneOfString oneOfString, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, oneOfString, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, OneOfString oneOfString, JsonSerializerOptions jsonSerializerOptions) + { + + } + } + + /// + /// The OneOfStringSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(OneOfString))] + public partial class OneOfStringSerializationContext : JsonSerializerContext + { + /// + /// The OneOfStringSerializationContext + /// + /// + public OneOfStringSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// OneOfStringDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(OneOfString))] + public partial class OneOfStringDeserializationContext : JsonSerializerContext + { + /// + /// OneOfStringDeserializationContext + /// + /// + public OneOfStringDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Order.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Order.cs new file mode 100644 index 00000000000..4297b458394 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Order.cs @@ -0,0 +1,385 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Order + /// + public partial class Order : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id + /// petId + /// quantity + /// shipDate + /// Order Status + /// complete (default to false) + [JsonConstructor] + public Order(long id, long petId, int quantity, DateTime shipDate, StatusEnum status, bool complete = false) + { + Id = id; + PetId = petId; + Quantity = quantity; + ShipDate = shipDate; + Status = status; + Complete = complete; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Order Status + /// + /// Order Status + public enum StatusEnum + { + /// + /// Enum Placed for value: placed + /// + Placed = 1, + + /// + /// Enum Approved for value: approved + /// + Approved = 2, + + /// + /// Enum Delivered for value: delivered + /// + Delivered = 3 + } + + /// + /// Returns a + /// + /// + /// + /// + public static StatusEnum StatusEnumFromString(string value) + { + if (value.Equals("placed")) + return StatusEnum.Placed; + + if (value.Equals("approved")) + return StatusEnum.Approved; + + if (value.Equals("delivered")) + return StatusEnum.Delivered; + + throw new NotImplementedException($"Could not convert value to type StatusEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static StatusEnum? StatusEnumFromStringOrDefault(string value) + { + if (value.Equals("placed")) + return StatusEnum.Placed; + + if (value.Equals("approved")) + return StatusEnum.Approved; + + if (value.Equals("delivered")) + return StatusEnum.Delivered; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string StatusEnumToJsonValue(StatusEnum value) + { + if (value == StatusEnum.Placed) + return "placed"; + + if (value == StatusEnum.Approved) + return "approved"; + + if (value == StatusEnum.Delivered) + return "delivered"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Order Status + /// + /// Order Status + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long Id { get; set; } + + /// + /// Gets or Sets PetId + /// + [JsonPropertyName("petId")] + public long PetId { get; set; } + + /// + /// Gets or Sets Quantity + /// + [JsonPropertyName("quantity")] + public int Quantity { get; set; } + + /// + /// Gets or Sets ShipDate + /// + /// 2020-02-02T20:20:20.000222Z + [JsonPropertyName("shipDate")] + public DateTime ShipDate { get; set; } + + /// + /// Gets or Sets Complete + /// + [JsonPropertyName("complete")] + public bool Complete { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Order {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PetId: ").Append(PetId).Append("\n"); + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OrderJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ShipDate + /// + public static string ShipDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + long? id = default; + long? petId = default; + int? quantity = default; + DateTime? shipDate = default; + Order.StatusEnum? status = default; + bool? complete = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + id = utf8JsonReader.GetInt64(); + break; + case "petId": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + petId = utf8JsonReader.GetInt64(); + break; + case "quantity": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + quantity = utf8JsonReader.GetInt32(); + break; + case "shipDate": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + shipDate = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = statusRawValue == null + ? null + : Order.StatusEnumFromStringOrDefault(statusRawValue); + break; + case "complete": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + complete = utf8JsonReader.GetBoolean(); + break; + default: + break; + } + } + } + + if (id == null) + throw new ArgumentNullException(nameof(id), "Property is required for class Order."); + + if (petId == null) + throw new ArgumentNullException(nameof(petId), "Property is required for class Order."); + + if (quantity == null) + throw new ArgumentNullException(nameof(quantity), "Property is required for class Order."); + + if (shipDate == null) + throw new ArgumentNullException(nameof(shipDate), "Property is required for class Order."); + + if (status == null) + throw new ArgumentNullException(nameof(status), "Property is required for class Order."); + + if (complete == null) + throw new ArgumentNullException(nameof(complete), "Property is required for class Order."); + + return new Order(id.Value, petId.Value, quantity.Value, shipDate.Value, status.Value, complete.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Order order, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, order, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Order order, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("id", order.Id); + writer.WriteNumber("petId", order.PetId); + writer.WriteNumber("quantity", order.Quantity); + writer.WriteString("shipDate", order.ShipDate.ToString(ShipDateFormat)); + + var statusRawValue = Order.StatusEnumToJsonValue(order.Status); + if (statusRawValue != null) + writer.WriteString("status", statusRawValue); + else + writer.WriteNull("status"); + + writer.WriteBoolean("complete", order.Complete); + } + } + + /// + /// The OrderSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Order))] + public partial class OrderSerializationContext : JsonSerializerContext + { + /// + /// The OrderSerializationContext + /// + /// + public OrderSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// OrderDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Order))] + public partial class OrderDeserializationContext : JsonSerializerContext + { + /// + /// OrderDeserializationContext + /// + /// + public OrderDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterComposite.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterComposite.cs new file mode 100644 index 00000000000..6443b1b88d1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterComposite.cs @@ -0,0 +1,234 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// OuterComposite + /// + public partial class OuterComposite : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// myBoolean + /// myNumber + /// myString + [JsonConstructor] + public OuterComposite(bool myBoolean, decimal myNumber, string myString) + { + MyBoolean = myBoolean; + MyNumber = myNumber; + MyString = myString; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets MyBoolean + /// + [JsonPropertyName("my_boolean")] + public bool MyBoolean { get; set; } + + /// + /// Gets or Sets MyNumber + /// + [JsonPropertyName("my_number")] + public decimal MyNumber { get; set; } + + /// + /// Gets or Sets MyString + /// + [JsonPropertyName("my_string")] + public string MyString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OuterComposite {\n"); + sb.Append(" MyBoolean: ").Append(MyBoolean).Append("\n"); + sb.Append(" MyNumber: ").Append(MyNumber).Append("\n"); + sb.Append(" MyString: ").Append(MyString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OuterCompositeJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + bool? myBoolean = default; + decimal? myNumber = default; + string? myString = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "my_boolean": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + myBoolean = utf8JsonReader.GetBoolean(); + break; + case "my_number": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + myNumber = utf8JsonReader.GetDecimal(); + break; + case "my_string": + myString = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (myBoolean == null) + throw new ArgumentNullException(nameof(myBoolean), "Property is required for class OuterComposite."); + + if (myNumber == null) + throw new ArgumentNullException(nameof(myNumber), "Property is required for class OuterComposite."); + + if (myString == null) + throw new ArgumentNullException(nameof(myString), "Property is required for class OuterComposite."); + + return new OuterComposite(myBoolean.Value, myNumber.Value, myString); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterComposite outerComposite, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, outerComposite, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, OuterComposite outerComposite, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteBoolean("my_boolean", outerComposite.MyBoolean); + writer.WriteNumber("my_number", outerComposite.MyNumber); + writer.WriteString("my_string", outerComposite.MyString); + } + } + + /// + /// The OuterCompositeSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(OuterComposite))] + public partial class OuterCompositeSerializationContext : JsonSerializerContext + { + /// + /// The OuterCompositeSerializationContext + /// + /// + public OuterCompositeSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// OuterCompositeDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(OuterComposite))] + public partial class OuterCompositeDeserializationContext : JsonSerializerContext + { + /// + /// OuterCompositeDeserializationContext + /// + /// + public OuterCompositeDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnum.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnum.cs new file mode 100644 index 00000000000..c1156ffc464 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnum.cs @@ -0,0 +1,224 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Defines OuterEnum + /// + public enum OuterEnum + { + /// + /// Enum Placed for value: placed + /// + Placed = 1, + + /// + /// Enum Approved for value: approved + /// + Approved = 2, + + /// + /// Enum Delivered for value: delivered + /// + Delivered = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class OuterEnumValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static OuterEnum FromString(string value) + { + if (value.Equals("placed")) + return OuterEnum.Placed; + + if (value.Equals("approved")) + return OuterEnum.Approved; + + if (value.Equals("delivered")) + return OuterEnum.Delivered; + + throw new NotImplementedException($"Could not convert value to type OuterEnum: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static OuterEnum? FromStringOrDefault(string value) + { + if (value.Equals("placed")) + return OuterEnum.Placed; + + if (value.Equals("approved")) + return OuterEnum.Approved; + + if (value.Equals("delivered")) + return OuterEnum.Delivered; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(OuterEnum value) + { + if (value == OuterEnum.Placed) + return "placed"; + + if (value == OuterEnum.Approved) + return "approved"; + + if (value == OuterEnum.Delivered) + return "delivered"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class OuterEnumJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnum? result = rawValue == null + ? null + : OuterEnumValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the OuterEnum to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterEnum outerEnum, JsonSerializerOptions options) + { + writer.WriteStringValue(outerEnum.ToString()); + } + } + + /// + /// A Json converter for type + /// + public class OuterEnumNullableJsonConverter : JsonConverter + { + /// + /// Returns a OuterEnum from the Json object + /// + /// + /// + /// + /// + public override OuterEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnum? result = rawValue == null + ? null + : OuterEnumValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterEnum? outerEnum, JsonSerializerOptions options) + { + writer.WriteStringValue(outerEnum?.ToString() ?? "null"); + } + } + + + /// + /// The OuterEnumSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(OuterEnum))] + public partial class OuterEnumSerializationContext : JsonSerializerContext + { + /// + /// The OuterEnumSerializationContext + /// + /// + public OuterEnumSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// OuterEnumDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(OuterEnum))] + public partial class OuterEnumDeserializationContext : JsonSerializerContext + { + /// + /// OuterEnumDeserializationContext + /// + /// + public OuterEnumDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumDefaultValue.cs new file mode 100644 index 00000000000..5838e6dc83e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumDefaultValue.cs @@ -0,0 +1,224 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Defines OuterEnumDefaultValue + /// + public enum OuterEnumDefaultValue + { + /// + /// Enum Placed for value: placed + /// + Placed = 1, + + /// + /// Enum Approved for value: approved + /// + Approved = 2, + + /// + /// Enum Delivered for value: delivered + /// + Delivered = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class OuterEnumDefaultValueValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static OuterEnumDefaultValue FromString(string value) + { + if (value.Equals("placed")) + return OuterEnumDefaultValue.Placed; + + if (value.Equals("approved")) + return OuterEnumDefaultValue.Approved; + + if (value.Equals("delivered")) + return OuterEnumDefaultValue.Delivered; + + throw new NotImplementedException($"Could not convert value to type OuterEnumDefaultValue: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static OuterEnumDefaultValue? FromStringOrDefault(string value) + { + if (value.Equals("placed")) + return OuterEnumDefaultValue.Placed; + + if (value.Equals("approved")) + return OuterEnumDefaultValue.Approved; + + if (value.Equals("delivered")) + return OuterEnumDefaultValue.Delivered; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(OuterEnumDefaultValue value) + { + if (value == OuterEnumDefaultValue.Placed) + return "placed"; + + if (value == OuterEnumDefaultValue.Approved) + return "approved"; + + if (value == OuterEnumDefaultValue.Delivered) + return "delivered"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class OuterEnumDefaultValueJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumDefaultValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumDefaultValue? result = rawValue == null + ? null + : OuterEnumDefaultValueValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the OuterEnumDefaultValue to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterEnumDefaultValue outerEnumDefaultValue, JsonSerializerOptions options) + { + writer.WriteStringValue(outerEnumDefaultValue.ToString()); + } + } + + /// + /// A Json converter for type + /// + public class OuterEnumDefaultValueNullableJsonConverter : JsonConverter + { + /// + /// Returns a OuterEnumDefaultValue from the Json object + /// + /// + /// + /// + /// + public override OuterEnumDefaultValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumDefaultValue? result = rawValue == null + ? null + : OuterEnumDefaultValueValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterEnumDefaultValue? outerEnumDefaultValue, JsonSerializerOptions options) + { + writer.WriteStringValue(outerEnumDefaultValue?.ToString() ?? "null"); + } + } + + + /// + /// The OuterEnumDefaultValueSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(OuterEnumDefaultValue))] + public partial class OuterEnumDefaultValueSerializationContext : JsonSerializerContext + { + /// + /// The OuterEnumDefaultValueSerializationContext + /// + /// + public OuterEnumDefaultValueSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// OuterEnumDefaultValueDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(OuterEnumDefaultValue))] + public partial class OuterEnumDefaultValueDeserializationContext : JsonSerializerContext + { + /// + /// OuterEnumDefaultValueDeserializationContext + /// + /// + public OuterEnumDefaultValueDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumInteger.cs new file mode 100644 index 00000000000..8b5cc059002 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumInteger.cs @@ -0,0 +1,215 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Defines OuterEnumInteger + /// + public enum OuterEnumInteger + { + /// + /// Enum NUMBER_0 for value: 0 + /// + NUMBER_0 = 0, + + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class OuterEnumIntegerValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static OuterEnumInteger FromString(string value) + { + if (value.Equals((0).ToString())) + return OuterEnumInteger.NUMBER_0; + + if (value.Equals((1).ToString())) + return OuterEnumInteger.NUMBER_1; + + if (value.Equals((2).ToString())) + return OuterEnumInteger.NUMBER_2; + + throw new NotImplementedException($"Could not convert value to type OuterEnumInteger: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static OuterEnumInteger? FromStringOrDefault(string value) + { + if (value.Equals((0).ToString())) + return OuterEnumInteger.NUMBER_0; + + if (value.Equals((1).ToString())) + return OuterEnumInteger.NUMBER_1; + + if (value.Equals((2).ToString())) + return OuterEnumInteger.NUMBER_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static int ToJsonValue(OuterEnumInteger value) + { + return (int) value; + } + } + + /// + /// A Json converter for type + /// + /// + public class OuterEnumIntegerJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumInteger? result = rawValue == null + ? null + : OuterEnumIntegerValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the OuterEnumInteger to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterEnumInteger outerEnumInteger, JsonSerializerOptions options) + { + writer.WriteStringValue(outerEnumInteger.ToString()); + } + } + + /// + /// A Json converter for type + /// + public class OuterEnumIntegerNullableJsonConverter : JsonConverter + { + /// + /// Returns a OuterEnumInteger from the Json object + /// + /// + /// + /// + /// + public override OuterEnumInteger? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumInteger? result = rawValue == null + ? null + : OuterEnumIntegerValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterEnumInteger? outerEnumInteger, JsonSerializerOptions options) + { + writer.WriteStringValue(outerEnumInteger?.ToString() ?? "null"); + } + } + + + /// + /// The OuterEnumIntegerSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(OuterEnumInteger))] + public partial class OuterEnumIntegerSerializationContext : JsonSerializerContext + { + /// + /// The OuterEnumIntegerSerializationContext + /// + /// + public OuterEnumIntegerSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// OuterEnumIntegerDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(OuterEnumInteger))] + public partial class OuterEnumIntegerDeserializationContext : JsonSerializerContext + { + /// + /// OuterEnumIntegerDeserializationContext + /// + /// + public OuterEnumIntegerDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumIntegerDefaultValue.cs new file mode 100644 index 00000000000..53e7411cb24 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumIntegerDefaultValue.cs @@ -0,0 +1,215 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Defines OuterEnumIntegerDefaultValue + /// + public enum OuterEnumIntegerDefaultValue + { + /// + /// Enum NUMBER_0 for value: 0 + /// + NUMBER_0 = 0, + + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class OuterEnumIntegerDefaultValueValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static OuterEnumIntegerDefaultValue FromString(string value) + { + if (value.Equals((0).ToString())) + return OuterEnumIntegerDefaultValue.NUMBER_0; + + if (value.Equals((1).ToString())) + return OuterEnumIntegerDefaultValue.NUMBER_1; + + if (value.Equals((2).ToString())) + return OuterEnumIntegerDefaultValue.NUMBER_2; + + throw new NotImplementedException($"Could not convert value to type OuterEnumIntegerDefaultValue: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static OuterEnumIntegerDefaultValue? FromStringOrDefault(string value) + { + if (value.Equals((0).ToString())) + return OuterEnumIntegerDefaultValue.NUMBER_0; + + if (value.Equals((1).ToString())) + return OuterEnumIntegerDefaultValue.NUMBER_1; + + if (value.Equals((2).ToString())) + return OuterEnumIntegerDefaultValue.NUMBER_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static int ToJsonValue(OuterEnumIntegerDefaultValue value) + { + return (int) value; + } + } + + /// + /// A Json converter for type + /// + /// + public class OuterEnumIntegerDefaultValueJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumIntegerDefaultValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumIntegerDefaultValue? result = rawValue == null + ? null + : OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the OuterEnumIntegerDefaultValue to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue, JsonSerializerOptions options) + { + writer.WriteStringValue(outerEnumIntegerDefaultValue.ToString()); + } + } + + /// + /// A Json converter for type + /// + public class OuterEnumIntegerDefaultValueNullableJsonConverter : JsonConverter + { + /// + /// Returns a OuterEnumIntegerDefaultValue from the Json object + /// + /// + /// + /// + /// + public override OuterEnumIntegerDefaultValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumIntegerDefaultValue? result = rawValue == null + ? null + : OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterEnumIntegerDefaultValue? outerEnumIntegerDefaultValue, JsonSerializerOptions options) + { + writer.WriteStringValue(outerEnumIntegerDefaultValue?.ToString() ?? "null"); + } + } + + + /// + /// The OuterEnumIntegerDefaultValueSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(OuterEnumIntegerDefaultValue))] + public partial class OuterEnumIntegerDefaultValueSerializationContext : JsonSerializerContext + { + /// + /// The OuterEnumIntegerDefaultValueSerializationContext + /// + /// + public OuterEnumIntegerDefaultValueSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// OuterEnumIntegerDefaultValueDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(OuterEnumIntegerDefaultValue))] + public partial class OuterEnumIntegerDefaultValueDeserializationContext : JsonSerializerContext + { + /// + /// OuterEnumIntegerDefaultValueDeserializationContext + /// + /// + public OuterEnumIntegerDefaultValueDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumTest.cs new file mode 100644 index 00000000000..dde6eaa6186 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterEnumTest.cs @@ -0,0 +1,294 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Defines Outer_Enum_Test + /// + public enum OuterEnumTest + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Converts to and from the JSON value + /// + public static class OuterEnumTestValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static OuterEnumTest FromString(string value) + { + if (value.Equals("UPPER")) + return OuterEnumTest.UPPER; + + if (value.Equals("lower")) + return OuterEnumTest.Lower; + + if (value.Equals("")) + return OuterEnumTest.Empty; + + if (value.Equals("Value\twith tab")) + return OuterEnumTest.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return OuterEnumTest.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return OuterEnumTest.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return OuterEnumTest.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return OuterEnumTest.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type OuterEnumTest: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static OuterEnumTest? FromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return OuterEnumTest.UPPER; + + if (value.Equals("lower")) + return OuterEnumTest.Lower; + + if (value.Equals("")) + return OuterEnumTest.Empty; + + if (value.Equals("Value\twith tab")) + return OuterEnumTest.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return OuterEnumTest.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return OuterEnumTest.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return OuterEnumTest.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return OuterEnumTest.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(OuterEnumTest value) + { + if (value == OuterEnumTest.UPPER) + return "UPPER"; + + if (value == OuterEnumTest.Lower) + return "lower"; + + if (value == OuterEnumTest.Empty) + return ""; + + if (value == OuterEnumTest.ValuewithTab) + return "Value\twith tab"; + + if (value == OuterEnumTest.ValueWithQuote) + return "Value with \" quote"; + + if (value == OuterEnumTest.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == OuterEnumTest.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == OuterEnumTest.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class OuterEnumTestJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override OuterEnumTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumTest? result = rawValue == null + ? null + : OuterEnumTestValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the OuterEnumTest to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterEnumTest outerEnumTest, JsonSerializerOptions options) + { + writer.WriteStringValue(outerEnumTest.ToString()); + } + } + + /// + /// A Json converter for type + /// + public class OuterEnumTestNullableJsonConverter : JsonConverter + { + /// + /// Returns a OuterEnumTest from the Json object + /// + /// + /// + /// + /// + public override OuterEnumTest? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + OuterEnumTest? result = rawValue == null + ? null + : OuterEnumTestValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OuterEnumTest? outerEnumTest, JsonSerializerOptions options) + { + writer.WriteStringValue(outerEnumTest?.ToString() ?? "null"); + } + } + + + /// + /// The OuterEnumTestSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(OuterEnumTest))] + public partial class OuterEnumTestSerializationContext : JsonSerializerContext + { + /// + /// The OuterEnumTestSerializationContext + /// + /// + public OuterEnumTestSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// OuterEnumTestDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(OuterEnumTest))] + public partial class OuterEnumTestDeserializationContext : JsonSerializerContext + { + /// + /// OuterEnumTestDeserializationContext + /// + /// + public OuterEnumTestDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ParentPet.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ParentPet.cs new file mode 100644 index 00000000000..ab38fd96c8e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ParentPet.cs @@ -0,0 +1,174 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ParentPet + /// + public partial class ParentPet : GrandparentAnimal, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// petType + [JsonConstructor] + public ParentPet(string petType) : base(petType) + { + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ParentPet {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class ParentPetJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? petType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "pet_type": + petType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (petType == null) + throw new ArgumentNullException(nameof(petType), "Property is required for class ParentPet."); + + return new ParentPet(petType); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, parentPet, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("pet_type", parentPet.PetType); + } + } + + /// + /// The ParentPetSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ParentPet))] + public partial class ParentPetSerializationContext : JsonSerializerContext + { + /// + /// The ParentPetSerializationContext + /// + /// + public ParentPetSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ParentPetDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ParentPet))] + public partial class ParentPetDeserializationContext : JsonSerializerContext + { + /// + /// ParentPetDeserializationContext + /// + /// + public ParentPetDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pet.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pet.cs new file mode 100644 index 00000000000..9d504ea689e --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pet.cs @@ -0,0 +1,382 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Pet + /// + public partial class Pet : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// category + /// id + /// name + /// photoUrls + /// pet status in the store + /// tags + [JsonConstructor] + public Pet(Category category, long id, string name, List photoUrls, StatusEnum status, List tags) + { + Category = category; + Id = id; + Name = name; + PhotoUrls = photoUrls; + Status = status; + Tags = tags; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// pet status in the store + /// + /// pet status in the store + public enum StatusEnum + { + /// + /// Enum Available for value: available + /// + Available = 1, + + /// + /// Enum Pending for value: pending + /// + Pending = 2, + + /// + /// Enum Sold for value: sold + /// + Sold = 3 + } + + /// + /// Returns a + /// + /// + /// + /// + public static StatusEnum StatusEnumFromString(string value) + { + if (value.Equals("available")) + return StatusEnum.Available; + + if (value.Equals("pending")) + return StatusEnum.Pending; + + if (value.Equals("sold")) + return StatusEnum.Sold; + + throw new NotImplementedException($"Could not convert value to type StatusEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static StatusEnum? StatusEnumFromStringOrDefault(string value) + { + if (value.Equals("available")) + return StatusEnum.Available; + + if (value.Equals("pending")) + return StatusEnum.Pending; + + if (value.Equals("sold")) + return StatusEnum.Sold; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string StatusEnumToJsonValue(StatusEnum value) + { + if (value == StatusEnum.Available) + return "available"; + + if (value == StatusEnum.Pending) + return "pending"; + + if (value == StatusEnum.Sold) + return "sold"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// pet status in the store + /// + /// pet status in the store + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// Gets or Sets Category + /// + [JsonPropertyName("category")] + public Category Category { get; set; } + + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long Id { get; set; } + + /// + /// Gets or Sets Name + /// + /// doggie + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets PhotoUrls + /// + [JsonPropertyName("photoUrls")] + public List PhotoUrls { get; set; } + + /// + /// Gets or Sets Tags + /// + [JsonPropertyName("tags")] + public List Tags { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Pet {\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Tags: ").Append(Tags).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PetJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Category? category = default; + long? id = default; + string? name = default; + List? photoUrls = default; + Pet.StatusEnum? status = default; + List? tags = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "category": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + category = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "id": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + id = utf8JsonReader.GetInt64(); + break; + case "name": + name = utf8JsonReader.GetString(); + break; + case "photoUrls": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + photoUrls = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = statusRawValue == null + ? null + : Pet.StatusEnumFromStringOrDefault(statusRawValue); + break; + case "tags": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + tags = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (category == null) + throw new ArgumentNullException(nameof(category), "Property is required for class Pet."); + + if (id == null) + throw new ArgumentNullException(nameof(id), "Property is required for class Pet."); + + if (name == null) + throw new ArgumentNullException(nameof(name), "Property is required for class Pet."); + + if (photoUrls == null) + throw new ArgumentNullException(nameof(photoUrls), "Property is required for class Pet."); + + if (status == null) + throw new ArgumentNullException(nameof(status), "Property is required for class Pet."); + + if (tags == null) + throw new ArgumentNullException(nameof(tags), "Property is required for class Pet."); + + return new Pet(category, id.Value, name, photoUrls, status.Value, tags); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Pet pet, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, pet, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Pet pet, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("category"); + JsonSerializer.Serialize(writer, pet.Category, jsonSerializerOptions); + writer.WriteNumber("id", pet.Id); + writer.WriteString("name", pet.Name); + writer.WritePropertyName("photoUrls"); + JsonSerializer.Serialize(writer, pet.PhotoUrls, jsonSerializerOptions); + + var statusRawValue = Pet.StatusEnumToJsonValue(pet.Status); + if (statusRawValue != null) + writer.WriteString("status", statusRawValue); + else + writer.WriteNull("status"); + + writer.WritePropertyName("tags"); + JsonSerializer.Serialize(writer, pet.Tags, jsonSerializerOptions); + } + } + + /// + /// The PetSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Pet))] + public partial class PetSerializationContext : JsonSerializerContext + { + /// + /// The PetSerializationContext + /// + /// + public PetSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// PetDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Pet))] + public partial class PetDeserializationContext : JsonSerializerContext + { + /// + /// PetDeserializationContext + /// + /// + public PetDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pig.cs new file mode 100644 index 00000000000..517b9c8ebc7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pig.cs @@ -0,0 +1,280 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Pig + /// + public partial class Pig : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// className + public Pig(BasquePig basquePig, string className) + { + BasquePig = basquePig; + ClassName = className; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// className + public Pig(DanishPig danishPig, string className) + { + DanishPig = danishPig; + ClassName = className; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets BasquePig + /// + public BasquePig? BasquePig { get; set; } + + /// + /// Gets or Sets DanishPig + /// + public DanishPig? DanishPig { get; set; } + + /// + /// Gets or Sets ClassName + /// + [JsonPropertyName("className")] + public string ClassName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Pig {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PigJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? className = default; + + BasquePig? basquePig = null; + DanishPig? danishPig = null; + + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName?.Equals("className") ?? false) + { + string? discriminator = utf8JsonReaderDiscriminator.GetString(); + if (discriminator?.Equals("BasquePig") ?? false) + { + Utf8JsonReader utf8JsonReaderBasquePig = utf8JsonReader; + basquePig = JsonSerializer.Deserialize(ref utf8JsonReaderBasquePig, jsonSerializerOptions); + } + if (discriminator?.Equals("DanishPig") ?? false) + { + Utf8JsonReader utf8JsonReaderDanishPig = utf8JsonReader; + danishPig = JsonSerializer.Deserialize(ref utf8JsonReaderDanishPig, jsonSerializerOptions); + } + } + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "className": + className = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (className == null) + throw new ArgumentNullException(nameof(className), "Property is required for class Pig."); + + if (basquePig != null) + return new Pig(basquePig, className); + + if (danishPig != null) + return new Pig(danishPig, className); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (pig.BasquePig != null) { + BasquePigJsonConverter basquePigJsonConverter = (BasquePigJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(pig.BasquePig.GetType())); + basquePigJsonConverter.WriteProperties(ref writer, pig.BasquePig, jsonSerializerOptions); + } + + if (pig.DanishPig != null) { + DanishPigJsonConverter danishPigJsonConverter = (DanishPigJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(pig.DanishPig.GetType())); + danishPigJsonConverter.WriteProperties(ref writer, pig.DanishPig, jsonSerializerOptions); + } + + WriteProperties(ref writer, pig, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Pig pig, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("className", pig.ClassName); + } + } + + /// + /// The PigSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Pig))] + public partial class PigSerializationContext : JsonSerializerContext + { + /// + /// The PigSerializationContext + /// + /// + public PigSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// PigDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Pig))] + public partial class PigDeserializationContext : JsonSerializerContext + { + /// + /// PigDeserializationContext + /// + /// + public PigDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/PolymorphicProperty.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/PolymorphicProperty.cs new file mode 100644 index 00000000000..5bbdeac532f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/PolymorphicProperty.cs @@ -0,0 +1,274 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// PolymorphicProperty + /// + public partial class PolymorphicProperty : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + internal PolymorphicProperty(bool varBool) + { + VarBool = varBool; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + internal PolymorphicProperty(string varString) + { + VarString = varString; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + internal PolymorphicProperty(Object varObject) + { + VarObject = varObject; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + internal PolymorphicProperty(List list) + { + List = list; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets VarBool + /// + public bool? VarBool { get; set; } + + /// + /// Gets or Sets VarString + /// + public string? VarString { get; set; } + + /// + /// Gets or Sets VarObject + /// + public Object? VarObject { get; set; } + + /// + /// Gets or Sets List + /// + public List? List { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PolymorphicProperty {\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PolymorphicPropertyJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override PolymorphicProperty Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + bool? varBool = default; + string? varString = default; + Object? varObject = default; + List? list = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderVarBool = utf8JsonReader; + OpenAPIClientUtils.TryDeserialize(ref utf8JsonReaderVarBool, jsonSerializerOptions, out varBool); + + Utf8JsonReader utf8JsonReaderVarString = utf8JsonReader; + OpenAPIClientUtils.TryDeserialize(ref utf8JsonReaderVarString, jsonSerializerOptions, out varString); + + Utf8JsonReader utf8JsonReaderVarObject = utf8JsonReader; + OpenAPIClientUtils.TryDeserialize(ref utf8JsonReaderVarObject, jsonSerializerOptions, out varObject); + + Utf8JsonReader utf8JsonReaderList = utf8JsonReader; + OpenAPIClientUtils.TryDeserialize?>(ref utf8JsonReaderList, jsonSerializerOptions, out list); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + default: + break; + } + } + } + + if (varBool != null) + return new PolymorphicProperty(varBool); + + if (varString != null) + return new PolymorphicProperty(varString); + + if (varObject != null) + return new PolymorphicProperty(varObject); + + if (list != null) + return new PolymorphicProperty(list); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PolymorphicProperty polymorphicProperty, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, polymorphicProperty, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, PolymorphicProperty polymorphicProperty, JsonSerializerOptions jsonSerializerOptions) + { + + } + } + + /// + /// The PolymorphicPropertySerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(PolymorphicProperty))] + public partial class PolymorphicPropertySerializationContext : JsonSerializerContext + { + /// + /// The PolymorphicPropertySerializationContext + /// + /// + public PolymorphicPropertySerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// PolymorphicPropertyDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(PolymorphicProperty))] + public partial class PolymorphicPropertyDeserializationContext : JsonSerializerContext + { + /// + /// PolymorphicPropertyDeserializationContext + /// + /// + public PolymorphicPropertyDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Quadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Quadrilateral.cs new file mode 100644 index 00000000000..d082a184fa0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Quadrilateral.cs @@ -0,0 +1,280 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Quadrilateral + /// + public partial class Quadrilateral : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// quadrilateralType + public Quadrilateral(SimpleQuadrilateral simpleQuadrilateral, string quadrilateralType) + { + SimpleQuadrilateral = simpleQuadrilateral; + QuadrilateralType = quadrilateralType; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// quadrilateralType + public Quadrilateral(ComplexQuadrilateral complexQuadrilateral, string quadrilateralType) + { + ComplexQuadrilateral = complexQuadrilateral; + QuadrilateralType = quadrilateralType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets SimpleQuadrilateral + /// + public SimpleQuadrilateral? SimpleQuadrilateral { get; set; } + + /// + /// Gets or Sets ComplexQuadrilateral + /// + public ComplexQuadrilateral? ComplexQuadrilateral { get; set; } + + /// + /// Gets or Sets QuadrilateralType + /// + [JsonPropertyName("quadrilateralType")] + public string QuadrilateralType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Quadrilateral {\n"); + sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class QuadrilateralJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? quadrilateralType = default; + + ComplexQuadrilateral? complexQuadrilateral = null; + SimpleQuadrilateral? simpleQuadrilateral = null; + + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName?.Equals("quadrilateralType") ?? false) + { + string? discriminator = utf8JsonReaderDiscriminator.GetString(); + if (discriminator?.Equals("ComplexQuadrilateral") ?? false) + { + Utf8JsonReader utf8JsonReaderComplexQuadrilateral = utf8JsonReader; + complexQuadrilateral = JsonSerializer.Deserialize(ref utf8JsonReaderComplexQuadrilateral, jsonSerializerOptions); + } + if (discriminator?.Equals("SimpleQuadrilateral") ?? false) + { + Utf8JsonReader utf8JsonReaderSimpleQuadrilateral = utf8JsonReader; + simpleQuadrilateral = JsonSerializer.Deserialize(ref utf8JsonReaderSimpleQuadrilateral, jsonSerializerOptions); + } + } + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "quadrilateralType": + quadrilateralType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (quadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class Quadrilateral."); + + if (complexQuadrilateral != null) + return new Quadrilateral(complexQuadrilateral, quadrilateralType); + + if (simpleQuadrilateral != null) + return new Quadrilateral(simpleQuadrilateral, quadrilateralType); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (quadrilateral.ComplexQuadrilateral != null) { + ComplexQuadrilateralJsonConverter complexQuadrilateralJsonConverter = (ComplexQuadrilateralJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(quadrilateral.ComplexQuadrilateral.GetType())); + complexQuadrilateralJsonConverter.WriteProperties(ref writer, quadrilateral.ComplexQuadrilateral, jsonSerializerOptions); + } + + if (quadrilateral.SimpleQuadrilateral != null) { + SimpleQuadrilateralJsonConverter simpleQuadrilateralJsonConverter = (SimpleQuadrilateralJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(quadrilateral.SimpleQuadrilateral.GetType())); + simpleQuadrilateralJsonConverter.WriteProperties(ref writer, quadrilateral.SimpleQuadrilateral, jsonSerializerOptions); + } + + WriteProperties(ref writer, quadrilateral, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("quadrilateralType", quadrilateral.QuadrilateralType); + } + } + + /// + /// The QuadrilateralSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Quadrilateral))] + public partial class QuadrilateralSerializationContext : JsonSerializerContext + { + /// + /// The QuadrilateralSerializationContext + /// + /// + public QuadrilateralSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// QuadrilateralDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Quadrilateral))] + public partial class QuadrilateralDeserializationContext : JsonSerializerContext + { + /// + /// QuadrilateralDeserializationContext + /// + /// + public QuadrilateralDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/QuadrilateralInterface.cs new file mode 100644 index 00000000000..6c288857e7c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/QuadrilateralInterface.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// QuadrilateralInterface + /// + public partial class QuadrilateralInterface : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// quadrilateralType + [JsonConstructor] + public QuadrilateralInterface(string quadrilateralType) + { + QuadrilateralType = quadrilateralType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets QuadrilateralType + /// + [JsonPropertyName("quadrilateralType")] + public string QuadrilateralType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class QuadrilateralInterface {\n"); + sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class QuadrilateralInterfaceJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? quadrilateralType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "quadrilateralType": + quadrilateralType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (quadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class QuadrilateralInterface."); + + return new QuadrilateralInterface(quadrilateralType); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, QuadrilateralInterface quadrilateralInterface, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, quadrilateralInterface, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, QuadrilateralInterface quadrilateralInterface, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("quadrilateralType", quadrilateralInterface.QuadrilateralType); + } + } + + /// + /// The QuadrilateralInterfaceSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(QuadrilateralInterface))] + public partial class QuadrilateralInterfaceSerializationContext : JsonSerializerContext + { + /// + /// The QuadrilateralInterfaceSerializationContext + /// + /// + public QuadrilateralInterfaceSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// QuadrilateralInterfaceDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(QuadrilateralInterface))] + public partial class QuadrilateralInterfaceDeserializationContext : JsonSerializerContext + { + /// + /// QuadrilateralInterfaceDeserializationContext + /// + /// + public QuadrilateralInterfaceDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ReadOnlyFirst.cs new file mode 100644 index 00000000000..6aa84200207 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ReadOnlyFirst.cs @@ -0,0 +1,251 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ReadOnlyFirst + /// + public partial class ReadOnlyFirst : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// bar + /// baz + [JsonConstructor] + public ReadOnlyFirst(string bar, string baz) + { + Bar = bar; + Baz = baz; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Bar + /// + [JsonPropertyName("bar")] + public string Bar { get; } + + /// + /// Gets or Sets Baz + /// + [JsonPropertyName("baz")] + public string Baz { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ReadOnlyFirst {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" Baz: ").Append(Baz).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object? input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ReadOnlyFirst).AreEqual; + } + + /// + /// Returns true if ReadOnlyFirst instances are equal + /// + /// Instance of ReadOnlyFirst to be compared + /// Boolean + public bool Equals(ReadOnlyFirst? input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReadOnlyFirstJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? bar = default; + string? baz = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "bar": + bar = utf8JsonReader.GetString(); + break; + case "baz": + baz = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (bar == null) + throw new ArgumentNullException(nameof(bar), "Property is required for class ReadOnlyFirst."); + + if (baz == null) + throw new ArgumentNullException(nameof(baz), "Property is required for class ReadOnlyFirst."); + + return new ReadOnlyFirst(bar, baz); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, readOnlyFirst, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("bar", readOnlyFirst.Bar); + writer.WriteString("baz", readOnlyFirst.Baz); + } + } + + /// + /// The ReadOnlyFirstSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ReadOnlyFirst))] + public partial class ReadOnlyFirstSerializationContext : JsonSerializerContext + { + /// + /// The ReadOnlyFirstSerializationContext + /// + /// + public ReadOnlyFirstSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ReadOnlyFirstDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ReadOnlyFirst))] + public partial class ReadOnlyFirstDeserializationContext : JsonSerializerContext + { + /// + /// ReadOnlyFirstDeserializationContext + /// + /// + public ReadOnlyFirstDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Return.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Return.cs new file mode 100644 index 00000000000..ebb78ff2cde --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Return.cs @@ -0,0 +1,199 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Model for testing reserved words + /// + public partial class Return : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// varReturn + [JsonConstructor] + public Return(int varReturn) + { + VarReturn = varReturn; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets VarReturn + /// + [JsonPropertyName("return")] + public int VarReturn { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Return {\n"); + sb.Append(" VarReturn: ").Append(VarReturn).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReturnJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + int? varReturn = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "return": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + varReturn = utf8JsonReader.GetInt32(); + break; + default: + break; + } + } + } + + if (varReturn == null) + throw new ArgumentNullException(nameof(varReturn), "Property is required for class Return."); + + return new Return(varReturn.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Return varReturn, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, varReturn, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Return varReturn, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("return", varReturn.VarReturn); + } + } + + /// + /// The ReturnSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Return))] + public partial class ReturnSerializationContext : JsonSerializerContext + { + /// + /// The ReturnSerializationContext + /// + /// + public ReturnSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ReturnDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Return))] + public partial class ReturnDeserializationContext : JsonSerializerContext + { + /// + /// ReturnDeserializationContext + /// + /// + public ReturnDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHash.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHash.cs new file mode 100644 index 00000000000..ceceff5abcc --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHash.cs @@ -0,0 +1,218 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Role report Hash + /// + public partial class RolesReportsHash : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// role + /// roleUuid + [JsonConstructor] + public RolesReportsHash(RolesReportsHashRole role, Guid roleUuid) + { + Role = role; + RoleUuid = roleUuid; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Role + /// + [JsonPropertyName("role")] + public RolesReportsHashRole Role { get; set; } + + /// + /// Gets or Sets RoleUuid + /// + [JsonPropertyName("role_uuid")] + public Guid RoleUuid { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RolesReportsHash {\n"); + sb.Append(" Role: ").Append(Role).Append("\n"); + sb.Append(" RoleUuid: ").Append(RoleUuid).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RolesReportsHashJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + RolesReportsHashRole? role = default; + Guid? roleUuid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "role": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + role = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "role_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + roleUuid = utf8JsonReader.GetGuid(); + break; + default: + break; + } + } + } + + if (role == null) + throw new ArgumentNullException(nameof(role), "Property is required for class RolesReportsHash."); + + if (roleUuid == null) + throw new ArgumentNullException(nameof(roleUuid), "Property is required for class RolesReportsHash."); + + return new RolesReportsHash(role, roleUuid.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RolesReportsHash rolesReportsHash, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, rolesReportsHash, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, RolesReportsHash rolesReportsHash, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("role"); + JsonSerializer.Serialize(writer, rolesReportsHash.Role, jsonSerializerOptions); + writer.WriteString("role_uuid", rolesReportsHash.RoleUuid); + } + } + + /// + /// The RolesReportsHashSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(RolesReportsHash))] + public partial class RolesReportsHashSerializationContext : JsonSerializerContext + { + /// + /// The RolesReportsHashSerializationContext + /// + /// + public RolesReportsHashSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// RolesReportsHashDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(RolesReportsHash))] + public partial class RolesReportsHashDeserializationContext : JsonSerializerContext + { + /// + /// RolesReportsHashDeserializationContext + /// + /// + public RolesReportsHashDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHashRole.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHashRole.cs new file mode 100644 index 00000000000..88d5afc2b70 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHashRole.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// RolesReportsHashRole + /// + public partial class RolesReportsHashRole : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + [JsonConstructor] + public RolesReportsHashRole(string name) + { + Name = name; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RolesReportsHashRole {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RolesReportsHashRoleJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + name = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (name == null) + throw new ArgumentNullException(nameof(name), "Property is required for class RolesReportsHashRole."); + + return new RolesReportsHashRole(name); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RolesReportsHashRole rolesReportsHashRole, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, rolesReportsHashRole, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, RolesReportsHashRole rolesReportsHashRole, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("name", rolesReportsHashRole.Name); + } + } + + /// + /// The RolesReportsHashRoleSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(RolesReportsHashRole))] + public partial class RolesReportsHashRoleSerializationContext : JsonSerializerContext + { + /// + /// The RolesReportsHashRoleSerializationContext + /// + /// + public RolesReportsHashRoleSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// RolesReportsHashRoleDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(RolesReportsHashRole))] + public partial class RolesReportsHashRoleDeserializationContext : JsonSerializerContext + { + /// + /// RolesReportsHashRoleDeserializationContext + /// + /// + public RolesReportsHashRoleDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ScaleneTriangle.cs new file mode 100644 index 00000000000..5aa209d7f2a --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ScaleneTriangle.cs @@ -0,0 +1,215 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ScaleneTriangle + /// + public partial class ScaleneTriangle : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// shapeType + /// triangleType + [JsonConstructor] + public ScaleneTriangle(string shapeType, string triangleType) + { + ShapeType = shapeType; + TriangleType = triangleType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ShapeType + /// + [JsonPropertyName("shapeType")] + public string ShapeType { get; set; } + + /// + /// Gets or Sets TriangleType + /// + [JsonPropertyName("triangleType")] + public string TriangleType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScaleneTriangle {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ScaleneTriangleJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? shapeType = default; + string? triangleType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "shapeType": + shapeType = utf8JsonReader.GetString(); + break; + case "triangleType": + triangleType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (shapeType == null) + throw new ArgumentNullException(nameof(shapeType), "Property is required for class ScaleneTriangle."); + + if (triangleType == null) + throw new ArgumentNullException(nameof(triangleType), "Property is required for class ScaleneTriangle."); + + return new ScaleneTriangle(shapeType, triangleType); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, scaleneTriangle, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("shapeType", scaleneTriangle.ShapeType); + writer.WriteString("triangleType", scaleneTriangle.TriangleType); + } + } + + /// + /// The ScaleneTriangleSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ScaleneTriangle))] + public partial class ScaleneTriangleSerializationContext : JsonSerializerContext + { + /// + /// The ScaleneTriangleSerializationContext + /// + /// + public ScaleneTriangleSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ScaleneTriangleDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ScaleneTriangle))] + public partial class ScaleneTriangleDeserializationContext : JsonSerializerContext + { + /// + /// ScaleneTriangleDeserializationContext + /// + /// + public ScaleneTriangleDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Shape.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Shape.cs new file mode 100644 index 00000000000..8a873c3fc15 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Shape.cs @@ -0,0 +1,280 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Shape + /// + public partial class Shape : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// shapeType + public Shape(Triangle triangle, string shapeType) + { + Triangle = triangle; + ShapeType = shapeType; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// shapeType + public Shape(Quadrilateral quadrilateral, string shapeType) + { + Quadrilateral = quadrilateral; + ShapeType = shapeType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Triangle + /// + public Triangle? Triangle { get; set; } + + /// + /// Gets or Sets Quadrilateral + /// + public Quadrilateral? Quadrilateral { get; set; } + + /// + /// Gets or Sets ShapeType + /// + [JsonPropertyName("shapeType")] + public string ShapeType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Shape {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ShapeJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? shapeType = default; + + Quadrilateral? quadrilateral = null; + Triangle? triangle = null; + + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName?.Equals("shapeType") ?? false) + { + string? discriminator = utf8JsonReaderDiscriminator.GetString(); + if (discriminator?.Equals("Quadrilateral") ?? false) + { + Utf8JsonReader utf8JsonReaderQuadrilateral = utf8JsonReader; + quadrilateral = JsonSerializer.Deserialize(ref utf8JsonReaderQuadrilateral, jsonSerializerOptions); + } + if (discriminator?.Equals("Triangle") ?? false) + { + Utf8JsonReader utf8JsonReaderTriangle = utf8JsonReader; + triangle = JsonSerializer.Deserialize(ref utf8JsonReaderTriangle, jsonSerializerOptions); + } + } + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "shapeType": + shapeType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (shapeType == null) + throw new ArgumentNullException(nameof(shapeType), "Property is required for class Shape."); + + if (quadrilateral != null) + return new Shape(quadrilateral, shapeType); + + if (triangle != null) + return new Shape(triangle, shapeType); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (shape.Quadrilateral != null) { + QuadrilateralJsonConverter quadrilateralJsonConverter = (QuadrilateralJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(shape.Quadrilateral.GetType())); + quadrilateralJsonConverter.WriteProperties(ref writer, shape.Quadrilateral, jsonSerializerOptions); + } + + if (shape.Triangle != null) { + TriangleJsonConverter triangleJsonConverter = (TriangleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(shape.Triangle.GetType())); + triangleJsonConverter.WriteProperties(ref writer, shape.Triangle, jsonSerializerOptions); + } + + WriteProperties(ref writer, shape, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Shape shape, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("shapeType", shape.ShapeType); + } + } + + /// + /// The ShapeSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Shape))] + public partial class ShapeSerializationContext : JsonSerializerContext + { + /// + /// The ShapeSerializationContext + /// + /// + public ShapeSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ShapeDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Shape))] + public partial class ShapeDeserializationContext : JsonSerializerContext + { + /// + /// ShapeDeserializationContext + /// + /// + public ShapeDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeInterface.cs new file mode 100644 index 00000000000..f6237312746 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeInterface.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ShapeInterface + /// + public partial class ShapeInterface : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// shapeType + [JsonConstructor] + public ShapeInterface(string shapeType) + { + ShapeType = shapeType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ShapeType + /// + [JsonPropertyName("shapeType")] + public string ShapeType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ShapeInterface {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ShapeInterfaceJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? shapeType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "shapeType": + shapeType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (shapeType == null) + throw new ArgumentNullException(nameof(shapeType), "Property is required for class ShapeInterface."); + + return new ShapeInterface(shapeType); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShapeInterface shapeInterface, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, shapeInterface, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ShapeInterface shapeInterface, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("shapeType", shapeInterface.ShapeType); + } + } + + /// + /// The ShapeInterfaceSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ShapeInterface))] + public partial class ShapeInterfaceSerializationContext : JsonSerializerContext + { + /// + /// The ShapeInterfaceSerializationContext + /// + /// + public ShapeInterfaceSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ShapeInterfaceDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ShapeInterface))] + public partial class ShapeInterfaceDeserializationContext : JsonSerializerContext + { + /// + /// ShapeInterfaceDeserializationContext + /// + /// + public ShapeInterfaceDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeOrNull.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeOrNull.cs new file mode 100644 index 00000000000..4166ed33308 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeOrNull.cs @@ -0,0 +1,280 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. + /// + public partial class ShapeOrNull : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// shapeType + public ShapeOrNull(Triangle triangle, string shapeType) + { + Triangle = triangle; + ShapeType = shapeType; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// shapeType + public ShapeOrNull(Quadrilateral quadrilateral, string shapeType) + { + Quadrilateral = quadrilateral; + ShapeType = shapeType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Triangle + /// + public Triangle? Triangle { get; set; } + + /// + /// Gets or Sets Quadrilateral + /// + public Quadrilateral? Quadrilateral { get; set; } + + /// + /// Gets or Sets ShapeType + /// + [JsonPropertyName("shapeType")] + public string ShapeType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ShapeOrNull {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ShapeOrNullJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? shapeType = default; + + Quadrilateral? quadrilateral = null; + Triangle? triangle = null; + + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName?.Equals("shapeType") ?? false) + { + string? discriminator = utf8JsonReaderDiscriminator.GetString(); + if (discriminator?.Equals("Quadrilateral") ?? false) + { + Utf8JsonReader utf8JsonReaderQuadrilateral = utf8JsonReader; + quadrilateral = JsonSerializer.Deserialize(ref utf8JsonReaderQuadrilateral, jsonSerializerOptions); + } + if (discriminator?.Equals("Triangle") ?? false) + { + Utf8JsonReader utf8JsonReaderTriangle = utf8JsonReader; + triangle = JsonSerializer.Deserialize(ref utf8JsonReaderTriangle, jsonSerializerOptions); + } + } + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "shapeType": + shapeType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (shapeType == null) + throw new ArgumentNullException(nameof(shapeType), "Property is required for class ShapeOrNull."); + + if (quadrilateral != null) + return new ShapeOrNull(quadrilateral, shapeType); + + if (triangle != null) + return new ShapeOrNull(triangle, shapeType); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (shapeOrNull.Quadrilateral != null) { + QuadrilateralJsonConverter quadrilateralJsonConverter = (QuadrilateralJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(shapeOrNull.Quadrilateral.GetType())); + quadrilateralJsonConverter.WriteProperties(ref writer, shapeOrNull.Quadrilateral, jsonSerializerOptions); + } + + if (shapeOrNull.Triangle != null) { + TriangleJsonConverter triangleJsonConverter = (TriangleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(shapeOrNull.Triangle.GetType())); + triangleJsonConverter.WriteProperties(ref writer, shapeOrNull.Triangle, jsonSerializerOptions); + } + + WriteProperties(ref writer, shapeOrNull, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("shapeType", shapeOrNull.ShapeType); + } + } + + /// + /// The ShapeOrNullSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ShapeOrNull))] + public partial class ShapeOrNullSerializationContext : JsonSerializerContext + { + /// + /// The ShapeOrNullSerializationContext + /// + /// + public ShapeOrNullSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ShapeOrNullDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ShapeOrNull))] + public partial class ShapeOrNullDeserializationContext : JsonSerializerContext + { + /// + /// ShapeOrNullDeserializationContext + /// + /// + public ShapeOrNullDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SimpleQuadrilateral.cs new file mode 100644 index 00000000000..2bee03bd593 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SimpleQuadrilateral.cs @@ -0,0 +1,215 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// SimpleQuadrilateral + /// + public partial class SimpleQuadrilateral : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// quadrilateralType + /// shapeType + [JsonConstructor] + public SimpleQuadrilateral(string quadrilateralType, string shapeType) + { + QuadrilateralType = quadrilateralType; + ShapeType = shapeType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets QuadrilateralType + /// + [JsonPropertyName("quadrilateralType")] + public string QuadrilateralType { get; set; } + + /// + /// Gets or Sets ShapeType + /// + [JsonPropertyName("shapeType")] + public string ShapeType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SimpleQuadrilateral {\n"); + sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SimpleQuadrilateralJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? quadrilateralType = default; + string? shapeType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "quadrilateralType": + quadrilateralType = utf8JsonReader.GetString(); + break; + case "shapeType": + shapeType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (quadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class SimpleQuadrilateral."); + + if (shapeType == null) + throw new ArgumentNullException(nameof(shapeType), "Property is required for class SimpleQuadrilateral."); + + return new SimpleQuadrilateral(quadrilateralType, shapeType); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, simpleQuadrilateral, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("quadrilateralType", simpleQuadrilateral.QuadrilateralType); + writer.WriteString("shapeType", simpleQuadrilateral.ShapeType); + } + } + + /// + /// The SimpleQuadrilateralSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(SimpleQuadrilateral))] + public partial class SimpleQuadrilateralSerializationContext : JsonSerializerContext + { + /// + /// The SimpleQuadrilateralSerializationContext + /// + /// + public SimpleQuadrilateralSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// SimpleQuadrilateralDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(SimpleQuadrilateral))] + public partial class SimpleQuadrilateralDeserializationContext : JsonSerializerContext + { + /// + /// SimpleQuadrilateralDeserializationContext + /// + /// + public SimpleQuadrilateralDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SpecialModelName.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SpecialModelName.cs new file mode 100644 index 00000000000..3b62d460a47 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SpecialModelName.cs @@ -0,0 +1,216 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// SpecialModelName + /// + public partial class SpecialModelName : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// varSpecialModelName + /// specialPropertyName + [JsonConstructor] + public SpecialModelName(string varSpecialModelName, long specialPropertyName) + { + VarSpecialModelName = varSpecialModelName; + SpecialPropertyName = specialPropertyName; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets VarSpecialModelName + /// + [JsonPropertyName("_special_model.name_")] + public string VarSpecialModelName { get; set; } + + /// + /// Gets or Sets SpecialPropertyName + /// + [JsonPropertyName("$special[property.name]")] + public long SpecialPropertyName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SpecialModelName {\n"); + sb.Append(" VarSpecialModelName: ").Append(VarSpecialModelName).Append("\n"); + sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SpecialModelNameJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? varSpecialModelName = default; + long? specialPropertyName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "_special_model.name_": + varSpecialModelName = utf8JsonReader.GetString(); + break; + case "$special[property.name]": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + specialPropertyName = utf8JsonReader.GetInt64(); + break; + default: + break; + } + } + } + + if (varSpecialModelName == null) + throw new ArgumentNullException(nameof(varSpecialModelName), "Property is required for class SpecialModelName."); + + if (specialPropertyName == null) + throw new ArgumentNullException(nameof(specialPropertyName), "Property is required for class SpecialModelName."); + + return new SpecialModelName(varSpecialModelName, specialPropertyName.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SpecialModelName specialModelName, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, specialModelName, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, SpecialModelName specialModelName, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("_special_model.name_", specialModelName.VarSpecialModelName); + writer.WriteNumber("$special[property.name]", specialModelName.SpecialPropertyName); + } + } + + /// + /// The SpecialModelNameSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(SpecialModelName))] + public partial class SpecialModelNameSerializationContext : JsonSerializerContext + { + /// + /// The SpecialModelNameSerializationContext + /// + /// + public SpecialModelNameSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// SpecialModelNameDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(SpecialModelName))] + public partial class SpecialModelNameDeserializationContext : JsonSerializerContext + { + /// + /// SpecialModelNameDeserializationContext + /// + /// + public SpecialModelNameDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Tag.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Tag.cs new file mode 100644 index 00000000000..db53dd6b139 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Tag.cs @@ -0,0 +1,216 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Tag + /// + public partial class Tag : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id + /// name + [JsonConstructor] + public Tag(long id, string name) + { + Id = id; + Name = name; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Tag {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TagJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + long? id = default; + string? name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + id = utf8JsonReader.GetInt64(); + break; + case "name": + name = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (id == null) + throw new ArgumentNullException(nameof(id), "Property is required for class Tag."); + + if (name == null) + throw new ArgumentNullException(nameof(name), "Property is required for class Tag."); + + return new Tag(id.Value, name); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Tag tag, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, tag, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Tag tag, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("id", tag.Id); + writer.WriteString("name", tag.Name); + } + } + + /// + /// The TagSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Tag))] + public partial class TagSerializationContext : JsonSerializerContext + { + /// + /// The TagSerializationContext + /// + /// + public TagSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// TagDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Tag))] + public partial class TagDeserializationContext : JsonSerializerContext + { + /// + /// TagDeserializationContext + /// + /// + public TagDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordList.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordList.cs new file mode 100644 index 00000000000..8083f3c0a78 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordList.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// TestCollectionEndingWithWordList + /// + public partial class TestCollectionEndingWithWordList : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// value + [JsonConstructor] + public TestCollectionEndingWithWordList(string value) + { + Value = value; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Value + /// + [JsonPropertyName("value")] + public string Value { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TestCollectionEndingWithWordList {\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TestCollectionEndingWithWordListJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "value": + value = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (value == null) + throw new ArgumentNullException(nameof(value), "Property is required for class TestCollectionEndingWithWordList."); + + return new TestCollectionEndingWithWordList(value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TestCollectionEndingWithWordList testCollectionEndingWithWordList, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, testCollectionEndingWithWordList, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, TestCollectionEndingWithWordList testCollectionEndingWithWordList, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("value", testCollectionEndingWithWordList.Value); + } + } + + /// + /// The TestCollectionEndingWithWordListSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(TestCollectionEndingWithWordList))] + public partial class TestCollectionEndingWithWordListSerializationContext : JsonSerializerContext + { + /// + /// The TestCollectionEndingWithWordListSerializationContext + /// + /// + public TestCollectionEndingWithWordListSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// TestCollectionEndingWithWordListDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(TestCollectionEndingWithWordList))] + public partial class TestCollectionEndingWithWordListDeserializationContext : JsonSerializerContext + { + /// + /// TestCollectionEndingWithWordListDeserializationContext + /// + /// + public TestCollectionEndingWithWordListDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordListObject.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordListObject.cs new file mode 100644 index 00000000000..6b4a6a6c4fd --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordListObject.cs @@ -0,0 +1,200 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// TestCollectionEndingWithWordListObject + /// + public partial class TestCollectionEndingWithWordListObject : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// testCollectionEndingWithWordList + [JsonConstructor] + public TestCollectionEndingWithWordListObject(List testCollectionEndingWithWordList) + { + TestCollectionEndingWithWordList = testCollectionEndingWithWordList; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets TestCollectionEndingWithWordList + /// + [JsonPropertyName("TestCollectionEndingWithWordList")] + public List TestCollectionEndingWithWordList { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TestCollectionEndingWithWordListObject {\n"); + sb.Append(" TestCollectionEndingWithWordList: ").Append(TestCollectionEndingWithWordList).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TestCollectionEndingWithWordListObjectJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + List? testCollectionEndingWithWordList = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "TestCollectionEndingWithWordList": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + testCollectionEndingWithWordList = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (testCollectionEndingWithWordList == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordList), "Property is required for class TestCollectionEndingWithWordListObject."); + + return new TestCollectionEndingWithWordListObject(testCollectionEndingWithWordList); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TestCollectionEndingWithWordListObject testCollectionEndingWithWordListObject, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, testCollectionEndingWithWordListObject, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, TestCollectionEndingWithWordListObject testCollectionEndingWithWordListObject, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("TestCollectionEndingWithWordList"); + JsonSerializer.Serialize(writer, testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList, jsonSerializerOptions); + } + } + + /// + /// The TestCollectionEndingWithWordListObjectSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(TestCollectionEndingWithWordListObject))] + public partial class TestCollectionEndingWithWordListObjectSerializationContext : JsonSerializerContext + { + /// + /// The TestCollectionEndingWithWordListObjectSerializationContext + /// + /// + public TestCollectionEndingWithWordListObjectSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// TestCollectionEndingWithWordListObjectDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(TestCollectionEndingWithWordListObject))] + public partial class TestCollectionEndingWithWordListObjectDeserializationContext : JsonSerializerContext + { + /// + /// TestCollectionEndingWithWordListObjectDeserializationContext + /// + /// + public TestCollectionEndingWithWordListObjectDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Triangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Triangle.cs new file mode 100644 index 00000000000..c013be07a19 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Triangle.cs @@ -0,0 +1,311 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Triangle + /// + public partial class Triangle : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + /// triangleType + public Triangle(EquilateralTriangle equilateralTriangle, string triangleType) + { + EquilateralTriangle = equilateralTriangle; + TriangleType = triangleType; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// triangleType + public Triangle(IsoscelesTriangle isoscelesTriangle, string triangleType) + { + IsoscelesTriangle = isoscelesTriangle; + TriangleType = triangleType; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// triangleType + public Triangle(ScaleneTriangle scaleneTriangle, string triangleType) + { + ScaleneTriangle = scaleneTriangle; + TriangleType = triangleType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets EquilateralTriangle + /// + public EquilateralTriangle? EquilateralTriangle { get; set; } + + /// + /// Gets or Sets IsoscelesTriangle + /// + public IsoscelesTriangle? IsoscelesTriangle { get; set; } + + /// + /// Gets or Sets ScaleneTriangle + /// + public ScaleneTriangle? ScaleneTriangle { get; set; } + + /// + /// Gets or Sets TriangleType + /// + [JsonPropertyName("triangleType")] + public string TriangleType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Triangle {\n"); + sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TriangleJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? triangleType = default; + + EquilateralTriangle? equilateralTriangle = null; + IsoscelesTriangle? isoscelesTriangle = null; + ScaleneTriangle? scaleneTriangle = null; + + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName?.Equals("triangleType") ?? false) + { + string? discriminator = utf8JsonReaderDiscriminator.GetString(); + if (discriminator?.Equals("EquilateralTriangle") ?? false) + { + Utf8JsonReader utf8JsonReaderEquilateralTriangle = utf8JsonReader; + equilateralTriangle = JsonSerializer.Deserialize(ref utf8JsonReaderEquilateralTriangle, jsonSerializerOptions); + } + if (discriminator?.Equals("IsoscelesTriangle") ?? false) + { + Utf8JsonReader utf8JsonReaderIsoscelesTriangle = utf8JsonReader; + isoscelesTriangle = JsonSerializer.Deserialize(ref utf8JsonReaderIsoscelesTriangle, jsonSerializerOptions); + } + if (discriminator?.Equals("ScaleneTriangle") ?? false) + { + Utf8JsonReader utf8JsonReaderScaleneTriangle = utf8JsonReader; + scaleneTriangle = JsonSerializer.Deserialize(ref utf8JsonReaderScaleneTriangle, jsonSerializerOptions); + } + } + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "triangleType": + triangleType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (triangleType == null) + throw new ArgumentNullException(nameof(triangleType), "Property is required for class Triangle."); + + if (equilateralTriangle != null) + return new Triangle(equilateralTriangle, triangleType); + + if (isoscelesTriangle != null) + return new Triangle(isoscelesTriangle, triangleType); + + if (scaleneTriangle != null) + return new Triangle(scaleneTriangle, triangleType); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (triangle.EquilateralTriangle != null) { + EquilateralTriangleJsonConverter equilateralTriangleJsonConverter = (EquilateralTriangleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(triangle.EquilateralTriangle.GetType())); + equilateralTriangleJsonConverter.WriteProperties(ref writer, triangle.EquilateralTriangle, jsonSerializerOptions); + } + + if (triangle.IsoscelesTriangle != null) { + IsoscelesTriangleJsonConverter isoscelesTriangleJsonConverter = (IsoscelesTriangleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(triangle.IsoscelesTriangle.GetType())); + isoscelesTriangleJsonConverter.WriteProperties(ref writer, triangle.IsoscelesTriangle, jsonSerializerOptions); + } + + if (triangle.ScaleneTriangle != null) { + ScaleneTriangleJsonConverter scaleneTriangleJsonConverter = (ScaleneTriangleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(triangle.ScaleneTriangle.GetType())); + scaleneTriangleJsonConverter.WriteProperties(ref writer, triangle.ScaleneTriangle, jsonSerializerOptions); + } + + WriteProperties(ref writer, triangle, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("triangleType", triangle.TriangleType); + } + } + + /// + /// The TriangleSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Triangle))] + public partial class TriangleSerializationContext : JsonSerializerContext + { + /// + /// The TriangleSerializationContext + /// + /// + public TriangleSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// TriangleDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Triangle))] + public partial class TriangleDeserializationContext : JsonSerializerContext + { + /// + /// TriangleDeserializationContext + /// + /// + public TriangleDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TriangleInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TriangleInterface.cs new file mode 100644 index 00000000000..cea3122195b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TriangleInterface.cs @@ -0,0 +1,198 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// TriangleInterface + /// + public partial class TriangleInterface : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// triangleType + [JsonConstructor] + public TriangleInterface(string triangleType) + { + TriangleType = triangleType; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets TriangleType + /// + [JsonPropertyName("triangleType")] + public string TriangleType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TriangleInterface {\n"); + sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TriangleInterfaceJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? triangleType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "triangleType": + triangleType = utf8JsonReader.GetString(); + break; + default: + break; + } + } + } + + if (triangleType == null) + throw new ArgumentNullException(nameof(triangleType), "Property is required for class TriangleInterface."); + + return new TriangleInterface(triangleType); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TriangleInterface triangleInterface, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, triangleInterface, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, TriangleInterface triangleInterface, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("triangleType", triangleInterface.TriangleType); + } + } + + /// + /// The TriangleInterfaceSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(TriangleInterface))] + public partial class TriangleInterfaceSerializationContext : JsonSerializerContext + { + /// + /// The TriangleInterfaceSerializationContext + /// + /// + public TriangleInterfaceSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// TriangleInterfaceDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(TriangleInterface))] + public partial class TriangleInterfaceDeserializationContext : JsonSerializerContext + { + /// + /// TriangleInterfaceDeserializationContext + /// + /// + public TriangleInterfaceDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/User.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/User.cs new file mode 100644 index 00000000000..0c72a6460e5 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/User.cs @@ -0,0 +1,391 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// User + /// + public partial class User : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// email + /// firstName + /// id + /// lastName + /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + /// password + /// phone + /// User Status + /// username + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + [JsonConstructor] + public User(string email, string firstName, long id, string lastName, Object objectWithNoDeclaredProps, string password, string phone, int userStatus, string username, Object? anyTypeProp = default, Object? anyTypePropNullable = default, Object? objectWithNoDeclaredPropsNullable = default) + { + Email = email; + FirstName = firstName; + Id = id; + LastName = lastName; + ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; + Password = password; + Phone = phone; + UserStatus = userStatus; + Username = username; + AnyTypeProp = anyTypeProp; + AnyTypePropNullable = anyTypePropNullable; + ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Email + /// + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// Gets or Sets FirstName + /// + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public long Id { get; set; } + + /// + /// Gets or Sets LastName + /// + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + /// + /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + [JsonPropertyName("objectWithNoDeclaredProps")] + public Object ObjectWithNoDeclaredProps { get; set; } + + /// + /// Gets or Sets Password + /// + [JsonPropertyName("password")] + public string Password { get; set; } + + /// + /// Gets or Sets Phone + /// + [JsonPropertyName("phone")] + public string Phone { get; set; } + + /// + /// User Status + /// + /// User Status + [JsonPropertyName("userStatus")] + public int UserStatus { get; set; } + + /// + /// Gets or Sets Username + /// + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + [JsonPropertyName("anyTypeProp")] + public Object? AnyTypeProp { get; set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + [JsonPropertyName("anyTypePropNullable")] + public Object? AnyTypePropNullable { get; set; } + + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + [JsonPropertyName("objectWithNoDeclaredPropsNullable")] + public Object? ObjectWithNoDeclaredPropsNullable { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class User {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" ObjectWithNoDeclaredProps: ").Append(ObjectWithNoDeclaredProps).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); + sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).Append("\n"); + sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UserJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? email = default; + string? firstName = default; + long? id = default; + string? lastName = default; + Object? objectWithNoDeclaredProps = default; + string? password = default; + string? phone = default; + int? userStatus = default; + string? username = default; + Object? anyTypeProp = default; + Object? anyTypePropNullable = default; + Object? objectWithNoDeclaredPropsNullable = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "email": + email = utf8JsonReader.GetString(); + break; + case "firstName": + firstName = utf8JsonReader.GetString(); + break; + case "id": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + id = utf8JsonReader.GetInt64(); + break; + case "lastName": + lastName = utf8JsonReader.GetString(); + break; + case "objectWithNoDeclaredProps": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectWithNoDeclaredProps = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "password": + password = utf8JsonReader.GetString(); + break; + case "phone": + phone = utf8JsonReader.GetString(); + break; + case "userStatus": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + userStatus = utf8JsonReader.GetInt32(); + break; + case "username": + username = utf8JsonReader.GetString(); + break; + case "anyTypeProp": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anyTypeProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "anyTypePropNullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anyTypePropNullable = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + case "objectWithNoDeclaredPropsNullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectWithNoDeclaredPropsNullable = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + break; + default: + break; + } + } + } + + if (email == null) + throw new ArgumentNullException(nameof(email), "Property is required for class User."); + + if (firstName == null) + throw new ArgumentNullException(nameof(firstName), "Property is required for class User."); + + if (id == null) + throw new ArgumentNullException(nameof(id), "Property is required for class User."); + + if (lastName == null) + throw new ArgumentNullException(nameof(lastName), "Property is required for class User."); + + if (objectWithNoDeclaredProps == null) + throw new ArgumentNullException(nameof(objectWithNoDeclaredProps), "Property is required for class User."); + + if (password == null) + throw new ArgumentNullException(nameof(password), "Property is required for class User."); + + if (phone == null) + throw new ArgumentNullException(nameof(phone), "Property is required for class User."); + + if (userStatus == null) + throw new ArgumentNullException(nameof(userStatus), "Property is required for class User."); + + if (username == null) + throw new ArgumentNullException(nameof(username), "Property is required for class User."); + + return new User(email, firstName, id.Value, lastName, objectWithNoDeclaredProps, password, phone, userStatus.Value, username, anyTypeProp, anyTypePropNullable, objectWithNoDeclaredPropsNullable); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, User user, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, user, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, User user, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("email", user.Email); + writer.WriteString("firstName", user.FirstName); + writer.WriteNumber("id", user.Id); + writer.WriteString("lastName", user.LastName); + writer.WritePropertyName("objectWithNoDeclaredProps"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, jsonSerializerOptions); + writer.WriteString("password", user.Password); + writer.WriteString("phone", user.Phone); + writer.WriteNumber("userStatus", user.UserStatus); + writer.WriteString("username", user.Username); + writer.WritePropertyName("anyTypeProp"); + JsonSerializer.Serialize(writer, user.AnyTypeProp, jsonSerializerOptions); + writer.WritePropertyName("anyTypePropNullable"); + JsonSerializer.Serialize(writer, user.AnyTypePropNullable, jsonSerializerOptions); + writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, jsonSerializerOptions); + } + } + + /// + /// The UserSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(User))] + public partial class UserSerializationContext : JsonSerializerContext + { + /// + /// The UserSerializationContext + /// + /// + public UserSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// UserDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(User))] + public partial class UserDeserializationContext : JsonSerializerContext + { + /// + /// UserDeserializationContext + /// + /// + public UserDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Whale.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Whale.cs new file mode 100644 index 00000000000..145c238351a --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Whale.cs @@ -0,0 +1,234 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Whale + /// + public partial class Whale : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// className + /// hasBaleen + /// hasTeeth + [JsonConstructor] + public Whale(string className, bool hasBaleen, bool hasTeeth) + { + ClassName = className; + HasBaleen = hasBaleen; + HasTeeth = hasTeeth; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets ClassName + /// + [JsonPropertyName("className")] + public string ClassName { get; set; } + + /// + /// Gets or Sets HasBaleen + /// + [JsonPropertyName("hasBaleen")] + public bool HasBaleen { get; set; } + + /// + /// Gets or Sets HasTeeth + /// + [JsonPropertyName("hasTeeth")] + public bool HasTeeth { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Whale {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" HasBaleen: ").Append(HasBaleen).Append("\n"); + sb.Append(" HasTeeth: ").Append(HasTeeth).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WhaleJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? className = default; + bool? hasBaleen = default; + bool? hasTeeth = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "className": + className = utf8JsonReader.GetString(); + break; + case "hasBaleen": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + hasBaleen = utf8JsonReader.GetBoolean(); + break; + case "hasTeeth": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + hasTeeth = utf8JsonReader.GetBoolean(); + break; + default: + break; + } + } + } + + if (className == null) + throw new ArgumentNullException(nameof(className), "Property is required for class Whale."); + + if (hasBaleen == null) + throw new ArgumentNullException(nameof(hasBaleen), "Property is required for class Whale."); + + if (hasTeeth == null) + throw new ArgumentNullException(nameof(hasTeeth), "Property is required for class Whale."); + + return new Whale(className, hasBaleen.Value, hasTeeth.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Whale whale, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, whale, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Whale whale, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("className", whale.ClassName); + writer.WriteBoolean("hasBaleen", whale.HasBaleen); + writer.WriteBoolean("hasTeeth", whale.HasTeeth); + } + } + + /// + /// The WhaleSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Whale))] + public partial class WhaleSerializationContext : JsonSerializerContext + { + /// + /// The WhaleSerializationContext + /// + /// + public WhaleSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// WhaleDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Whale))] + public partial class WhaleDeserializationContext : JsonSerializerContext + { + /// + /// WhaleDeserializationContext + /// + /// + public WhaleDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Zebra.cs new file mode 100644 index 00000000000..13ba96492f4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Zebra.cs @@ -0,0 +1,314 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Zebra + /// + public partial class Zebra : Dictionary, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// className + /// type + [JsonConstructor] + public Zebra(string className, TypeEnum type) : base() + { + ClassName = className; + Type = type; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Defines Type + /// + public enum TypeEnum + { + /// + /// Enum Plains for value: plains + /// + Plains = 1, + + /// + /// Enum Mountain for value: mountain + /// + Mountain = 2, + + /// + /// Enum Grevys for value: grevys + /// + Grevys = 3 + } + + /// + /// Returns a + /// + /// + /// + /// + public static TypeEnum TypeEnumFromString(string value) + { + if (value.Equals("plains")) + return TypeEnum.Plains; + + if (value.Equals("mountain")) + return TypeEnum.Mountain; + + if (value.Equals("grevys")) + return TypeEnum.Grevys; + + throw new NotImplementedException($"Could not convert value to type TypeEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static TypeEnum? TypeEnumFromStringOrDefault(string value) + { + if (value.Equals("plains")) + return TypeEnum.Plains; + + if (value.Equals("mountain")) + return TypeEnum.Mountain; + + if (value.Equals("grevys")) + return TypeEnum.Grevys; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string TypeEnumToJsonValue(TypeEnum value) + { + if (value == TypeEnum.Plains) + return "plains"; + + if (value == TypeEnum.Mountain) + return "mountain"; + + if (value == TypeEnum.Grevys) + return "grevys"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets Type + /// + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Gets or Sets ClassName + /// + [JsonPropertyName("className")] + public string ClassName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Zebra {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ZebraJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + string? className = default; + Zebra.TypeEnum? type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "className": + className = utf8JsonReader.GetString(); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = typeRawValue == null + ? null + : Zebra.TypeEnumFromStringOrDefault(typeRawValue); + break; + default: + break; + } + } + } + + if (className == null) + throw new ArgumentNullException(nameof(className), "Property is required for class Zebra."); + + if (type == null) + throw new ArgumentNullException(nameof(type), "Property is required for class Zebra."); + + return new Zebra(className, type.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Zebra zebra, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, zebra, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, Zebra zebra, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteString("className", zebra.ClassName); + + var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.Type); + if (typeRawValue != null) + writer.WriteString("type", typeRawValue); + else + writer.WriteNull("type"); + } + } + + /// + /// The ZebraSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(Zebra))] + public partial class ZebraSerializationContext : JsonSerializerContext + { + /// + /// The ZebraSerializationContext + /// + /// + public ZebraSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ZebraDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(Zebra))] + public partial class ZebraDeserializationContext : JsonSerializerContext + { + /// + /// ZebraDeserializationContext + /// + /// + public ZebraDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ZeroBasedEnum.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ZeroBasedEnum.cs new file mode 100644 index 00000000000..53b58db3e06 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ZeroBasedEnum.cs @@ -0,0 +1,210 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// Defines ZeroBasedEnum + /// + public enum ZeroBasedEnum + { + /// + /// Enum Unknown for value: unknown + /// + Unknown, + + /// + /// Enum NotUnknown for value: notUnknown + /// + NotUnknown + } + + /// + /// Converts to and from the JSON value + /// + public static class ZeroBasedEnumValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static ZeroBasedEnum FromString(string value) + { + if (value.Equals("unknown")) + return ZeroBasedEnum.Unknown; + + if (value.Equals("notUnknown")) + return ZeroBasedEnum.NotUnknown; + + throw new NotImplementedException($"Could not convert value to type ZeroBasedEnum: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static ZeroBasedEnum? FromStringOrDefault(string value) + { + if (value.Equals("unknown")) + return ZeroBasedEnum.Unknown; + + if (value.Equals("notUnknown")) + return ZeroBasedEnum.NotUnknown; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(ZeroBasedEnum value) + { + if (value == ZeroBasedEnum.Unknown) + return "unknown"; + + if (value == ZeroBasedEnum.NotUnknown) + return "notUnknown"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ZeroBasedEnumJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override ZeroBasedEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ZeroBasedEnum? result = rawValue == null + ? null + : ZeroBasedEnumValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ZeroBasedEnum to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ZeroBasedEnum zeroBasedEnum, JsonSerializerOptions options) + { + writer.WriteStringValue(zeroBasedEnum.ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ZeroBasedEnumNullableJsonConverter : JsonConverter + { + /// + /// Returns a ZeroBasedEnum from the Json object + /// + /// + /// + /// + /// + public override ZeroBasedEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ZeroBasedEnum? result = rawValue == null + ? null + : ZeroBasedEnumValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ZeroBasedEnum? zeroBasedEnum, JsonSerializerOptions options) + { + writer.WriteStringValue(zeroBasedEnum?.ToString() ?? "null"); + } + } + + + /// + /// The ZeroBasedEnumSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ZeroBasedEnum))] + public partial class ZeroBasedEnumSerializationContext : JsonSerializerContext + { + /// + /// The ZeroBasedEnumSerializationContext + /// + /// + public ZeroBasedEnumSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ZeroBasedEnumDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ZeroBasedEnum))] + public partial class ZeroBasedEnumDeserializationContext : JsonSerializerContext + { + /// + /// ZeroBasedEnumDeserializationContext + /// + /// + public ZeroBasedEnumDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ZeroBasedEnumClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ZeroBasedEnumClass.cs new file mode 100644 index 00000000000..502739fecd3 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ZeroBasedEnumClass.cs @@ -0,0 +1,272 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// ZeroBasedEnumClass + /// + public partial class ZeroBasedEnumClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// zeroBasedEnum + [JsonConstructor] + public ZeroBasedEnumClass(ZeroBasedEnumEnum zeroBasedEnum) + { + ZeroBasedEnum = zeroBasedEnum; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Defines ZeroBasedEnum + /// + public enum ZeroBasedEnumEnum + { + /// + /// Enum Unknown for value: unknown + /// + Unknown, + + /// + /// Enum NotUnknown for value: notUnknown + /// + NotUnknown + } + + /// + /// Returns a + /// + /// + /// + /// + public static ZeroBasedEnumEnum ZeroBasedEnumEnumFromString(string value) + { + if (value.Equals("unknown")) + return ZeroBasedEnumEnum.Unknown; + + if (value.Equals("notUnknown")) + return ZeroBasedEnumEnum.NotUnknown; + + throw new NotImplementedException($"Could not convert value to type ZeroBasedEnumEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static ZeroBasedEnumEnum? ZeroBasedEnumEnumFromStringOrDefault(string value) + { + if (value.Equals("unknown")) + return ZeroBasedEnumEnum.Unknown; + + if (value.Equals("notUnknown")) + return ZeroBasedEnumEnum.NotUnknown; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum value) + { + if (value == ZeroBasedEnumEnum.Unknown) + return "unknown"; + + if (value == ZeroBasedEnumEnum.NotUnknown) + return "notUnknown"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets ZeroBasedEnum + /// + [JsonPropertyName("ZeroBasedEnum")] + public ZeroBasedEnumEnum ZeroBasedEnum { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ZeroBasedEnumClass {\n"); + sb.Append(" ZeroBasedEnum: ").Append(ZeroBasedEnum).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ZeroBasedEnumClassJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + ZeroBasedEnumClass.ZeroBasedEnumEnum? zeroBasedEnum = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "ZeroBasedEnum": + string? zeroBasedEnumRawValue = utf8JsonReader.GetString(); + zeroBasedEnum = zeroBasedEnumRawValue == null + ? null + : ZeroBasedEnumClass.ZeroBasedEnumEnumFromStringOrDefault(zeroBasedEnumRawValue); + break; + default: + break; + } + } + } + + if (zeroBasedEnum == null) + throw new ArgumentNullException(nameof(zeroBasedEnum), "Property is required for class ZeroBasedEnumClass."); + + return new ZeroBasedEnumClass(zeroBasedEnum.Value); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ZeroBasedEnumClass zeroBasedEnumClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, zeroBasedEnumClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, ZeroBasedEnumClass zeroBasedEnumClass, JsonSerializerOptions jsonSerializerOptions) + { + + var zeroBasedEnumRawValue = ZeroBasedEnumClass.ZeroBasedEnumEnumToJsonValue(zeroBasedEnumClass.ZeroBasedEnum); + if (zeroBasedEnumRawValue != null) + writer.WriteString("ZeroBasedEnum", zeroBasedEnumRawValue); + else + writer.WriteNull("ZeroBasedEnum"); + } + } + + /// + /// The ZeroBasedEnumClassSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(ZeroBasedEnumClass))] + public partial class ZeroBasedEnumClassSerializationContext : JsonSerializerContext + { + /// + /// The ZeroBasedEnumClassSerializationContext + /// + /// + public ZeroBasedEnumClassSerializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } + + /// + /// ZeroBasedEnumClassDeserializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] + [JsonSerializable(typeof(ZeroBasedEnumClass))] + public partial class ZeroBasedEnumClassDeserializationContext : JsonSerializerContext + { + /// + /// ZeroBasedEnumClassDeserializationContext + /// + /// + public ZeroBasedEnumClassDeserializationContext(JsonSerializerOptionsProvider optionsProvider): base(new(optionsProvider.Options)) + { + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/README.md new file mode 100644 index 00000000000..c745a961604 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/README.md @@ -0,0 +1,258 @@ +# Created with Openapi Generator + + +## Run the following powershell command to generate the library + +```ps1 +$properties = @( + 'apiName=Api', + 'targetFramework=net7.0', + 'validatable=true', + 'nullableReferenceTypes=true', + 'hideGenerationTimestamp=true', + 'packageVersion=1.0.0', + 'packageAuthors=OpenAPI', + 'packageCompany=OpenAPI', + 'packageCopyright=No Copyright', + 'packageDescription=A library generated from a OpenAPI doc', + 'packageName=UseSourceGeneration', + 'packageTags=', + 'packageTitle=OpenAPI Library' +) -join "," + +$global = @( + 'apiDocs=true', + 'modelDocs=true', + 'apiTests=true', + 'modelTests=true' +) -join "," + +java -jar "/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar" generate ` + -g csharp-netcore ` + -i .yaml ` + -o ` + --library generichost ` + --additional-properties $properties ` + --global-property $global ` + --git-host "github.com" ` + --git-repo-id "GIT_REPO_ID" ` + --git-user-id "GIT_USER_ID" ` + --release-note "Minor update" + # -t templates +``` + + +## Using the library in your project + +```cs +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + var api = host.Services.GetRequiredService(); + ApiResponse response = await api.Call123TestSpecialTagsAsync("todo"); + ModelClient model = response.AsModel(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, options) => + { + // the type of token here depends on the api security specifications + ApiKeyToken token = new(""); + options.AddTokens(token); + + // optionally choose the method the tokens will be provided with, default is RateLimitProvider + options.UseProvider, ApiKeyToken>(); + + // the type of token here depends on the api security specifications + ApiKeyToken token = new(""); + options.AddTokens(token); + + // optionally choose the method the tokens will be provided with, default is RateLimitProvider + options.UseProvider, ApiKeyToken>(); + + // the type of token here depends on the api security specifications + ApiKeyToken token = new(""); + options.AddTokens(token); + + // optionally choose the method the tokens will be provided with, default is RateLimitProvider + options.UseProvider, ApiKeyToken>(); + + // the type of token here depends on the api security specifications + ApiKeyToken token = new(""); + options.AddTokens(token); + + // optionally choose the method the tokens will be provided with, default is RateLimitProvider + options.UseProvider, ApiKeyToken>(); + + // the type of token here depends on the api security specifications + ApiKeyToken token = new(""); + options.AddTokens(token); + + // optionally choose the method the tokens will be provided with, default is RateLimitProvider + options.UseProvider, ApiKeyToken>(); + + // the type of token here depends on the api security specifications + ApiKeyToken token = new(""); + options.AddTokens(token); + + // optionally choose the method the tokens will be provided with, default is RateLimitProvider + options.UseProvider, ApiKeyToken>(); + + options.ConfigureJsonOptions((jsonOptions) => + { + // your custom converters if any + }); + + options.AddApiHttpClients(builder: builder => builder + .AddRetryPolicy(2) + .AddTimeoutPolicy(TimeSpan.FromSeconds(5)) + .AddCircuitBreakerPolicy(10, TimeSpan.FromSeconds(30)) + // add whatever middleware you prefer + ); + }); + } +} +``` + +## Questions + +- What about HttpRequest failures and retries? + If supportsRetry is enabled, you can configure Polly in the ConfigureClients method. +- How are tokens used? + Tokens are provided by a TokenProvider class. The default is RateLimitProvider which will perform client side rate limiting. + Other providers can be used with the UseProvider method. +- Does an HttpRequest throw an error when the server response is not Ok? + It depends how you made the request. If the return type is ApiResponse no error will be thrown, though the Content property will be null. + StatusCode and ReasonPhrase will contain information about the error. + If the return type is T, then it will throw. If the return type is TOrDefault, it will return null. +- How do I validate requests and process responses? + Use the provided On and After methods in the Api class from the namespace UseSourceGeneration.Rest.DefaultApi. + Or provide your own class by using the generic ConfigureApi method. + + +## Dependencies + +- [Microsoft.Extensions.Hosting](https://www.nuget.org/packages/Microsoft.Extensions.Hosting/) - 5.0.0 or later +- [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/) - 5.0.0 or later +- [Microsoft.Extensions.Http.Polly](https://www.nuget.org/packages/Microsoft.Extensions.Http.Polly/) - 5.0.1 or later +- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 4.7.0 or later + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: +- write:pets: modify pets in your account +- read:pets: read your pets + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + + +### http_basic_test + +- **Type**: HTTP basic authentication + + +### bearer_test + +- **Type**: Bearer Authentication + + +### http_signature_test + +- **Type**: HTTP signature authentication + + +## Build +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpClientCodegen + +## Api Information +- appName: OpenAPI Petstore +- appVersion: 1.0.0 +- appDescription: This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +## [OpenApi Global properties](https://openapi-generator.tech/docs/globals) +- generateAliasAsModel: +- supportingFiles: +- models: omitted for brevity +- apis: omitted for brevity +- apiDocs: true +- modelDocs: true +- apiTests: true +- modelTests: true +- withXml: + +## [OpenApi Generator Parameters](https://openapi-generator.tech/docs/generators/csharp-netcore) +- allowUnicodeIdentifiers: +- apiName: Api +- caseInsensitiveResponseHeaders: +- conditionalSerialization: false +- disallowAdditionalPropertiesIfNotPresent: false +- gitHost: github.com +- gitRepoId: GIT_REPO_ID +- gitUserId: GIT_USER_ID +- hideGenerationTimestamp: true +- interfacePrefix: I +- library: generichost +- licenseId: +- modelPropertyNaming: +- netCoreProjectFile: false +- nonPublicApi: false +- nullableReferenceTypes: true +- optionalAssemblyInfo: +- optionalEmitDefaultValues: false +- optionalMethodArgument: true +- optionalProjectFile: +- packageAuthors: OpenAPI +- packageCompany: OpenAPI +- packageCopyright: No Copyright +- packageDescription: A library generated from a OpenAPI doc +- packageGuid: {321C8C3F-0156-40C1-AE42-D59761FB9B6C} +- packageName: UseSourceGeneration +- packageTags: +- packageTitle: OpenAPI Library +- packageVersion: 1.0.0 +- releaseNote: Minor update +- returnICollection: false +- sortParamsByRequiredFlag: +- sourceFolder: src +- targetFramework: net7.0 +- useCollection: false +- useDateTimeOffset: false +- useOneOfDiscriminatorLookup: false +- validatable: true + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project. diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/UseSourceGeneration.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/UseSourceGeneration.csproj new file mode 100644 index 00000000000..60dd69fbf95 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/UseSourceGeneration.csproj @@ -0,0 +1,30 @@ + + + + true + net7.0 + UseSourceGeneration + UseSourceGeneration + Library + OpenAPI + OpenAPI + OpenAPI Library + A library generated from a OpenAPI doc + No Copyright + UseSourceGeneration + 1.0.0 + bin\$(Configuration)\$(TargetFramework)\UseSourceGeneration.xml + https://github.com/GIT_USER_ID/GIT_REPO_ID.git + git + Minor update + enable + + + + + + + + + +